1 //===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file declares a class to represent arbitrary precision floating point
11 /// values and provide a variety of arithmetic operations on them.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ADT_APFLOAT_H
16 #define LLVM_ADT_APFLOAT_H
17
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/FloatingPointMode.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/float128.h"
24 #include <memory>
25
26 #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
27 do { \
28 if (usesLayout<IEEEFloat>(getSemantics())) \
29 return U.IEEE.METHOD_CALL; \
30 if (usesLayout<DoubleAPFloat>(getSemantics())) \
31 return U.Double.METHOD_CALL; \
32 llvm_unreachable("Unexpected semantics"); \
33 } while (false)
34
35 namespace llvm {
36
37 struct fltSemantics;
38 class APSInt;
39 class StringRef;
40 class APFloat;
41 class raw_ostream;
42
43 template <typename T> class Expected;
44 template <typename T> class SmallVectorImpl;
45
46 /// Enum that represents what fraction of the LSB truncated bits of an fp number
47 /// represent.
48 ///
49 /// This essentially combines the roles of guard and sticky bits.
50 enum lostFraction { // Example of truncated bits:
51 lfExactlyZero, // 000000
52 lfLessThanHalf, // 0xxxxx x's not all zero
53 lfExactlyHalf, // 100000
54 lfMoreThanHalf // 1xxxxx x's not all zero
55 };
56
57 /// A self-contained host- and target-independent arbitrary-precision
58 /// floating-point software implementation.
59 ///
60 /// APFloat uses bignum integer arithmetic as provided by static functions in
61 /// the APInt class. The library will work with bignum integers whose parts are
62 /// any unsigned type at least 16 bits wide, but 64 bits is recommended.
63 ///
64 /// Written for clarity rather than speed, in particular with a view to use in
65 /// the front-end of a cross compiler so that target arithmetic can be correctly
66 /// performed on the host. Performance should nonetheless be reasonable,
67 /// particularly for its intended use. It may be useful as a base
68 /// implementation for a run-time library during development of a faster
69 /// target-specific one.
70 ///
71 /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all
72 /// implemented operations. Currently implemented operations are add, subtract,
73 /// multiply, divide, fused-multiply-add, conversion-to-float,
74 /// conversion-to-integer and conversion-from-integer. New rounding modes
75 /// (e.g. away from zero) can be added with three or four lines of code.
76 ///
77 /// Four formats are built-in: IEEE single precision, double precision,
78 /// quadruple precision, and x87 80-bit extended double (when operating with
79 /// full extended precision). Adding a new format that obeys IEEE semantics
80 /// only requires adding two lines of code: a declaration and definition of the
81 /// format.
82 ///
83 /// All operations return the status of that operation as an exception bit-mask,
84 /// so multiple operations can be done consecutively with their results or-ed
85 /// together. The returned status can be useful for compiler diagnostics; e.g.,
86 /// inexact, underflow and overflow can be easily diagnosed on constant folding,
87 /// and compiler optimizers can determine what exceptions would be raised by
88 /// folding operations and optimize, or perhaps not optimize, accordingly.
89 ///
90 /// At present, underflow tininess is detected after rounding; it should be
91 /// straight forward to add support for the before-rounding case too.
92 ///
93 /// The library reads hexadecimal floating point numbers as per C99, and
94 /// correctly rounds if necessary according to the specified rounding mode.
95 /// Syntax is required to have been validated by the caller. It also converts
96 /// floating point numbers to hexadecimal text as per the C99 %a and %A
97 /// conversions. The output precision (or alternatively the natural minimal
98 /// precision) can be specified; if the requested precision is less than the
99 /// natural precision the output is correctly rounded for the specified rounding
100 /// mode.
101 ///
102 /// It also reads decimal floating point numbers and correctly rounds according
103 /// to the specified rounding mode.
104 ///
105 /// Conversion to decimal text is not currently implemented.
106 ///
107 /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit
108 /// signed exponent, and the significand as an array of integer parts. After
109 /// normalization of a number of precision P the exponent is within the range of
110 /// the format, and if the number is not denormal the P-th bit of the
111 /// significand is set as an explicit integer bit. For denormals the most
112 /// significant bit is shifted right so that the exponent is maintained at the
113 /// format's minimum, so that the smallest denormal has just the least
114 /// significant bit of the significand set. The sign of zeroes and infinities
115 /// is significant; the exponent and significand of such numbers is not stored,
116 /// but has a known implicit (deterministic) value: 0 for the significands, 0
117 /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and
118 /// significand are deterministic, although not really meaningful, and preserved
119 /// in non-conversion operations. The exponent is implicitly all 1 bits.
120 ///
121 /// APFloat does not provide any exception handling beyond default exception
122 /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause
123 /// by encoding Signaling NaNs with the first bit of its trailing significand as
124 /// 0.
125 ///
126 /// TODO
127 /// ====
128 ///
129 /// Some features that may or may not be worth adding:
130 ///
131 /// Binary to decimal conversion (hard).
132 ///
133 /// Optional ability to detect underflow tininess before rounding.
134 ///
135 /// New formats: x87 in single and double precision mode (IEEE apart from
136 /// extended exponent range) (hard).
137 ///
138 /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward.
139 ///
140
141 // This is the common type definitions shared by APFloat and its internal
142 // implementation classes. This struct should not define any non-static data
143 // members.
144 struct APFloatBase {
145 typedef APInt::WordType integerPart;
146 static constexpr unsigned integerPartWidth = APInt::APINT_BITS_PER_WORD;
147
148 /// A signed type to represent a floating point numbers unbiased exponent.
149 typedef int32_t ExponentType;
150
151 /// \name Floating Point Semantics.
152 /// @{
153 enum Semantics {
154 S_IEEEhalf,
155 S_BFloat,
156 S_IEEEsingle,
157 S_IEEEdouble,
158 S_IEEEquad,
159 // The IBM double-double semantics. Such a number consists of a pair of
160 // IEEE 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
161 // (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
162 // Therefore it has two 53-bit mantissa parts that aren't necessarily
163 // adjacent to each other, and two 11-bit exponents.
164 //
165 // Note: we need to make the value different from semBogus as otherwise
166 // an unsafe optimization may collapse both values to a single address,
167 // and we heavily rely on them having distinct addresses.
168 S_PPCDoubleDouble,
169 // These are legacy semantics for the fallback, inaccurate implementation
170 // of IBM double-double, if the accurate semPPCDoubleDouble doesn't handle
171 // the operation. It's equivalent to having an IEEE number with consecutive
172 // 106 bits of mantissa and 11 bits of exponent.
173 //
174 // It's not equivalent to IBM double-double. For example, a legit IBM
175 // double-double, 1 + epsilon:
176 //
177 // 1 + epsilon = 1 + (1 >> 1076)
178 //
179 // is not representable by a consecutive 106 bits of mantissa.
180 //
181 // Currently, these semantics are used in the following way:
182 //
183 // semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
184 // (64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
185 // semPPCDoubleDoubleLegacy -> IEEE operations
186 //
187 // We use bitcastToAPInt() to get the bit representation (in APInt) of the
188 // underlying IEEEdouble, then use the APInt constructor to construct the
189 // legacy IEEE float.
190 //
191 // TODO: Implement all operations in semPPCDoubleDouble, and delete these
192 // semantics.
193 S_PPCDoubleDoubleLegacy,
194 // 8-bit floating point number following IEEE-754 conventions with bit
195 // layout S1E5M2 as described in https://arxiv.org/abs/2209.05433.
196 S_Float8E5M2,
197 // 8-bit floating point number mostly following IEEE-754 conventions
198 // and bit layout S1E5M2 described in https://arxiv.org/abs/2206.02915,
199 // with expanded range and with no infinity or signed zero.
200 // NaN is represented as negative zero. (FN -> Finite, UZ -> unsigned zero).
201 // This format's exponent bias is 16, instead of the 15 (2 ** (5 - 1) - 1)
202 // that IEEE precedent would imply.
203 S_Float8E5M2FNUZ,
204 // 8-bit floating point number following IEEE-754 conventions with bit
205 // layout S1E4M3.
206 S_Float8E4M3,
207 // 8-bit floating point number mostly following IEEE-754 conventions with
208 // bit layout S1E4M3 as described in https://arxiv.org/abs/2209.05433.
209 // Unlike IEEE-754 types, there are no infinity values, and NaN is
210 // represented with the exponent and mantissa bits set to all 1s.
211 S_Float8E4M3FN,
212 // 8-bit floating point number mostly following IEEE-754 conventions
213 // and bit layout S1E4M3 described in https://arxiv.org/abs/2206.02915,
214 // with expanded range and with no infinity or signed zero.
215 // NaN is represented as negative zero. (FN -> Finite, UZ -> unsigned zero).
216 // This format's exponent bias is 8, instead of the 7 (2 ** (4 - 1) - 1)
217 // that IEEE precedent would imply.
218 S_Float8E4M3FNUZ,
219 // 8-bit floating point number mostly following IEEE-754 conventions
220 // and bit layout S1E4M3 with expanded range and with no infinity or signed
221 // zero.
222 // NaN is represented as negative zero. (FN -> Finite, UZ -> unsigned zero).
223 // This format's exponent bias is 11, instead of the 7 (2 ** (4 - 1) - 1)
224 // that IEEE precedent would imply.
225 S_Float8E4M3B11FNUZ,
226 // 8-bit floating point number following IEEE-754 conventions with bit
227 // layout S1E3M4.
228 S_Float8E3M4,
229 // Floating point number that occupies 32 bits or less of storage, providing
230 // improved range compared to half (16-bit) formats, at (potentially)
231 // greater throughput than single precision (32-bit) formats.
232 S_FloatTF32,
233 // 8-bit floating point number with (all the) 8 bits for the exponent
234 // like in FP32. There are no zeroes, no infinities, and no denormal values.
235 // This format has unsigned representation only. (U -> Unsigned only).
236 // NaN is represented with all bits set to 1. Bias is 127.
237 // This format represents the scale data type in the MX specification from:
238 // https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
239 S_Float8E8M0FNU,
240 // 6-bit floating point number with bit layout S1E3M2. Unlike IEEE-754
241 // types, there are no infinity or NaN values. The format is detailed in
242 // https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
243 S_Float6E3M2FN,
244 // 6-bit floating point number with bit layout S1E2M3. Unlike IEEE-754
245 // types, there are no infinity or NaN values. The format is detailed in
246 // https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
247 S_Float6E2M3FN,
248 // 4-bit floating point number with bit layout S1E2M1. Unlike IEEE-754
249 // types, there are no infinity or NaN values. The format is detailed in
250 // https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
251 S_Float4E2M1FN,
252 // TODO: Documentation is missing.
253 S_x87DoubleExtended,
254 S_MaxSemantics = S_x87DoubleExtended,
255 };
256
257 LLVM_ABI static const llvm::fltSemantics &EnumToSemantics(Semantics S);
258 LLVM_ABI static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem);
259
260 LLVM_ABI static const fltSemantics &IEEEhalf() LLVM_READNONE;
261 LLVM_ABI static const fltSemantics &BFloat() LLVM_READNONE;
262 LLVM_ABI static const fltSemantics &IEEEsingle() LLVM_READNONE;
263 LLVM_ABI static const fltSemantics &IEEEdouble() LLVM_READNONE;
264 LLVM_ABI static const fltSemantics &IEEEquad() LLVM_READNONE;
265 LLVM_ABI static const fltSemantics &PPCDoubleDouble() LLVM_READNONE;
266 LLVM_ABI static const fltSemantics &PPCDoubleDoubleLegacy() LLVM_READNONE;
267 LLVM_ABI static const fltSemantics &Float8E5M2() LLVM_READNONE;
268 LLVM_ABI static const fltSemantics &Float8E5M2FNUZ() LLVM_READNONE;
269 LLVM_ABI static const fltSemantics &Float8E4M3() LLVM_READNONE;
270 LLVM_ABI static const fltSemantics &Float8E4M3FN() LLVM_READNONE;
271 LLVM_ABI static const fltSemantics &Float8E4M3FNUZ() LLVM_READNONE;
272 LLVM_ABI static const fltSemantics &Float8E4M3B11FNUZ() LLVM_READNONE;
273 LLVM_ABI static const fltSemantics &Float8E3M4() LLVM_READNONE;
274 LLVM_ABI static const fltSemantics &FloatTF32() LLVM_READNONE;
275 LLVM_ABI static const fltSemantics &Float8E8M0FNU() LLVM_READNONE;
276 LLVM_ABI static const fltSemantics &Float6E3M2FN() LLVM_READNONE;
277 LLVM_ABI static const fltSemantics &Float6E2M3FN() LLVM_READNONE;
278 LLVM_ABI static const fltSemantics &Float4E2M1FN() LLVM_READNONE;
279 LLVM_ABI static const fltSemantics &x87DoubleExtended() LLVM_READNONE;
280
281 /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with
282 /// anything real.
283 LLVM_ABI static const fltSemantics &Bogus() LLVM_READNONE;
284
285 // Returns true if any number described by this semantics can be precisely
286 // represented by the specified semantics. Does not take into account
287 // the value of fltNonfiniteBehavior, hasZero, hasSignedRepr.
288 LLVM_ABI static bool isRepresentableBy(const fltSemantics &A,
289 const fltSemantics &B);
290
291 /// @}
292
293 /// IEEE-754R 5.11: Floating Point Comparison Relations.
294 enum cmpResult {
295 cmpLessThan,
296 cmpEqual,
297 cmpGreaterThan,
298 cmpUnordered
299 };
300
301 /// IEEE-754R 4.3: Rounding-direction attributes.
302 using roundingMode = llvm::RoundingMode;
303
304 static constexpr roundingMode rmNearestTiesToEven =
305 RoundingMode::NearestTiesToEven;
306 static constexpr roundingMode rmTowardPositive = RoundingMode::TowardPositive;
307 static constexpr roundingMode rmTowardNegative = RoundingMode::TowardNegative;
308 static constexpr roundingMode rmTowardZero = RoundingMode::TowardZero;
309 static constexpr roundingMode rmNearestTiesToAway =
310 RoundingMode::NearestTiesToAway;
311
312 /// IEEE-754R 7: Default exception handling.
313 ///
314 /// opUnderflow or opOverflow are always returned or-ed with opInexact.
315 ///
316 /// APFloat models this behavior specified by IEEE-754:
317 /// "For operations producing results in floating-point format, the default
318 /// result of an operation that signals the invalid operation exception
319 /// shall be a quiet NaN."
320 enum opStatus {
321 opOK = 0x00,
322 opInvalidOp = 0x01,
323 opDivByZero = 0x02,
324 opOverflow = 0x04,
325 opUnderflow = 0x08,
326 opInexact = 0x10
327 };
328
329 /// Category of internally-represented number.
330 enum fltCategory {
331 fcInfinity,
332 fcNaN,
333 fcNormal,
334 fcZero
335 };
336
337 /// Convenience enum used to construct an uninitialized APFloat.
338 enum uninitializedTag {
339 uninitialized
340 };
341
342 /// Enumeration of \c ilogb error results.
343 enum IlogbErrorKinds {
344 IEK_Zero = INT_MIN + 1,
345 IEK_NaN = INT_MIN,
346 IEK_Inf = INT_MAX
347 };
348
349 LLVM_ABI static unsigned int semanticsPrecision(const fltSemantics &);
350 LLVM_ABI static ExponentType semanticsMinExponent(const fltSemantics &);
351 LLVM_ABI static ExponentType semanticsMaxExponent(const fltSemantics &);
352 LLVM_ABI static unsigned int semanticsSizeInBits(const fltSemantics &);
353 LLVM_ABI static unsigned int semanticsIntSizeInBits(const fltSemantics &,
354 bool);
355 LLVM_ABI static bool semanticsHasZero(const fltSemantics &);
356 LLVM_ABI static bool semanticsHasSignedRepr(const fltSemantics &);
357 LLVM_ABI static bool semanticsHasInf(const fltSemantics &);
358 LLVM_ABI static bool semanticsHasNaN(const fltSemantics &);
359 LLVM_ABI static bool isIEEELikeFP(const fltSemantics &);
360 LLVM_ABI static bool hasSignBitInMSB(const fltSemantics &);
361
362 // Returns true if any number described by \p Src can be precisely represented
363 // by a normal (not subnormal) value in \p Dst.
364 LLVM_ABI static bool isRepresentableAsNormalIn(const fltSemantics &Src,
365 const fltSemantics &Dst);
366
367 /// Returns the size of the floating point number (in bits) in the given
368 /// semantics.
369 LLVM_ABI static unsigned getSizeInBits(const fltSemantics &Sem);
370 };
371
372 namespace detail {
373
374 using integerPart = APFloatBase::integerPart;
375 using uninitializedTag = APFloatBase::uninitializedTag;
376 using roundingMode = APFloatBase::roundingMode;
377 using opStatus = APFloatBase::opStatus;
378 using cmpResult = APFloatBase::cmpResult;
379 using fltCategory = APFloatBase::fltCategory;
380 using ExponentType = APFloatBase::ExponentType;
381 static constexpr uninitializedTag uninitialized = APFloatBase::uninitialized;
382 static constexpr roundingMode rmNearestTiesToEven =
383 APFloatBase::rmNearestTiesToEven;
384 static constexpr roundingMode rmNearestTiesToAway =
385 APFloatBase::rmNearestTiesToAway;
386 static constexpr roundingMode rmTowardNegative = APFloatBase::rmTowardNegative;
387 static constexpr roundingMode rmTowardPositive = APFloatBase::rmTowardPositive;
388 static constexpr roundingMode rmTowardZero = APFloatBase::rmTowardZero;
389 static constexpr unsigned integerPartWidth = APFloatBase::integerPartWidth;
390 static constexpr cmpResult cmpEqual = APFloatBase::cmpEqual;
391 static constexpr cmpResult cmpLessThan = APFloatBase::cmpLessThan;
392 static constexpr cmpResult cmpGreaterThan = APFloatBase::cmpGreaterThan;
393 static constexpr cmpResult cmpUnordered = APFloatBase::cmpUnordered;
394 static constexpr opStatus opOK = APFloatBase::opOK;
395 static constexpr opStatus opInvalidOp = APFloatBase::opInvalidOp;
396 static constexpr opStatus opDivByZero = APFloatBase::opDivByZero;
397 static constexpr opStatus opOverflow = APFloatBase::opOverflow;
398 static constexpr opStatus opUnderflow = APFloatBase::opUnderflow;
399 static constexpr opStatus opInexact = APFloatBase::opInexact;
400 static constexpr fltCategory fcInfinity = APFloatBase::fcInfinity;
401 static constexpr fltCategory fcNaN = APFloatBase::fcNaN;
402 static constexpr fltCategory fcNormal = APFloatBase::fcNormal;
403 static constexpr fltCategory fcZero = APFloatBase::fcZero;
404
405 class IEEEFloat final {
406 public:
407 /// \name Constructors
408 /// @{
409
410 LLVM_ABI IEEEFloat(const fltSemantics &); // Default construct to +0.0
411 LLVM_ABI IEEEFloat(const fltSemantics &, integerPart);
412 LLVM_ABI IEEEFloat(const fltSemantics &, uninitializedTag);
413 LLVM_ABI IEEEFloat(const fltSemantics &, const APInt &);
414 LLVM_ABI explicit IEEEFloat(double d);
415 LLVM_ABI explicit IEEEFloat(float f);
416 LLVM_ABI IEEEFloat(const IEEEFloat &);
417 LLVM_ABI IEEEFloat(IEEEFloat &&);
418 LLVM_ABI ~IEEEFloat();
419
420 /// @}
421
422 /// Returns whether this instance allocated memory.
needsCleanup()423 bool needsCleanup() const { return partCount() > 1; }
424
425 /// \name Convenience "constructors"
426 /// @{
427
428 /// @}
429
430 /// \name Arithmetic
431 /// @{
432
433 LLVM_ABI opStatus add(const IEEEFloat &, roundingMode);
434 LLVM_ABI opStatus subtract(const IEEEFloat &, roundingMode);
435 LLVM_ABI opStatus multiply(const IEEEFloat &, roundingMode);
436 LLVM_ABI opStatus divide(const IEEEFloat &, roundingMode);
437 /// IEEE remainder.
438 LLVM_ABI opStatus remainder(const IEEEFloat &);
439 /// C fmod, or llvm frem.
440 LLVM_ABI opStatus mod(const IEEEFloat &);
441 LLVM_ABI opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &,
442 roundingMode);
443 LLVM_ABI opStatus roundToIntegral(roundingMode);
444 /// IEEE-754R 5.3.1: nextUp/nextDown.
445 LLVM_ABI opStatus next(bool nextDown);
446
447 /// @}
448
449 /// \name Sign operations.
450 /// @{
451
452 LLVM_ABI void changeSign();
453
454 /// @}
455
456 /// \name Conversions
457 /// @{
458
459 LLVM_ABI opStatus convert(const fltSemantics &, roundingMode, bool *);
460 LLVM_ABI opStatus convertToInteger(MutableArrayRef<integerPart>, unsigned int,
461 bool, roundingMode, bool *) const;
462 LLVM_ABI opStatus convertFromAPInt(const APInt &, bool, roundingMode);
463 LLVM_ABI opStatus convertFromSignExtendedInteger(const integerPart *,
464 unsigned int, bool,
465 roundingMode);
466 LLVM_ABI opStatus convertFromZeroExtendedInteger(const integerPart *,
467 unsigned int, bool,
468 roundingMode);
469 LLVM_ABI Expected<opStatus> convertFromString(StringRef, roundingMode);
470 LLVM_ABI APInt bitcastToAPInt() const;
471 LLVM_ABI double convertToDouble() const;
472 #ifdef HAS_IEE754_FLOAT128
473 LLVM_ABI float128 convertToQuad() const;
474 #endif
475 LLVM_ABI float convertToFloat() const;
476
477 /// @}
478
479 /// The definition of equality is not straightforward for floating point, so
480 /// we won't use operator==. Use one of the following, or write whatever it
481 /// is you really mean.
482 bool operator==(const IEEEFloat &) const = delete;
483
484 /// IEEE comparison with another floating point number (NaNs compare
485 /// unordered, 0==-0).
486 LLVM_ABI cmpResult compare(const IEEEFloat &) const;
487
488 /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0).
489 LLVM_ABI bool bitwiseIsEqual(const IEEEFloat &) const;
490
491 /// Write out a hexadecimal representation of the floating point value to DST,
492 /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d.
493 /// Return the number of characters written, excluding the terminating NUL.
494 LLVM_ABI unsigned int convertToHexString(char *dst, unsigned int hexDigits,
495 bool upperCase, roundingMode) const;
496
497 /// \name IEEE-754R 5.7.2 General operations.
498 /// @{
499
500 /// IEEE-754R isSignMinus: Returns true if and only if the current value is
501 /// negative.
502 ///
503 /// This applies to zeros and NaNs as well.
isNegative()504 bool isNegative() const { return sign; }
505
506 /// IEEE-754R isNormal: Returns true if and only if the current value is normal.
507 ///
508 /// This implies that the current value of the float is not zero, subnormal,
509 /// infinite, or NaN following the definition of normality from IEEE-754R.
isNormal()510 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
511
512 /// Returns true if and only if the current value is zero, subnormal, or
513 /// normal.
514 ///
515 /// This means that the value is not infinite or NaN.
isFinite()516 bool isFinite() const { return !isNaN() && !isInfinity(); }
517
518 /// Returns true if and only if the float is plus or minus zero.
isZero()519 bool isZero() const { return category == fltCategory::fcZero; }
520
521 /// IEEE-754R isSubnormal(): Returns true if and only if the float is a
522 /// denormal.
523 LLVM_ABI bool isDenormal() const;
524
525 /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity.
isInfinity()526 bool isInfinity() const { return category == fcInfinity; }
527
528 /// Returns true if and only if the float is a quiet or signaling NaN.
isNaN()529 bool isNaN() const { return category == fcNaN; }
530
531 /// Returns true if and only if the float is a signaling NaN.
532 LLVM_ABI bool isSignaling() const;
533
534 /// @}
535
536 /// \name Simple Queries
537 /// @{
538
getCategory()539 fltCategory getCategory() const { return category; }
getSemantics()540 const fltSemantics &getSemantics() const { return *semantics; }
isNonZero()541 bool isNonZero() const { return category != fltCategory::fcZero; }
isFiniteNonZero()542 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
isPosZero()543 bool isPosZero() const { return isZero() && !isNegative(); }
isNegZero()544 bool isNegZero() const { return isZero() && isNegative(); }
545
546 /// Returns true if and only if the number has the smallest possible non-zero
547 /// magnitude in the current semantics.
548 LLVM_ABI bool isSmallest() const;
549
550 /// Returns true if this is the smallest (by magnitude) normalized finite
551 /// number in the given semantics.
552 LLVM_ABI bool isSmallestNormalized() const;
553
554 /// Returns true if and only if the number has the largest possible finite
555 /// magnitude in the current semantics.
556 LLVM_ABI bool isLargest() const;
557
558 /// Returns true if and only if the number is an exact integer.
559 LLVM_ABI bool isInteger() const;
560
561 /// @}
562
563 LLVM_ABI IEEEFloat &operator=(const IEEEFloat &);
564 LLVM_ABI IEEEFloat &operator=(IEEEFloat &&);
565
566 /// Overload to compute a hash code for an APFloat value.
567 ///
568 /// Note that the use of hash codes for floating point values is in general
569 /// frought with peril. Equality is hard to define for these values. For
570 /// example, should negative and positive zero hash to different codes? Are
571 /// they equal or not? This hash value implementation specifically
572 /// emphasizes producing different codes for different inputs in order to
573 /// be used in canonicalization and memoization. As such, equality is
574 /// bitwiseIsEqual, and 0 != -0.
575 LLVM_ABI friend hash_code hash_value(const IEEEFloat &Arg);
576
577 /// Converts this value into a decimal string.
578 ///
579 /// \param FormatPrecision The maximum number of digits of
580 /// precision to output. If there are fewer digits available,
581 /// zero padding will not be used unless the value is
582 /// integral and small enough to be expressed in
583 /// FormatPrecision digits. 0 means to use the natural
584 /// precision of the number.
585 /// \param FormatMaxPadding The maximum number of zeros to
586 /// consider inserting before falling back to scientific
587 /// notation. 0 means to always use scientific notation.
588 ///
589 /// \param TruncateZero Indicate whether to remove the trailing zero in
590 /// fraction part or not. Also setting this parameter to false forcing
591 /// producing of output more similar to default printf behavior.
592 /// Specifically the lower e is used as exponent delimiter and exponent
593 /// always contains no less than two digits.
594 ///
595 /// Number Precision MaxPadding Result
596 /// ------ --------- ---------- ------
597 /// 1.01E+4 5 2 10100
598 /// 1.01E+4 4 2 1.01E+4
599 /// 1.01E+4 5 1 1.01E+4
600 /// 1.01E-2 5 2 0.0101
601 /// 1.01E-2 4 2 0.0101
602 /// 1.01E-2 4 1 1.01E-2
603 LLVM_ABI void toString(SmallVectorImpl<char> &Str,
604 unsigned FormatPrecision = 0,
605 unsigned FormatMaxPadding = 3,
606 bool TruncateZero = true) const;
607
608 /// If this value has an exact multiplicative inverse, store it in inv and
609 /// return true.
610 LLVM_ABI bool getExactInverse(APFloat *inv) const;
611
612 // If this is an exact power of two, return the exponent while ignoring the
613 // sign bit. If it's not an exact power of 2, return INT_MIN
614 LLVM_ABI LLVM_READONLY int getExactLog2Abs() const;
615
616 // If this is an exact power of two, return the exponent. If it's not an exact
617 // power of 2, return INT_MIN
618 LLVM_READONLY
getExactLog2()619 int getExactLog2() const {
620 return isNegative() ? INT_MIN : getExactLog2Abs();
621 }
622
623 /// Returns the exponent of the internal representation of the APFloat.
624 ///
625 /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)).
626 /// For special APFloat values, this returns special error codes:
627 ///
628 /// NaN -> \c IEK_NaN
629 /// 0 -> \c IEK_Zero
630 /// Inf -> \c IEK_Inf
631 ///
632 LLVM_ABI friend int ilogb(const IEEEFloat &Arg);
633
634 /// Returns: X * 2^Exp for integral exponents.
635 LLVM_ABI friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
636
637 LLVM_ABI friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode);
638
639 /// \name Special value setters.
640 /// @{
641
642 LLVM_ABI void makeLargest(bool Neg = false);
643 LLVM_ABI void makeSmallest(bool Neg = false);
644 LLVM_ABI void makeNaN(bool SNaN = false, bool Neg = false,
645 const APInt *fill = nullptr);
646 LLVM_ABI void makeInf(bool Neg = false);
647 LLVM_ABI void makeZero(bool Neg = false);
648 LLVM_ABI void makeQuiet();
649
650 /// Returns the smallest (by magnitude) normalized finite number in the given
651 /// semantics.
652 ///
653 /// \param Negative - True iff the number should be negative
654 LLVM_ABI void makeSmallestNormalized(bool Negative = false);
655
656 /// @}
657
658 LLVM_ABI cmpResult compareAbsoluteValue(const IEEEFloat &) const;
659
660 private:
661 /// \name Simple Queries
662 /// @{
663
664 integerPart *significandParts();
665 const integerPart *significandParts() const;
666 LLVM_ABI unsigned int partCount() const;
667
668 /// @}
669
670 /// \name Significand operations.
671 /// @{
672
673 integerPart addSignificand(const IEEEFloat &);
674 integerPart subtractSignificand(const IEEEFloat &, integerPart);
675 // Exported for IEEEFloatUnitTestHelper.
676 LLVM_ABI lostFraction addOrSubtractSignificand(const IEEEFloat &,
677 bool subtract);
678 lostFraction multiplySignificand(const IEEEFloat &, IEEEFloat,
679 bool ignoreAddend = false);
680 lostFraction multiplySignificand(const IEEEFloat&);
681 lostFraction divideSignificand(const IEEEFloat &);
682 void incrementSignificand();
683 void initialize(const fltSemantics *);
684 void shiftSignificandLeft(unsigned int);
685 lostFraction shiftSignificandRight(unsigned int);
686 unsigned int significandLSB() const;
687 unsigned int significandMSB() const;
688 void zeroSignificand();
689 unsigned int getNumHighBits() const;
690 /// Return true if the significand excluding the integral bit is all ones.
691 bool isSignificandAllOnes() const;
692 bool isSignificandAllOnesExceptLSB() const;
693 /// Return true if the significand excluding the integral bit is all zeros.
694 bool isSignificandAllZeros() const;
695 bool isSignificandAllZerosExceptMSB() const;
696
697 /// @}
698
699 /// \name Arithmetic on special values.
700 /// @{
701
702 opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract);
703 opStatus divideSpecials(const IEEEFloat &);
704 opStatus multiplySpecials(const IEEEFloat &);
705 opStatus modSpecials(const IEEEFloat &);
706 opStatus remainderSpecials(const IEEEFloat&);
707
708 /// @}
709
710 /// \name Miscellany
711 /// @{
712
713 bool convertFromStringSpecials(StringRef str);
714 opStatus normalize(roundingMode, lostFraction);
715 opStatus addOrSubtract(const IEEEFloat &, roundingMode, bool subtract);
716 opStatus handleOverflow(roundingMode);
717 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const;
718 opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart>,
719 unsigned int, bool, roundingMode,
720 bool *) const;
721 opStatus convertFromUnsignedParts(const integerPart *, unsigned int,
722 roundingMode);
723 Expected<opStatus> convertFromHexadecimalString(StringRef, roundingMode);
724 Expected<opStatus> convertFromDecimalString(StringRef, roundingMode);
725 char *convertNormalToHexString(char *, unsigned int, bool,
726 roundingMode) const;
727 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int,
728 roundingMode);
729 ExponentType exponentNaN() const;
730 ExponentType exponentInf() const;
731 ExponentType exponentZero() const;
732
733 /// @}
734
735 template <const fltSemantics &S> APInt convertIEEEFloatToAPInt() const;
736 APInt convertHalfAPFloatToAPInt() const;
737 APInt convertBFloatAPFloatToAPInt() const;
738 APInt convertFloatAPFloatToAPInt() const;
739 APInt convertDoubleAPFloatToAPInt() const;
740 APInt convertQuadrupleAPFloatToAPInt() const;
741 APInt convertF80LongDoubleAPFloatToAPInt() const;
742 APInt convertPPCDoubleDoubleLegacyAPFloatToAPInt() const;
743 APInt convertFloat8E5M2APFloatToAPInt() const;
744 APInt convertFloat8E5M2FNUZAPFloatToAPInt() const;
745 APInt convertFloat8E4M3APFloatToAPInt() const;
746 APInt convertFloat8E4M3FNAPFloatToAPInt() const;
747 APInt convertFloat8E4M3FNUZAPFloatToAPInt() const;
748 APInt convertFloat8E4M3B11FNUZAPFloatToAPInt() const;
749 APInt convertFloat8E3M4APFloatToAPInt() const;
750 APInt convertFloatTF32APFloatToAPInt() const;
751 APInt convertFloat8E8M0FNUAPFloatToAPInt() const;
752 APInt convertFloat6E3M2FNAPFloatToAPInt() const;
753 APInt convertFloat6E2M3FNAPFloatToAPInt() const;
754 APInt convertFloat4E2M1FNAPFloatToAPInt() const;
755 void initFromAPInt(const fltSemantics *Sem, const APInt &api);
756 template <const fltSemantics &S> void initFromIEEEAPInt(const APInt &api);
757 void initFromHalfAPInt(const APInt &api);
758 void initFromBFloatAPInt(const APInt &api);
759 void initFromFloatAPInt(const APInt &api);
760 void initFromDoubleAPInt(const APInt &api);
761 void initFromQuadrupleAPInt(const APInt &api);
762 void initFromF80LongDoubleAPInt(const APInt &api);
763 void initFromPPCDoubleDoubleLegacyAPInt(const APInt &api);
764 void initFromFloat8E5M2APInt(const APInt &api);
765 void initFromFloat8E5M2FNUZAPInt(const APInt &api);
766 void initFromFloat8E4M3APInt(const APInt &api);
767 void initFromFloat8E4M3FNAPInt(const APInt &api);
768 void initFromFloat8E4M3FNUZAPInt(const APInt &api);
769 void initFromFloat8E4M3B11FNUZAPInt(const APInt &api);
770 void initFromFloat8E3M4APInt(const APInt &api);
771 void initFromFloatTF32APInt(const APInt &api);
772 void initFromFloat8E8M0FNUAPInt(const APInt &api);
773 void initFromFloat6E3M2FNAPInt(const APInt &api);
774 void initFromFloat6E2M3FNAPInt(const APInt &api);
775 void initFromFloat4E2M1FNAPInt(const APInt &api);
776
777 void assign(const IEEEFloat &);
778 void copySignificand(const IEEEFloat &);
779 void freeSignificand();
780
781 /// Note: this must be the first data member.
782 /// The semantics that this value obeys.
783 const fltSemantics *semantics;
784
785 /// A binary fraction with an explicit integer bit.
786 ///
787 /// The significand must be at least one bit wider than the target precision.
788 union Significand {
789 integerPart part;
790 integerPart *parts;
791 } significand;
792
793 /// The signed unbiased exponent of the value.
794 ExponentType exponent;
795
796 /// What kind of floating point number this is.
797 ///
798 /// Only 2 bits are required, but VisualStudio incorrectly sign extends it.
799 /// Using the extra bit keeps it from failing under VisualStudio.
800 fltCategory category : 3;
801
802 /// Sign bit of the number.
803 unsigned int sign : 1;
804
805 friend class IEEEFloatUnitTestHelper;
806 };
807
808 LLVM_ABI hash_code hash_value(const IEEEFloat &Arg);
809 LLVM_ABI int ilogb(const IEEEFloat &Arg);
810 LLVM_ABI IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
811 LLVM_ABI IEEEFloat frexp(const IEEEFloat &Val, int &Exp, roundingMode RM);
812
813 // This mode implements more precise float in terms of two APFloats.
814 // The interface and layout is designed for arbitrary underlying semantics,
815 // though currently only PPCDoubleDouble semantics are supported, whose
816 // corresponding underlying semantics are IEEEdouble.
817 class DoubleAPFloat final {
818 // Note: this must be the first data member.
819 const fltSemantics *Semantics;
820 APFloat *Floats;
821
822 opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c,
823 const APFloat &cc, roundingMode RM);
824
825 opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS,
826 DoubleAPFloat &Out, roundingMode RM);
827
828 public:
829 LLVM_ABI DoubleAPFloat(const fltSemantics &S);
830 LLVM_ABI DoubleAPFloat(const fltSemantics &S, uninitializedTag);
831 LLVM_ABI DoubleAPFloat(const fltSemantics &S, integerPart);
832 LLVM_ABI DoubleAPFloat(const fltSemantics &S, const APInt &I);
833 LLVM_ABI DoubleAPFloat(const fltSemantics &S, APFloat &&First,
834 APFloat &&Second);
835 LLVM_ABI DoubleAPFloat(const DoubleAPFloat &RHS);
836 LLVM_ABI DoubleAPFloat(DoubleAPFloat &&RHS);
837 ~DoubleAPFloat();
838
839 LLVM_ABI DoubleAPFloat &operator=(const DoubleAPFloat &RHS);
840 inline DoubleAPFloat &operator=(DoubleAPFloat &&RHS);
841
needsCleanup()842 bool needsCleanup() const { return Floats != nullptr; }
843
844 inline APFloat &getFirst();
845 inline const APFloat &getFirst() const;
846 inline APFloat &getSecond();
847 inline const APFloat &getSecond() const;
848
849 LLVM_ABI opStatus add(const DoubleAPFloat &RHS, roundingMode RM);
850 LLVM_ABI opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM);
851 LLVM_ABI opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM);
852 LLVM_ABI opStatus divide(const DoubleAPFloat &RHS, roundingMode RM);
853 LLVM_ABI opStatus remainder(const DoubleAPFloat &RHS);
854 LLVM_ABI opStatus mod(const DoubleAPFloat &RHS);
855 LLVM_ABI opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
856 const DoubleAPFloat &Addend,
857 roundingMode RM);
858 LLVM_ABI opStatus roundToIntegral(roundingMode RM);
859 LLVM_ABI void changeSign();
860 LLVM_ABI cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const;
861
862 LLVM_ABI fltCategory getCategory() const;
863 LLVM_ABI bool isNegative() const;
864
865 LLVM_ABI void makeInf(bool Neg);
866 LLVM_ABI void makeZero(bool Neg);
867 LLVM_ABI void makeLargest(bool Neg);
868 LLVM_ABI void makeSmallest(bool Neg);
869 LLVM_ABI void makeSmallestNormalized(bool Neg);
870 LLVM_ABI void makeNaN(bool SNaN, bool Neg, const APInt *fill);
871
872 LLVM_ABI cmpResult compare(const DoubleAPFloat &RHS) const;
873 LLVM_ABI bool bitwiseIsEqual(const DoubleAPFloat &RHS) const;
874 LLVM_ABI APInt bitcastToAPInt() const;
875 LLVM_ABI Expected<opStatus> convertFromString(StringRef, roundingMode);
876 LLVM_ABI opStatus next(bool nextDown);
877
878 LLVM_ABI opStatus convertToInteger(MutableArrayRef<integerPart> Input,
879 unsigned int Width, bool IsSigned,
880 roundingMode RM, bool *IsExact) const;
881 LLVM_ABI opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
882 roundingMode RM);
883 LLVM_ABI opStatus convertFromSignExtendedInteger(const integerPart *Input,
884 unsigned int InputSize,
885 bool IsSigned,
886 roundingMode RM);
887 LLVM_ABI opStatus convertFromZeroExtendedInteger(const integerPart *Input,
888 unsigned int InputSize,
889 bool IsSigned,
890 roundingMode RM);
891 LLVM_ABI unsigned int convertToHexString(char *DST, unsigned int HexDigits,
892 bool UpperCase,
893 roundingMode RM) const;
894
895 LLVM_ABI bool isDenormal() const;
896 LLVM_ABI bool isSmallest() const;
897 LLVM_ABI bool isSmallestNormalized() const;
898 LLVM_ABI bool isLargest() const;
899 LLVM_ABI bool isInteger() const;
900
901 LLVM_ABI void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
902 unsigned FormatMaxPadding,
903 bool TruncateZero = true) const;
904
905 LLVM_ABI bool getExactInverse(APFloat *inv) const;
906
907 LLVM_ABI LLVM_READONLY int getExactLog2() const;
908 LLVM_ABI LLVM_READONLY int getExactLog2Abs() const;
909
910 LLVM_ABI friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp,
911 roundingMode);
912 LLVM_ABI friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp,
913 roundingMode);
914 LLVM_ABI friend hash_code hash_value(const DoubleAPFloat &Arg);
915 };
916
917 LLVM_ABI hash_code hash_value(const DoubleAPFloat &Arg);
918 LLVM_ABI DoubleAPFloat scalbn(const DoubleAPFloat &Arg, int Exp,
919 roundingMode RM);
920 LLVM_ABI DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp, roundingMode);
921
922 } // End detail namespace
923
924 // This is a interface class that is currently forwarding functionalities from
925 // detail::IEEEFloat.
926 class APFloat : public APFloatBase {
927 typedef detail::IEEEFloat IEEEFloat;
928 typedef detail::DoubleAPFloat DoubleAPFloat;
929
930 static_assert(std::is_standard_layout<IEEEFloat>::value);
931
932 union Storage {
933 const fltSemantics *semantics;
934 IEEEFloat IEEE;
935 DoubleAPFloat Double;
936
937 LLVM_ABI explicit Storage(IEEEFloat F, const fltSemantics &S);
Storage(DoubleAPFloat F,const fltSemantics & S)938 explicit Storage(DoubleAPFloat F, const fltSemantics &S)
939 : Double(std::move(F)) {
940 assert(&S == &PPCDoubleDouble());
941 }
942
943 template <typename... ArgTypes>
Storage(const fltSemantics & Semantics,ArgTypes &&...Args)944 Storage(const fltSemantics &Semantics, ArgTypes &&... Args) {
945 if (usesLayout<IEEEFloat>(Semantics)) {
946 new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...);
947 return;
948 }
949 if (usesLayout<DoubleAPFloat>(Semantics)) {
950 new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...);
951 return;
952 }
953 llvm_unreachable("Unexpected semantics");
954 }
955
~Storage()956 ~Storage() {
957 if (usesLayout<IEEEFloat>(*semantics)) {
958 IEEE.~IEEEFloat();
959 return;
960 }
961 if (usesLayout<DoubleAPFloat>(*semantics)) {
962 Double.~DoubleAPFloat();
963 return;
964 }
965 llvm_unreachable("Unexpected semantics");
966 }
967
Storage(const Storage & RHS)968 Storage(const Storage &RHS) {
969 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
970 new (this) IEEEFloat(RHS.IEEE);
971 return;
972 }
973 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
974 new (this) DoubleAPFloat(RHS.Double);
975 return;
976 }
977 llvm_unreachable("Unexpected semantics");
978 }
979
Storage(Storage && RHS)980 Storage(Storage &&RHS) {
981 if (usesLayout<IEEEFloat>(*RHS.semantics)) {
982 new (this) IEEEFloat(std::move(RHS.IEEE));
983 return;
984 }
985 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) {
986 new (this) DoubleAPFloat(std::move(RHS.Double));
987 return;
988 }
989 llvm_unreachable("Unexpected semantics");
990 }
991
992 Storage &operator=(const Storage &RHS) {
993 if (usesLayout<IEEEFloat>(*semantics) &&
994 usesLayout<IEEEFloat>(*RHS.semantics)) {
995 IEEE = RHS.IEEE;
996 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
997 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
998 Double = RHS.Double;
999 } else if (this != &RHS) {
1000 this->~Storage();
1001 new (this) Storage(RHS);
1002 }
1003 return *this;
1004 }
1005
1006 Storage &operator=(Storage &&RHS) {
1007 if (usesLayout<IEEEFloat>(*semantics) &&
1008 usesLayout<IEEEFloat>(*RHS.semantics)) {
1009 IEEE = std::move(RHS.IEEE);
1010 } else if (usesLayout<DoubleAPFloat>(*semantics) &&
1011 usesLayout<DoubleAPFloat>(*RHS.semantics)) {
1012 Double = std::move(RHS.Double);
1013 } else if (this != &RHS) {
1014 this->~Storage();
1015 new (this) Storage(std::move(RHS));
1016 }
1017 return *this;
1018 }
1019 } U;
1020
usesLayout(const fltSemantics & Semantics)1021 template <typename T> static bool usesLayout(const fltSemantics &Semantics) {
1022 static_assert(std::is_same<T, IEEEFloat>::value ||
1023 std::is_same<T, DoubleAPFloat>::value);
1024 if (std::is_same<T, DoubleAPFloat>::value) {
1025 return &Semantics == &PPCDoubleDouble();
1026 }
1027 return &Semantics != &PPCDoubleDouble();
1028 }
1029
getIEEE()1030 IEEEFloat &getIEEE() {
1031 if (usesLayout<IEEEFloat>(*U.semantics))
1032 return U.IEEE;
1033 if (usesLayout<DoubleAPFloat>(*U.semantics))
1034 return U.Double.getFirst().U.IEEE;
1035 llvm_unreachable("Unexpected semantics");
1036 }
1037
getIEEE()1038 const IEEEFloat &getIEEE() const {
1039 if (usesLayout<IEEEFloat>(*U.semantics))
1040 return U.IEEE;
1041 if (usesLayout<DoubleAPFloat>(*U.semantics))
1042 return U.Double.getFirst().U.IEEE;
1043 llvm_unreachable("Unexpected semantics");
1044 }
1045
makeZero(bool Neg)1046 void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); }
1047
makeInf(bool Neg)1048 void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); }
1049
makeNaN(bool SNaN,bool Neg,const APInt * fill)1050 void makeNaN(bool SNaN, bool Neg, const APInt *fill) {
1051 APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill));
1052 }
1053
makeLargest(bool Neg)1054 void makeLargest(bool Neg) {
1055 APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg));
1056 }
1057
makeSmallest(bool Neg)1058 void makeSmallest(bool Neg) {
1059 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg));
1060 }
1061
makeSmallestNormalized(bool Neg)1062 void makeSmallestNormalized(bool Neg) {
1063 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg));
1064 }
1065
APFloat(IEEEFloat F,const fltSemantics & S)1066 explicit APFloat(IEEEFloat F, const fltSemantics &S) : U(std::move(F), S) {}
APFloat(DoubleAPFloat F,const fltSemantics & S)1067 explicit APFloat(DoubleAPFloat F, const fltSemantics &S)
1068 : U(std::move(F), S) {}
1069
compareAbsoluteValue(const APFloat & RHS)1070 cmpResult compareAbsoluteValue(const APFloat &RHS) const {
1071 assert(&getSemantics() == &RHS.getSemantics() &&
1072 "Should only compare APFloats with the same semantics");
1073 if (usesLayout<IEEEFloat>(getSemantics()))
1074 return U.IEEE.compareAbsoluteValue(RHS.U.IEEE);
1075 if (usesLayout<DoubleAPFloat>(getSemantics()))
1076 return U.Double.compareAbsoluteValue(RHS.U.Double);
1077 llvm_unreachable("Unexpected semantics");
1078 }
1079
1080 public:
APFloat(const fltSemantics & Semantics)1081 APFloat(const fltSemantics &Semantics) : U(Semantics) {}
1082 LLVM_ABI APFloat(const fltSemantics &Semantics, StringRef S);
APFloat(const fltSemantics & Semantics,integerPart I)1083 APFloat(const fltSemantics &Semantics, integerPart I) : U(Semantics, I) {}
1084 template <typename T,
1085 typename = std::enable_if_t<std::is_floating_point<T>::value>>
1086 APFloat(const fltSemantics &Semantics, T V) = delete;
1087 // TODO: Remove this constructor. This isn't faster than the first one.
APFloat(const fltSemantics & Semantics,uninitializedTag)1088 APFloat(const fltSemantics &Semantics, uninitializedTag)
1089 : U(Semantics, uninitialized) {}
APFloat(const fltSemantics & Semantics,const APInt & I)1090 APFloat(const fltSemantics &Semantics, const APInt &I) : U(Semantics, I) {}
APFloat(double d)1091 explicit APFloat(double d) : U(IEEEFloat(d), IEEEdouble()) {}
APFloat(float f)1092 explicit APFloat(float f) : U(IEEEFloat(f), IEEEsingle()) {}
1093 APFloat(const APFloat &RHS) = default;
1094 APFloat(APFloat &&RHS) = default;
1095
1096 ~APFloat() = default;
1097
needsCleanup()1098 bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); }
1099
1100 /// Factory for Positive and Negative Zero.
1101 ///
1102 /// \param Negative True iff the number should be negative.
1103 static APFloat getZero(const fltSemantics &Sem, bool Negative = false) {
1104 APFloat Val(Sem, uninitialized);
1105 Val.makeZero(Negative);
1106 return Val;
1107 }
1108
1109 /// Factory for Positive and Negative One.
1110 ///
1111 /// \param Negative True iff the number should be negative.
1112 static APFloat getOne(const fltSemantics &Sem, bool Negative = false) {
1113 APFloat Val(Sem, 1U);
1114 if (Negative)
1115 Val.changeSign();
1116 return Val;
1117 }
1118
1119 /// Factory for Positive and Negative Infinity.
1120 ///
1121 /// \param Negative True iff the number should be negative.
1122 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) {
1123 APFloat Val(Sem, uninitialized);
1124 Val.makeInf(Negative);
1125 return Val;
1126 }
1127
1128 /// Factory for NaN values.
1129 ///
1130 /// \param Negative - True iff the NaN generated should be negative.
1131 /// \param payload - The unspecified fill bits for creating the NaN, 0 by
1132 /// default. The value is truncated as necessary.
1133 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false,
1134 uint64_t payload = 0) {
1135 if (payload) {
1136 APInt intPayload(64, payload);
1137 return getQNaN(Sem, Negative, &intPayload);
1138 } else {
1139 return getQNaN(Sem, Negative, nullptr);
1140 }
1141 }
1142
1143 /// Factory for QNaN values.
1144 static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false,
1145 const APInt *payload = nullptr) {
1146 APFloat Val(Sem, uninitialized);
1147 Val.makeNaN(false, Negative, payload);
1148 return Val;
1149 }
1150
1151 /// Factory for SNaN values.
1152 static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false,
1153 const APInt *payload = nullptr) {
1154 APFloat Val(Sem, uninitialized);
1155 Val.makeNaN(true, Negative, payload);
1156 return Val;
1157 }
1158
1159 /// Returns the largest finite number in the given semantics.
1160 ///
1161 /// \param Negative - True iff the number should be negative
1162 static APFloat getLargest(const fltSemantics &Sem, bool Negative = false) {
1163 APFloat Val(Sem, uninitialized);
1164 Val.makeLargest(Negative);
1165 return Val;
1166 }
1167
1168 /// Returns the smallest (by magnitude) finite number in the given semantics.
1169 /// Might be denormalized, which implies a relative loss of precision.
1170 ///
1171 /// \param Negative - True iff the number should be negative
1172 static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false) {
1173 APFloat Val(Sem, uninitialized);
1174 Val.makeSmallest(Negative);
1175 return Val;
1176 }
1177
1178 /// Returns the smallest (by magnitude) normalized finite number in the given
1179 /// semantics.
1180 ///
1181 /// \param Negative - True iff the number should be negative
1182 static APFloat getSmallestNormalized(const fltSemantics &Sem,
1183 bool Negative = false) {
1184 APFloat Val(Sem, uninitialized);
1185 Val.makeSmallestNormalized(Negative);
1186 return Val;
1187 }
1188
1189 /// Returns a float which is bitcasted from an all one value int.
1190 ///
1191 /// \param Semantics - type float semantics
1192 LLVM_ABI static APFloat getAllOnesValue(const fltSemantics &Semantics);
1193
1194 /// Returns true if the given semantics has actual significand.
1195 ///
1196 /// \param Sem - type float semantics
hasSignificand(const fltSemantics & Sem)1197 static bool hasSignificand(const fltSemantics &Sem) {
1198 return &Sem != &Float8E8M0FNU();
1199 }
1200
1201 /// Used to insert APFloat objects, or objects that contain APFloat objects,
1202 /// into FoldingSets.
1203 LLVM_ABI void Profile(FoldingSetNodeID &NID) const;
1204
add(const APFloat & RHS,roundingMode RM)1205 opStatus add(const APFloat &RHS, roundingMode RM) {
1206 assert(&getSemantics() == &RHS.getSemantics() &&
1207 "Should only call on two APFloats with the same semantics");
1208 if (usesLayout<IEEEFloat>(getSemantics()))
1209 return U.IEEE.add(RHS.U.IEEE, RM);
1210 if (usesLayout<DoubleAPFloat>(getSemantics()))
1211 return U.Double.add(RHS.U.Double, RM);
1212 llvm_unreachable("Unexpected semantics");
1213 }
subtract(const APFloat & RHS,roundingMode RM)1214 opStatus subtract(const APFloat &RHS, roundingMode RM) {
1215 assert(&getSemantics() == &RHS.getSemantics() &&
1216 "Should only call on two APFloats with the same semantics");
1217 if (usesLayout<IEEEFloat>(getSemantics()))
1218 return U.IEEE.subtract(RHS.U.IEEE, RM);
1219 if (usesLayout<DoubleAPFloat>(getSemantics()))
1220 return U.Double.subtract(RHS.U.Double, RM);
1221 llvm_unreachable("Unexpected semantics");
1222 }
multiply(const APFloat & RHS,roundingMode RM)1223 opStatus multiply(const APFloat &RHS, roundingMode RM) {
1224 assert(&getSemantics() == &RHS.getSemantics() &&
1225 "Should only call on two APFloats with the same semantics");
1226 if (usesLayout<IEEEFloat>(getSemantics()))
1227 return U.IEEE.multiply(RHS.U.IEEE, RM);
1228 if (usesLayout<DoubleAPFloat>(getSemantics()))
1229 return U.Double.multiply(RHS.U.Double, RM);
1230 llvm_unreachable("Unexpected semantics");
1231 }
divide(const APFloat & RHS,roundingMode RM)1232 opStatus divide(const APFloat &RHS, roundingMode RM) {
1233 assert(&getSemantics() == &RHS.getSemantics() &&
1234 "Should only call on two APFloats with the same semantics");
1235 if (usesLayout<IEEEFloat>(getSemantics()))
1236 return U.IEEE.divide(RHS.U.IEEE, RM);
1237 if (usesLayout<DoubleAPFloat>(getSemantics()))
1238 return U.Double.divide(RHS.U.Double, RM);
1239 llvm_unreachable("Unexpected semantics");
1240 }
remainder(const APFloat & RHS)1241 opStatus remainder(const APFloat &RHS) {
1242 assert(&getSemantics() == &RHS.getSemantics() &&
1243 "Should only call on two APFloats with the same semantics");
1244 if (usesLayout<IEEEFloat>(getSemantics()))
1245 return U.IEEE.remainder(RHS.U.IEEE);
1246 if (usesLayout<DoubleAPFloat>(getSemantics()))
1247 return U.Double.remainder(RHS.U.Double);
1248 llvm_unreachable("Unexpected semantics");
1249 }
mod(const APFloat & RHS)1250 opStatus mod(const APFloat &RHS) {
1251 assert(&getSemantics() == &RHS.getSemantics() &&
1252 "Should only call on two APFloats with the same semantics");
1253 if (usesLayout<IEEEFloat>(getSemantics()))
1254 return U.IEEE.mod(RHS.U.IEEE);
1255 if (usesLayout<DoubleAPFloat>(getSemantics()))
1256 return U.Double.mod(RHS.U.Double);
1257 llvm_unreachable("Unexpected semantics");
1258 }
fusedMultiplyAdd(const APFloat & Multiplicand,const APFloat & Addend,roundingMode RM)1259 opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend,
1260 roundingMode RM) {
1261 assert(&getSemantics() == &Multiplicand.getSemantics() &&
1262 "Should only call on APFloats with the same semantics");
1263 assert(&getSemantics() == &Addend.getSemantics() &&
1264 "Should only call on APFloats with the same semantics");
1265 if (usesLayout<IEEEFloat>(getSemantics()))
1266 return U.IEEE.fusedMultiplyAdd(Multiplicand.U.IEEE, Addend.U.IEEE, RM);
1267 if (usesLayout<DoubleAPFloat>(getSemantics()))
1268 return U.Double.fusedMultiplyAdd(Multiplicand.U.Double, Addend.U.Double,
1269 RM);
1270 llvm_unreachable("Unexpected semantics");
1271 }
roundToIntegral(roundingMode RM)1272 opStatus roundToIntegral(roundingMode RM) {
1273 APFLOAT_DISPATCH_ON_SEMANTICS(roundToIntegral(RM));
1274 }
1275
1276 // TODO: bool parameters are not readable and a source of bugs.
1277 // Do something.
next(bool nextDown)1278 opStatus next(bool nextDown) {
1279 APFLOAT_DISPATCH_ON_SEMANTICS(next(nextDown));
1280 }
1281
1282 /// Negate an APFloat.
1283 APFloat operator-() const {
1284 APFloat Result(*this);
1285 Result.changeSign();
1286 return Result;
1287 }
1288
1289 /// Add two APFloats, rounding ties to the nearest even.
1290 /// No error checking.
1291 APFloat operator+(const APFloat &RHS) const {
1292 APFloat Result(*this);
1293 (void)Result.add(RHS, rmNearestTiesToEven);
1294 return Result;
1295 }
1296
1297 /// Subtract two APFloats, rounding ties to the nearest even.
1298 /// No error checking.
1299 APFloat operator-(const APFloat &RHS) const {
1300 APFloat Result(*this);
1301 (void)Result.subtract(RHS, rmNearestTiesToEven);
1302 return Result;
1303 }
1304
1305 /// Multiply two APFloats, rounding ties to the nearest even.
1306 /// No error checking.
1307 APFloat operator*(const APFloat &RHS) const {
1308 APFloat Result(*this);
1309 (void)Result.multiply(RHS, rmNearestTiesToEven);
1310 return Result;
1311 }
1312
1313 /// Divide the first APFloat by the second, rounding ties to the nearest even.
1314 /// No error checking.
1315 APFloat operator/(const APFloat &RHS) const {
1316 APFloat Result(*this);
1317 (void)Result.divide(RHS, rmNearestTiesToEven);
1318 return Result;
1319 }
1320
changeSign()1321 void changeSign() { APFLOAT_DISPATCH_ON_SEMANTICS(changeSign()); }
clearSign()1322 void clearSign() {
1323 if (isNegative())
1324 changeSign();
1325 }
copySign(const APFloat & RHS)1326 void copySign(const APFloat &RHS) {
1327 if (isNegative() != RHS.isNegative())
1328 changeSign();
1329 }
1330
1331 /// A static helper to produce a copy of an APFloat value with its sign
1332 /// copied from some other APFloat.
copySign(APFloat Value,const APFloat & Sign)1333 static APFloat copySign(APFloat Value, const APFloat &Sign) {
1334 Value.copySign(Sign);
1335 return Value;
1336 }
1337
1338 /// Assuming this is an IEEE-754 NaN value, quiet its signaling bit.
1339 /// This preserves the sign and payload bits.
makeQuiet()1340 APFloat makeQuiet() const {
1341 APFloat Result(*this);
1342 Result.getIEEE().makeQuiet();
1343 return Result;
1344 }
1345
1346 LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM,
1347 bool *losesInfo);
convertToInteger(MutableArrayRef<integerPart> Input,unsigned int Width,bool IsSigned,roundingMode RM,bool * IsExact)1348 opStatus convertToInteger(MutableArrayRef<integerPart> Input,
1349 unsigned int Width, bool IsSigned, roundingMode RM,
1350 bool *IsExact) const {
1351 APFLOAT_DISPATCH_ON_SEMANTICS(
1352 convertToInteger(Input, Width, IsSigned, RM, IsExact));
1353 }
1354 LLVM_ABI opStatus convertToInteger(APSInt &Result, roundingMode RM,
1355 bool *IsExact) const;
convertFromAPInt(const APInt & Input,bool IsSigned,roundingMode RM)1356 opStatus convertFromAPInt(const APInt &Input, bool IsSigned,
1357 roundingMode RM) {
1358 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromAPInt(Input, IsSigned, RM));
1359 }
convertFromSignExtendedInteger(const integerPart * Input,unsigned int InputSize,bool IsSigned,roundingMode RM)1360 opStatus convertFromSignExtendedInteger(const integerPart *Input,
1361 unsigned int InputSize, bool IsSigned,
1362 roundingMode RM) {
1363 APFLOAT_DISPATCH_ON_SEMANTICS(
1364 convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM));
1365 }
convertFromZeroExtendedInteger(const integerPart * Input,unsigned int InputSize,bool IsSigned,roundingMode RM)1366 opStatus convertFromZeroExtendedInteger(const integerPart *Input,
1367 unsigned int InputSize, bool IsSigned,
1368 roundingMode RM) {
1369 APFLOAT_DISPATCH_ON_SEMANTICS(
1370 convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM));
1371 }
1372 LLVM_ABI Expected<opStatus> convertFromString(StringRef, roundingMode);
bitcastToAPInt()1373 APInt bitcastToAPInt() const {
1374 APFLOAT_DISPATCH_ON_SEMANTICS(bitcastToAPInt());
1375 }
1376
1377 /// Converts this APFloat to host double value.
1378 ///
1379 /// \pre The APFloat must be built using semantics, that can be represented by
1380 /// the host double type without loss of precision. It can be IEEEdouble and
1381 /// shorter semantics, like IEEEsingle and others.
1382 LLVM_ABI double convertToDouble() const;
1383
1384 /// Converts this APFloat to host float value.
1385 ///
1386 /// \pre The APFloat must be built using semantics, that can be represented by
1387 /// the host float type without loss of precision. It can be IEEEquad and
1388 /// shorter semantics, like IEEEdouble and others.
1389 #ifdef HAS_IEE754_FLOAT128
1390 LLVM_ABI float128 convertToQuad() const;
1391 #endif
1392
1393 /// Converts this APFloat to host float value.
1394 ///
1395 /// \pre The APFloat must be built using semantics, that can be represented by
1396 /// the host float type without loss of precision. It can be IEEEsingle and
1397 /// shorter semantics, like IEEEhalf.
1398 LLVM_ABI float convertToFloat() const;
1399
1400 bool operator==(const APFloat &RHS) const { return compare(RHS) == cmpEqual; }
1401
1402 bool operator!=(const APFloat &RHS) const { return compare(RHS) != cmpEqual; }
1403
1404 bool operator<(const APFloat &RHS) const {
1405 return compare(RHS) == cmpLessThan;
1406 }
1407
1408 bool operator>(const APFloat &RHS) const {
1409 return compare(RHS) == cmpGreaterThan;
1410 }
1411
1412 bool operator<=(const APFloat &RHS) const {
1413 cmpResult Res = compare(RHS);
1414 return Res == cmpLessThan || Res == cmpEqual;
1415 }
1416
1417 bool operator>=(const APFloat &RHS) const {
1418 cmpResult Res = compare(RHS);
1419 return Res == cmpGreaterThan || Res == cmpEqual;
1420 }
1421
compare(const APFloat & RHS)1422 cmpResult compare(const APFloat &RHS) const {
1423 assert(&getSemantics() == &RHS.getSemantics() &&
1424 "Should only compare APFloats with the same semantics");
1425 if (usesLayout<IEEEFloat>(getSemantics()))
1426 return U.IEEE.compare(RHS.U.IEEE);
1427 if (usesLayout<DoubleAPFloat>(getSemantics()))
1428 return U.Double.compare(RHS.U.Double);
1429 llvm_unreachable("Unexpected semantics");
1430 }
1431
bitwiseIsEqual(const APFloat & RHS)1432 bool bitwiseIsEqual(const APFloat &RHS) const {
1433 if (&getSemantics() != &RHS.getSemantics())
1434 return false;
1435 if (usesLayout<IEEEFloat>(getSemantics()))
1436 return U.IEEE.bitwiseIsEqual(RHS.U.IEEE);
1437 if (usesLayout<DoubleAPFloat>(getSemantics()))
1438 return U.Double.bitwiseIsEqual(RHS.U.Double);
1439 llvm_unreachable("Unexpected semantics");
1440 }
1441
1442 /// We don't rely on operator== working on double values, as
1443 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1444 /// As such, this method can be used to do an exact bit-for-bit comparison of
1445 /// two floating point values.
1446 ///
1447 /// We leave the version with the double argument here because it's just so
1448 /// convenient to write "2.0" and the like. Without this function we'd
1449 /// have to duplicate its logic everywhere it's called.
isExactlyValue(double V)1450 bool isExactlyValue(double V) const {
1451 bool ignored;
1452 APFloat Tmp(V);
1453 Tmp.convert(getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
1454 return bitwiseIsEqual(Tmp);
1455 }
1456
convertToHexString(char * DST,unsigned int HexDigits,bool UpperCase,roundingMode RM)1457 unsigned int convertToHexString(char *DST, unsigned int HexDigits,
1458 bool UpperCase, roundingMode RM) const {
1459 APFLOAT_DISPATCH_ON_SEMANTICS(
1460 convertToHexString(DST, HexDigits, UpperCase, RM));
1461 }
1462
isZero()1463 bool isZero() const { return getCategory() == fcZero; }
isInfinity()1464 bool isInfinity() const { return getCategory() == fcInfinity; }
isNaN()1465 bool isNaN() const { return getCategory() == fcNaN; }
1466
isNegative()1467 bool isNegative() const { return getIEEE().isNegative(); }
isDenormal()1468 bool isDenormal() const { APFLOAT_DISPATCH_ON_SEMANTICS(isDenormal()); }
isSignaling()1469 bool isSignaling() const { return getIEEE().isSignaling(); }
1470
isNormal()1471 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); }
isFinite()1472 bool isFinite() const { return !isNaN() && !isInfinity(); }
1473
getCategory()1474 fltCategory getCategory() const { return getIEEE().getCategory(); }
getSemantics()1475 const fltSemantics &getSemantics() const { return *U.semantics; }
isNonZero()1476 bool isNonZero() const { return !isZero(); }
isFiniteNonZero()1477 bool isFiniteNonZero() const { return isFinite() && !isZero(); }
isPosZero()1478 bool isPosZero() const { return isZero() && !isNegative(); }
isNegZero()1479 bool isNegZero() const { return isZero() && isNegative(); }
isPosInfinity()1480 bool isPosInfinity() const { return isInfinity() && !isNegative(); }
isNegInfinity()1481 bool isNegInfinity() const { return isInfinity() && isNegative(); }
isSmallest()1482 bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); }
isLargest()1483 bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); }
isInteger()1484 bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); }
1485
isSmallestNormalized()1486 bool isSmallestNormalized() const {
1487 APFLOAT_DISPATCH_ON_SEMANTICS(isSmallestNormalized());
1488 }
1489
1490 /// Return the FPClassTest which will return true for the value.
1491 LLVM_ABI FPClassTest classify() const;
1492
1493 APFloat &operator=(const APFloat &RHS) = default;
1494 APFloat &operator=(APFloat &&RHS) = default;
1495
1496 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0,
1497 unsigned FormatMaxPadding = 3, bool TruncateZero = true) const {
1498 APFLOAT_DISPATCH_ON_SEMANTICS(
1499 toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero));
1500 }
1501
1502 LLVM_ABI void print(raw_ostream &) const;
1503
1504 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1505 LLVM_DUMP_METHOD void dump() const;
1506 #endif
1507
getExactInverse(APFloat * inv)1508 bool getExactInverse(APFloat *inv) const {
1509 APFLOAT_DISPATCH_ON_SEMANTICS(getExactInverse(inv));
1510 }
1511
1512 LLVM_READONLY
getExactLog2Abs()1513 int getExactLog2Abs() const {
1514 APFLOAT_DISPATCH_ON_SEMANTICS(getExactLog2Abs());
1515 }
1516
1517 LLVM_READONLY
getExactLog2()1518 int getExactLog2() const {
1519 APFLOAT_DISPATCH_ON_SEMANTICS(getExactLog2());
1520 }
1521
1522 LLVM_ABI friend hash_code hash_value(const APFloat &Arg);
ilogb(const APFloat & Arg)1523 friend int ilogb(const APFloat &Arg) { return ilogb(Arg.getIEEE()); }
1524 friend APFloat scalbn(APFloat X, int Exp, roundingMode RM);
1525 friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM);
1526 friend IEEEFloat;
1527 friend DoubleAPFloat;
1528 };
1529
1530 static_assert(sizeof(APFloat) == sizeof(detail::IEEEFloat),
1531 "Empty base class optimization is not performed.");
1532
1533 /// See friend declarations above.
1534 ///
1535 /// These additional declarations are required in order to compile LLVM with IBM
1536 /// xlC compiler.
1537 LLVM_ABI hash_code hash_value(const APFloat &Arg);
scalbn(APFloat X,int Exp,APFloat::roundingMode RM)1538 inline APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM) {
1539 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1540 return APFloat(scalbn(X.U.IEEE, Exp, RM), X.getSemantics());
1541 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1542 return APFloat(scalbn(X.U.Double, Exp, RM), X.getSemantics());
1543 llvm_unreachable("Unexpected semantics");
1544 }
1545
1546 /// Equivalent of C standard library function.
1547 ///
1548 /// While the C standard says Exp is an unspecified value for infinity and nan,
1549 /// this returns INT_MAX for infinities, and INT_MIN for NaNs.
frexp(const APFloat & X,int & Exp,APFloat::roundingMode RM)1550 inline APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM) {
1551 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics()))
1552 return APFloat(frexp(X.U.IEEE, Exp, RM), X.getSemantics());
1553 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics()))
1554 return APFloat(frexp(X.U.Double, Exp, RM), X.getSemantics());
1555 llvm_unreachable("Unexpected semantics");
1556 }
1557 /// Returns the absolute value of the argument.
abs(APFloat X)1558 inline APFloat abs(APFloat X) {
1559 X.clearSign();
1560 return X;
1561 }
1562
1563 /// Returns the negated value of the argument.
neg(APFloat X)1564 inline APFloat neg(APFloat X) {
1565 X.changeSign();
1566 return X;
1567 }
1568
1569 /// Implements IEEE-754 2008 minNum semantics. Returns the smaller of the
1570 /// 2 arguments if both are not NaN. If either argument is a qNaN, returns the
1571 /// other argument. If either argument is sNaN, return a qNaN.
1572 /// -0 is treated as ordered less than +0.
1573 LLVM_READONLY
minnum(const APFloat & A,const APFloat & B)1574 inline APFloat minnum(const APFloat &A, const APFloat &B) {
1575 if (A.isSignaling())
1576 return A.makeQuiet();
1577 if (B.isSignaling())
1578 return B.makeQuiet();
1579 if (A.isNaN())
1580 return B;
1581 if (B.isNaN())
1582 return A;
1583 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1584 return A.isNegative() ? A : B;
1585 return B < A ? B : A;
1586 }
1587
1588 /// Implements IEEE-754 2008 maxNum semantics. Returns the larger of the
1589 /// 2 arguments if both are not NaN. If either argument is a qNaN, returns the
1590 /// other argument. If either argument is sNaN, return a qNaN.
1591 /// +0 is treated as ordered greater than -0.
1592 LLVM_READONLY
maxnum(const APFloat & A,const APFloat & B)1593 inline APFloat maxnum(const APFloat &A, const APFloat &B) {
1594 if (A.isSignaling())
1595 return A.makeQuiet();
1596 if (B.isSignaling())
1597 return B.makeQuiet();
1598 if (A.isNaN())
1599 return B;
1600 if (B.isNaN())
1601 return A;
1602 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1603 return A.isNegative() ? B : A;
1604 return A < B ? B : A;
1605 }
1606
1607 /// Implements IEEE 754-2019 minimum semantics. Returns the smaller of 2
1608 /// arguments, returning a quiet NaN if an argument is a NaN and treating -0
1609 /// as less than +0.
1610 LLVM_READONLY
minimum(const APFloat & A,const APFloat & B)1611 inline APFloat minimum(const APFloat &A, const APFloat &B) {
1612 if (A.isNaN())
1613 return A.makeQuiet();
1614 if (B.isNaN())
1615 return B.makeQuiet();
1616 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1617 return A.isNegative() ? A : B;
1618 return B < A ? B : A;
1619 }
1620
1621 /// Implements IEEE 754-2019 minimumNumber semantics. Returns the smaller
1622 /// of 2 arguments, not propagating NaNs and treating -0 as less than +0.
1623 LLVM_READONLY
minimumnum(const APFloat & A,const APFloat & B)1624 inline APFloat minimumnum(const APFloat &A, const APFloat &B) {
1625 if (A.isNaN())
1626 return B.isNaN() ? B.makeQuiet() : B;
1627 if (B.isNaN())
1628 return A;
1629 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1630 return A.isNegative() ? A : B;
1631 return B < A ? B : A;
1632 }
1633
1634 /// Implements IEEE 754-2019 maximum semantics. Returns the larger of 2
1635 /// arguments, returning a quiet NaN if an argument is a NaN and treating -0
1636 /// as less than +0.
1637 LLVM_READONLY
maximum(const APFloat & A,const APFloat & B)1638 inline APFloat maximum(const APFloat &A, const APFloat &B) {
1639 if (A.isNaN())
1640 return A.makeQuiet();
1641 if (B.isNaN())
1642 return B.makeQuiet();
1643 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1644 return A.isNegative() ? B : A;
1645 return A < B ? B : A;
1646 }
1647
1648 /// Implements IEEE 754-2019 maximumNumber semantics. Returns the larger
1649 /// of 2 arguments, not propagating NaNs and treating -0 as less than +0.
1650 LLVM_READONLY
maximumnum(const APFloat & A,const APFloat & B)1651 inline APFloat maximumnum(const APFloat &A, const APFloat &B) {
1652 if (A.isNaN())
1653 return B.isNaN() ? B.makeQuiet() : B;
1654 if (B.isNaN())
1655 return A;
1656 if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative()))
1657 return A.isNegative() ? B : A;
1658 return A < B ? B : A;
1659 }
1660
1661 inline raw_ostream &operator<<(raw_ostream &OS, const APFloat &V) {
1662 V.print(OS);
1663 return OS;
1664 }
1665
1666 // We want the following functions to be available in the header for inlining.
1667 // We cannot define them inline in the class definition of `DoubleAPFloat`
1668 // because doing so would instantiate `std::unique_ptr<APFloat[]>` before
1669 // `APFloat` is defined, and that would be undefined behavior.
1670 namespace detail {
1671
1672 DoubleAPFloat &DoubleAPFloat::operator=(DoubleAPFloat &&RHS) {
1673 if (this != &RHS) {
1674 this->~DoubleAPFloat();
1675 new (this) DoubleAPFloat(std::move(RHS));
1676 }
1677 return *this;
1678 }
1679
getFirst()1680 APFloat &DoubleAPFloat::getFirst() { return Floats[0]; }
getFirst()1681 const APFloat &DoubleAPFloat::getFirst() const { return Floats[0]; }
getSecond()1682 APFloat &DoubleAPFloat::getSecond() { return Floats[1]; }
getSecond()1683 const APFloat &DoubleAPFloat::getSecond() const { return Floats[1]; }
1684
~DoubleAPFloat()1685 inline DoubleAPFloat::~DoubleAPFloat() { delete[] Floats; }
1686
1687 } // namespace detail
1688
1689 } // namespace llvm
1690
1691 #undef APFLOAT_DISPATCH_ON_SEMANTICS
1692 #endif // LLVM_ADT_APFLOAT_H
1693