File: | build/source/llvm/lib/Support/APFloat.cpp |
Warning: | line 2515, column 7 Potential memory leak |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===-- APFloat.cpp - Implement APFloat class -----------------------------===// | ||||
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 | // This file implements a class to represent arbitrary precision floating | ||||
10 | // point values and provide a variety of arithmetic operations on them. | ||||
11 | // | ||||
12 | //===----------------------------------------------------------------------===// | ||||
13 | |||||
14 | #include "llvm/ADT/APFloat.h" | ||||
15 | #include "llvm/ADT/APSInt.h" | ||||
16 | #include "llvm/ADT/ArrayRef.h" | ||||
17 | #include "llvm/ADT/FloatingPointMode.h" | ||||
18 | #include "llvm/ADT/FoldingSet.h" | ||||
19 | #include "llvm/ADT/Hashing.h" | ||||
20 | #include "llvm/ADT/STLExtras.h" | ||||
21 | #include "llvm/ADT/StringExtras.h" | ||||
22 | #include "llvm/ADT/StringRef.h" | ||||
23 | #include "llvm/Config/llvm-config.h" | ||||
24 | #include "llvm/Support/Debug.h" | ||||
25 | #include "llvm/Support/Error.h" | ||||
26 | #include "llvm/Support/MathExtras.h" | ||||
27 | #include "llvm/Support/raw_ostream.h" | ||||
28 | #include <cstring> | ||||
29 | #include <limits.h> | ||||
30 | |||||
31 | #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \ | ||||
32 | do { \ | ||||
33 | if (usesLayout<IEEEFloat>(getSemantics())) \ | ||||
34 | return U.IEEE.METHOD_CALL; \ | ||||
35 | if (usesLayout<DoubleAPFloat>(getSemantics())) \ | ||||
36 | return U.Double.METHOD_CALL; \ | ||||
37 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/lib/Support/APFloat.cpp" , 37); \ | ||||
38 | } while (false) | ||||
39 | |||||
40 | using namespace llvm; | ||||
41 | |||||
42 | /// A macro used to combine two fcCategory enums into one key which can be used | ||||
43 | /// in a switch statement to classify how the interaction of two APFloat's | ||||
44 | /// categories affects an operation. | ||||
45 | /// | ||||
46 | /// TODO: If clang source code is ever allowed to use constexpr in its own | ||||
47 | /// codebase, change this into a static inline function. | ||||
48 | #define PackCategoriesIntoKey(_lhs, _rhs)((_lhs) * 4 + (_rhs)) ((_lhs) * 4 + (_rhs)) | ||||
49 | |||||
50 | /* Assumed in hexadecimal significand parsing, and conversion to | ||||
51 | hexadecimal strings. */ | ||||
52 | static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!"); | ||||
53 | |||||
54 | namespace llvm { | ||||
55 | |||||
56 | // How the nonfinite values Inf and NaN are represented. | ||||
57 | enum class fltNonfiniteBehavior { | ||||
58 | // Represents standard IEEE 754 behavior. A value is nonfinite if the | ||||
59 | // exponent field is all 1s. In such cases, a value is Inf if the | ||||
60 | // significand bits are all zero, and NaN otherwise | ||||
61 | IEEE754, | ||||
62 | |||||
63 | // This behavior is present in the Float8ExMyFN* types (Float8E4M3FN, | ||||
64 | // Float8E5M2FNUZ, Float8E4M3FNUZ, and Float8E4M3B11FNUZ). There is no | ||||
65 | // representation for Inf, and operations that would ordinarily produce Inf | ||||
66 | // produce NaN instead. | ||||
67 | // The details of the NaN representation(s) in this form are determined by the | ||||
68 | // `fltNanEncoding` enum. We treat all NaNs as quiet, as the available | ||||
69 | // encodings do not distinguish between signalling and quiet NaN. | ||||
70 | NanOnly, | ||||
71 | }; | ||||
72 | |||||
73 | // How NaN values are represented. This is curently only used in combination | ||||
74 | // with fltNonfiniteBehavior::NanOnly, and using a variant other than IEEE | ||||
75 | // while having IEEE non-finite behavior is liable to lead to unexpected | ||||
76 | // results. | ||||
77 | enum class fltNanEncoding { | ||||
78 | // Represents the standard IEEE behavior where a value is NaN if its | ||||
79 | // exponent is all 1s and the significand is non-zero. | ||||
80 | IEEE, | ||||
81 | |||||
82 | // Represents the behavior in the Float8E4M3 floating point type where NaN is | ||||
83 | // represented by having the exponent and mantissa set to all 1s. | ||||
84 | // This behavior matches the FP8 E4M3 type described in | ||||
85 | // https://arxiv.org/abs/2209.05433. We treat both signed and unsigned NaNs | ||||
86 | // as non-signalling, although the paper does not state whether the NaN | ||||
87 | // values are signalling or not. | ||||
88 | AllOnes, | ||||
89 | |||||
90 | // Represents the behavior in Float8E{5,4}E{2,3}FNUZ floating point types | ||||
91 | // where NaN is represented by a sign bit of 1 and all 0s in the exponent | ||||
92 | // and mantissa (i.e. the negative zero encoding in a IEEE float). Since | ||||
93 | // there is only one NaN value, it is treated as quiet NaN. This matches the | ||||
94 | // behavior described in https://arxiv.org/abs/2206.02915 . | ||||
95 | NegativeZero, | ||||
96 | }; | ||||
97 | |||||
98 | /* Represents floating point arithmetic semantics. */ | ||||
99 | struct fltSemantics { | ||||
100 | /* The largest E such that 2^E is representable; this matches the | ||||
101 | definition of IEEE 754. */ | ||||
102 | APFloatBase::ExponentType maxExponent; | ||||
103 | |||||
104 | /* The smallest E such that 2^E is a normalized number; this | ||||
105 | matches the definition of IEEE 754. */ | ||||
106 | APFloatBase::ExponentType minExponent; | ||||
107 | |||||
108 | /* Number of bits in the significand. This includes the integer | ||||
109 | bit. */ | ||||
110 | unsigned int precision; | ||||
111 | |||||
112 | /* Number of bits actually used in the semantics. */ | ||||
113 | unsigned int sizeInBits; | ||||
114 | |||||
115 | fltNonfiniteBehavior nonFiniteBehavior = fltNonfiniteBehavior::IEEE754; | ||||
116 | |||||
117 | fltNanEncoding nanEncoding = fltNanEncoding::IEEE; | ||||
118 | // Returns true if any number described by this semantics can be precisely | ||||
119 | // represented by the specified semantics. Does not take into account | ||||
120 | // the value of fltNonfiniteBehavior. | ||||
121 | bool isRepresentableBy(const fltSemantics &S) const { | ||||
122 | return maxExponent <= S.maxExponent && minExponent >= S.minExponent && | ||||
123 | precision <= S.precision; | ||||
124 | } | ||||
125 | }; | ||||
126 | |||||
127 | static constexpr fltSemantics semIEEEhalf = {15, -14, 11, 16}; | ||||
128 | static constexpr fltSemantics semBFloat = {127, -126, 8, 16}; | ||||
129 | static constexpr fltSemantics semIEEEsingle = {127, -126, 24, 32}; | ||||
130 | static constexpr fltSemantics semIEEEdouble = {1023, -1022, 53, 64}; | ||||
131 | static constexpr fltSemantics semIEEEquad = {16383, -16382, 113, 128}; | ||||
132 | static constexpr fltSemantics semFloat8E5M2 = {15, -14, 3, 8}; | ||||
133 | static constexpr fltSemantics semFloat8E5M2FNUZ = { | ||||
134 | 15, -15, 3, 8, fltNonfiniteBehavior::NanOnly, fltNanEncoding::NegativeZero}; | ||||
135 | static constexpr fltSemantics semFloat8E4M3FN = { | ||||
136 | 8, -6, 4, 8, fltNonfiniteBehavior::NanOnly, fltNanEncoding::AllOnes}; | ||||
137 | static constexpr fltSemantics semFloat8E4M3FNUZ = { | ||||
138 | 7, -7, 4, 8, fltNonfiniteBehavior::NanOnly, fltNanEncoding::NegativeZero}; | ||||
139 | static constexpr fltSemantics semFloat8E4M3B11FNUZ = { | ||||
140 | 4, -10, 4, 8, fltNonfiniteBehavior::NanOnly, fltNanEncoding::NegativeZero}; | ||||
141 | static constexpr fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80}; | ||||
142 | static constexpr fltSemantics semBogus = {0, 0, 0, 0}; | ||||
143 | |||||
144 | /* The IBM double-double semantics. Such a number consists of a pair of IEEE | ||||
145 | 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal, | ||||
146 | (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo. | ||||
147 | Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent | ||||
148 | to each other, and two 11-bit exponents. | ||||
149 | |||||
150 | Note: we need to make the value different from semBogus as otherwise | ||||
151 | an unsafe optimization may collapse both values to a single address, | ||||
152 | and we heavily rely on them having distinct addresses. */ | ||||
153 | static constexpr fltSemantics semPPCDoubleDouble = {-1, 0, 0, 128}; | ||||
154 | |||||
155 | /* These are legacy semantics for the fallback, inaccrurate implementation of | ||||
156 | IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the | ||||
157 | operation. It's equivalent to having an IEEE number with consecutive 106 | ||||
158 | bits of mantissa and 11 bits of exponent. | ||||
159 | |||||
160 | It's not equivalent to IBM double-double. For example, a legit IBM | ||||
161 | double-double, 1 + epsilon: | ||||
162 | |||||
163 | 1 + epsilon = 1 + (1 >> 1076) | ||||
164 | |||||
165 | is not representable by a consecutive 106 bits of mantissa. | ||||
166 | |||||
167 | Currently, these semantics are used in the following way: | ||||
168 | |||||
169 | semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) -> | ||||
170 | (64-bit APInt, 64-bit APInt) -> (128-bit APInt) -> | ||||
171 | semPPCDoubleDoubleLegacy -> IEEE operations | ||||
172 | |||||
173 | We use bitcastToAPInt() to get the bit representation (in APInt) of the | ||||
174 | underlying IEEEdouble, then use the APInt constructor to construct the | ||||
175 | legacy IEEE float. | ||||
176 | |||||
177 | TODO: Implement all operations in semPPCDoubleDouble, and delete these | ||||
178 | semantics. */ | ||||
179 | static constexpr fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53, | ||||
180 | 53 + 53, 128}; | ||||
181 | |||||
182 | const llvm::fltSemantics &APFloatBase::EnumToSemantics(Semantics S) { | ||||
183 | switch (S) { | ||||
184 | case S_IEEEhalf: | ||||
185 | return IEEEhalf(); | ||||
186 | case S_BFloat: | ||||
187 | return BFloat(); | ||||
188 | case S_IEEEsingle: | ||||
189 | return IEEEsingle(); | ||||
190 | case S_IEEEdouble: | ||||
191 | return IEEEdouble(); | ||||
192 | case S_IEEEquad: | ||||
193 | return IEEEquad(); | ||||
194 | case S_PPCDoubleDouble: | ||||
195 | return PPCDoubleDouble(); | ||||
196 | case S_Float8E5M2: | ||||
197 | return Float8E5M2(); | ||||
198 | case S_Float8E5M2FNUZ: | ||||
199 | return Float8E5M2FNUZ(); | ||||
200 | case S_Float8E4M3FN: | ||||
201 | return Float8E4M3FN(); | ||||
202 | case S_Float8E4M3FNUZ: | ||||
203 | return Float8E4M3FNUZ(); | ||||
204 | case S_Float8E4M3B11FNUZ: | ||||
205 | return Float8E4M3B11FNUZ(); | ||||
206 | case S_x87DoubleExtended: | ||||
207 | return x87DoubleExtended(); | ||||
208 | } | ||||
209 | llvm_unreachable("Unrecognised floating semantics")::llvm::llvm_unreachable_internal("Unrecognised floating semantics" , "llvm/lib/Support/APFloat.cpp", 209); | ||||
210 | } | ||||
211 | |||||
212 | APFloatBase::Semantics | ||||
213 | APFloatBase::SemanticsToEnum(const llvm::fltSemantics &Sem) { | ||||
214 | if (&Sem == &llvm::APFloat::IEEEhalf()) | ||||
215 | return S_IEEEhalf; | ||||
216 | else if (&Sem == &llvm::APFloat::BFloat()) | ||||
217 | return S_BFloat; | ||||
218 | else if (&Sem == &llvm::APFloat::IEEEsingle()) | ||||
219 | return S_IEEEsingle; | ||||
220 | else if (&Sem == &llvm::APFloat::IEEEdouble()) | ||||
221 | return S_IEEEdouble; | ||||
222 | else if (&Sem == &llvm::APFloat::IEEEquad()) | ||||
223 | return S_IEEEquad; | ||||
224 | else if (&Sem == &llvm::APFloat::PPCDoubleDouble()) | ||||
225 | return S_PPCDoubleDouble; | ||||
226 | else if (&Sem == &llvm::APFloat::Float8E5M2()) | ||||
227 | return S_Float8E5M2; | ||||
228 | else if (&Sem == &llvm::APFloat::Float8E5M2FNUZ()) | ||||
229 | return S_Float8E5M2FNUZ; | ||||
230 | else if (&Sem == &llvm::APFloat::Float8E4M3FN()) | ||||
231 | return S_Float8E4M3FN; | ||||
232 | else if (&Sem == &llvm::APFloat::Float8E4M3FNUZ()) | ||||
233 | return S_Float8E4M3FNUZ; | ||||
234 | else if (&Sem == &llvm::APFloat::Float8E4M3B11FNUZ()) | ||||
235 | return S_Float8E4M3B11FNUZ; | ||||
236 | else if (&Sem == &llvm::APFloat::x87DoubleExtended()) | ||||
237 | return S_x87DoubleExtended; | ||||
238 | else | ||||
239 | llvm_unreachable("Unknown floating semantics")::llvm::llvm_unreachable_internal("Unknown floating semantics" , "llvm/lib/Support/APFloat.cpp", 239); | ||||
240 | } | ||||
241 | |||||
242 | const fltSemantics &APFloatBase::IEEEhalf() { return semIEEEhalf; } | ||||
243 | const fltSemantics &APFloatBase::BFloat() { return semBFloat; } | ||||
244 | const fltSemantics &APFloatBase::IEEEsingle() { return semIEEEsingle; } | ||||
245 | const fltSemantics &APFloatBase::IEEEdouble() { return semIEEEdouble; } | ||||
246 | const fltSemantics &APFloatBase::IEEEquad() { return semIEEEquad; } | ||||
247 | const fltSemantics &APFloatBase::PPCDoubleDouble() { | ||||
248 | return semPPCDoubleDouble; | ||||
249 | } | ||||
250 | const fltSemantics &APFloatBase::Float8E5M2() { return semFloat8E5M2; } | ||||
251 | const fltSemantics &APFloatBase::Float8E5M2FNUZ() { return semFloat8E5M2FNUZ; } | ||||
252 | const fltSemantics &APFloatBase::Float8E4M3FN() { return semFloat8E4M3FN; } | ||||
253 | const fltSemantics &APFloatBase::Float8E4M3FNUZ() { return semFloat8E4M3FNUZ; } | ||||
254 | const fltSemantics &APFloatBase::Float8E4M3B11FNUZ() { | ||||
255 | return semFloat8E4M3B11FNUZ; | ||||
256 | } | ||||
257 | const fltSemantics &APFloatBase::x87DoubleExtended() { | ||||
258 | return semX87DoubleExtended; | ||||
259 | } | ||||
260 | const fltSemantics &APFloatBase::Bogus() { return semBogus; } | ||||
261 | |||||
262 | constexpr RoundingMode APFloatBase::rmNearestTiesToEven; | ||||
263 | constexpr RoundingMode APFloatBase::rmTowardPositive; | ||||
264 | constexpr RoundingMode APFloatBase::rmTowardNegative; | ||||
265 | constexpr RoundingMode APFloatBase::rmTowardZero; | ||||
266 | constexpr RoundingMode APFloatBase::rmNearestTiesToAway; | ||||
267 | |||||
268 | /* A tight upper bound on number of parts required to hold the value | ||||
269 | pow(5, power) is | ||||
270 | |||||
271 | power * 815 / (351 * integerPartWidth) + 1 | ||||
272 | |||||
273 | However, whilst the result may require only this many parts, | ||||
274 | because we are multiplying two values to get it, the | ||||
275 | multiplication may require an extra part with the excess part | ||||
276 | being zero (consider the trivial case of 1 * 1, tcFullMultiply | ||||
277 | requires two parts to hold the single-part result). So we add an | ||||
278 | extra one to guarantee enough space whilst multiplying. */ | ||||
279 | const unsigned int maxExponent = 16383; | ||||
280 | const unsigned int maxPrecision = 113; | ||||
281 | const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1; | ||||
282 | const unsigned int maxPowerOfFiveParts = | ||||
283 | 2 + | ||||
284 | ((maxPowerOfFiveExponent * 815) / (351 * APFloatBase::integerPartWidth)); | ||||
285 | |||||
286 | unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) { | ||||
287 | return semantics.precision; | ||||
288 | } | ||||
289 | APFloatBase::ExponentType | ||||
290 | APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) { | ||||
291 | return semantics.maxExponent; | ||||
292 | } | ||||
293 | APFloatBase::ExponentType | ||||
294 | APFloatBase::semanticsMinExponent(const fltSemantics &semantics) { | ||||
295 | return semantics.minExponent; | ||||
296 | } | ||||
297 | unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) { | ||||
298 | return semantics.sizeInBits; | ||||
299 | } | ||||
300 | unsigned int APFloatBase::semanticsIntSizeInBits(const fltSemantics &semantics, | ||||
301 | bool isSigned) { | ||||
302 | // The max FP value is pow(2, MaxExponent) * (1 + MaxFraction), so we need | ||||
303 | // at least one more bit than the MaxExponent to hold the max FP value. | ||||
304 | unsigned int MinBitWidth = semanticsMaxExponent(semantics) + 1; | ||||
305 | // Extra sign bit needed. | ||||
306 | if (isSigned) | ||||
307 | ++MinBitWidth; | ||||
308 | return MinBitWidth; | ||||
309 | } | ||||
310 | |||||
311 | bool APFloatBase::isRepresentableAsNormalIn(const fltSemantics &Src, | ||||
312 | const fltSemantics &Dst) { | ||||
313 | // Exponent range must be larger. | ||||
314 | if (Src.maxExponent >= Dst.maxExponent || Src.minExponent <= Dst.minExponent) | ||||
315 | return false; | ||||
316 | |||||
317 | // If the mantissa is long enough, the result value could still be denormal | ||||
318 | // with a larger exponent range. | ||||
319 | // | ||||
320 | // FIXME: This condition is probably not accurate but also shouldn't be a | ||||
321 | // practical concern with existing types. | ||||
322 | return Dst.precision >= Src.precision; | ||||
323 | } | ||||
324 | |||||
325 | unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) { | ||||
326 | return Sem.sizeInBits; | ||||
327 | } | ||||
328 | |||||
329 | static constexpr APFloatBase::ExponentType | ||||
330 | exponentZero(const fltSemantics &semantics) { | ||||
331 | return semantics.minExponent - 1; | ||||
332 | } | ||||
333 | |||||
334 | static constexpr APFloatBase::ExponentType | ||||
335 | exponentInf(const fltSemantics &semantics) { | ||||
336 | return semantics.maxExponent + 1; | ||||
337 | } | ||||
338 | |||||
339 | static constexpr APFloatBase::ExponentType | ||||
340 | exponentNaN(const fltSemantics &semantics) { | ||||
341 | if (semantics.nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) { | ||||
342 | if (semantics.nanEncoding == fltNanEncoding::NegativeZero) | ||||
343 | return exponentZero(semantics); | ||||
344 | return semantics.maxExponent; | ||||
345 | } | ||||
346 | return semantics.maxExponent + 1; | ||||
347 | } | ||||
348 | |||||
349 | /* A bunch of private, handy routines. */ | ||||
350 | |||||
351 | static inline Error createError(const Twine &Err) { | ||||
352 | return make_error<StringError>(Err, inconvertibleErrorCode()); | ||||
353 | } | ||||
354 | |||||
355 | static constexpr inline unsigned int partCountForBits(unsigned int bits) { | ||||
356 | return ((bits) + APFloatBase::integerPartWidth - 1) / APFloatBase::integerPartWidth; | ||||
357 | } | ||||
358 | |||||
359 | /* Returns 0U-9U. Return values >= 10U are not digits. */ | ||||
360 | static inline unsigned int | ||||
361 | decDigitValue(unsigned int c) | ||||
362 | { | ||||
363 | return c - '0'; | ||||
364 | } | ||||
365 | |||||
366 | /* Return the value of a decimal exponent of the form | ||||
367 | [+-]ddddddd. | ||||
368 | |||||
369 | If the exponent overflows, returns a large exponent with the | ||||
370 | appropriate sign. */ | ||||
371 | static Expected<int> readExponent(StringRef::iterator begin, | ||||
372 | StringRef::iterator end) { | ||||
373 | bool isNegative; | ||||
374 | unsigned int absExponent; | ||||
375 | const unsigned int overlargeExponent = 24000; /* FIXME. */ | ||||
376 | StringRef::iterator p = begin; | ||||
377 | |||||
378 | // Treat no exponent as 0 to match binutils | ||||
379 | if (p == end || ((*p == '-' || *p == '+') && (p + 1) == end)) { | ||||
380 | return 0; | ||||
381 | } | ||||
382 | |||||
383 | isNegative = (*p == '-'); | ||||
384 | if (*p == '-' || *p == '+') { | ||||
385 | p++; | ||||
386 | if (p == end) | ||||
387 | return createError("Exponent has no digits"); | ||||
388 | } | ||||
389 | |||||
390 | absExponent = decDigitValue(*p++); | ||||
391 | if (absExponent >= 10U) | ||||
392 | return createError("Invalid character in exponent"); | ||||
393 | |||||
394 | for (; p != end; ++p) { | ||||
395 | unsigned int value; | ||||
396 | |||||
397 | value = decDigitValue(*p); | ||||
398 | if (value >= 10U) | ||||
399 | return createError("Invalid character in exponent"); | ||||
400 | |||||
401 | absExponent = absExponent * 10U + value; | ||||
402 | if (absExponent >= overlargeExponent) { | ||||
403 | absExponent = overlargeExponent; | ||||
404 | break; | ||||
405 | } | ||||
406 | } | ||||
407 | |||||
408 | if (isNegative) | ||||
409 | return -(int) absExponent; | ||||
410 | else | ||||
411 | return (int) absExponent; | ||||
412 | } | ||||
413 | |||||
414 | /* This is ugly and needs cleaning up, but I don't immediately see | ||||
415 | how whilst remaining safe. */ | ||||
416 | static Expected<int> totalExponent(StringRef::iterator p, | ||||
417 | StringRef::iterator end, | ||||
418 | int exponentAdjustment) { | ||||
419 | int unsignedExponent; | ||||
420 | bool negative, overflow; | ||||
421 | int exponent = 0; | ||||
422 | |||||
423 | if (p == end) | ||||
424 | return createError("Exponent has no digits"); | ||||
425 | |||||
426 | negative = *p == '-'; | ||||
427 | if (*p == '-' || *p == '+') { | ||||
428 | p++; | ||||
429 | if (p == end) | ||||
430 | return createError("Exponent has no digits"); | ||||
431 | } | ||||
432 | |||||
433 | unsignedExponent = 0; | ||||
434 | overflow = false; | ||||
435 | for (; p != end; ++p) { | ||||
436 | unsigned int value; | ||||
437 | |||||
438 | value = decDigitValue(*p); | ||||
439 | if (value >= 10U) | ||||
440 | return createError("Invalid character in exponent"); | ||||
441 | |||||
442 | unsignedExponent = unsignedExponent * 10 + value; | ||||
443 | if (unsignedExponent > 32767) { | ||||
444 | overflow = true; | ||||
445 | break; | ||||
446 | } | ||||
447 | } | ||||
448 | |||||
449 | if (exponentAdjustment > 32767 || exponentAdjustment < -32768) | ||||
450 | overflow = true; | ||||
451 | |||||
452 | if (!overflow) { | ||||
453 | exponent = unsignedExponent; | ||||
454 | if (negative) | ||||
455 | exponent = -exponent; | ||||
456 | exponent += exponentAdjustment; | ||||
457 | if (exponent > 32767 || exponent < -32768) | ||||
458 | overflow = true; | ||||
459 | } | ||||
460 | |||||
461 | if (overflow) | ||||
462 | exponent = negative ? -32768: 32767; | ||||
463 | |||||
464 | return exponent; | ||||
465 | } | ||||
466 | |||||
467 | static Expected<StringRef::iterator> | ||||
468 | skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, | ||||
469 | StringRef::iterator *dot) { | ||||
470 | StringRef::iterator p = begin; | ||||
471 | *dot = end; | ||||
472 | while (p != end && *p == '0') | ||||
473 | p++; | ||||
474 | |||||
475 | if (p != end && *p == '.') { | ||||
476 | *dot = p++; | ||||
477 | |||||
478 | if (end - begin == 1) | ||||
479 | return createError("Significand has no digits"); | ||||
480 | |||||
481 | while (p != end && *p == '0') | ||||
482 | p++; | ||||
483 | } | ||||
484 | |||||
485 | return p; | ||||
486 | } | ||||
487 | |||||
488 | /* Given a normal decimal floating point number of the form | ||||
489 | |||||
490 | dddd.dddd[eE][+-]ddd | ||||
491 | |||||
492 | where the decimal point and exponent are optional, fill out the | ||||
493 | structure D. Exponent is appropriate if the significand is | ||||
494 | treated as an integer, and normalizedExponent if the significand | ||||
495 | is taken to have the decimal point after a single leading | ||||
496 | non-zero digit. | ||||
497 | |||||
498 | If the value is zero, V->firstSigDigit points to a non-digit, and | ||||
499 | the return exponent is zero. | ||||
500 | */ | ||||
501 | struct decimalInfo { | ||||
502 | const char *firstSigDigit; | ||||
503 | const char *lastSigDigit; | ||||
504 | int exponent; | ||||
505 | int normalizedExponent; | ||||
506 | }; | ||||
507 | |||||
508 | static Error interpretDecimal(StringRef::iterator begin, | ||||
509 | StringRef::iterator end, decimalInfo *D) { | ||||
510 | StringRef::iterator dot = end; | ||||
511 | |||||
512 | auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot); | ||||
513 | if (!PtrOrErr) | ||||
514 | return PtrOrErr.takeError(); | ||||
515 | StringRef::iterator p = *PtrOrErr; | ||||
516 | |||||
517 | D->firstSigDigit = p; | ||||
518 | D->exponent = 0; | ||||
519 | D->normalizedExponent = 0; | ||||
520 | |||||
521 | for (; p != end; ++p) { | ||||
522 | if (*p == '.') { | ||||
523 | if (dot != end) | ||||
524 | return createError("String contains multiple dots"); | ||||
525 | dot = p++; | ||||
526 | if (p == end) | ||||
527 | break; | ||||
528 | } | ||||
529 | if (decDigitValue(*p) >= 10U) | ||||
530 | break; | ||||
531 | } | ||||
532 | |||||
533 | if (p != end) { | ||||
534 | if (*p != 'e' && *p != 'E') | ||||
535 | return createError("Invalid character in significand"); | ||||
536 | if (p == begin) | ||||
537 | return createError("Significand has no digits"); | ||||
538 | if (dot != end && p - begin == 1) | ||||
539 | return createError("Significand has no digits"); | ||||
540 | |||||
541 | /* p points to the first non-digit in the string */ | ||||
542 | auto ExpOrErr = readExponent(p + 1, end); | ||||
543 | if (!ExpOrErr) | ||||
544 | return ExpOrErr.takeError(); | ||||
545 | D->exponent = *ExpOrErr; | ||||
546 | |||||
547 | /* Implied decimal point? */ | ||||
548 | if (dot == end) | ||||
549 | dot = p; | ||||
550 | } | ||||
551 | |||||
552 | /* If number is all zeroes accept any exponent. */ | ||||
553 | if (p != D->firstSigDigit) { | ||||
554 | /* Drop insignificant trailing zeroes. */ | ||||
555 | if (p != begin) { | ||||
556 | do | ||||
557 | do | ||||
558 | p--; | ||||
559 | while (p != begin && *p == '0'); | ||||
560 | while (p != begin && *p == '.'); | ||||
561 | } | ||||
562 | |||||
563 | /* Adjust the exponents for any decimal point. */ | ||||
564 | D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p)); | ||||
565 | D->normalizedExponent = (D->exponent + | ||||
566 | static_cast<APFloat::ExponentType>((p - D->firstSigDigit) | ||||
567 | - (dot > D->firstSigDigit && dot < p))); | ||||
568 | } | ||||
569 | |||||
570 | D->lastSigDigit = p; | ||||
571 | return Error::success(); | ||||
572 | } | ||||
573 | |||||
574 | /* Return the trailing fraction of a hexadecimal number. | ||||
575 | DIGITVALUE is the first hex digit of the fraction, P points to | ||||
576 | the next digit. */ | ||||
577 | static Expected<lostFraction> | ||||
578 | trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, | ||||
579 | unsigned int digitValue) { | ||||
580 | unsigned int hexDigit; | ||||
581 | |||||
582 | /* If the first trailing digit isn't 0 or 8 we can work out the | ||||
583 | fraction immediately. */ | ||||
584 | if (digitValue > 8) | ||||
585 | return lfMoreThanHalf; | ||||
586 | else if (digitValue < 8 && digitValue > 0) | ||||
587 | return lfLessThanHalf; | ||||
588 | |||||
589 | // Otherwise we need to find the first non-zero digit. | ||||
590 | while (p != end && (*p == '0' || *p == '.')) | ||||
591 | p++; | ||||
592 | |||||
593 | if (p == end) | ||||
594 | return createError("Invalid trailing hexadecimal fraction!"); | ||||
595 | |||||
596 | hexDigit = hexDigitValue(*p); | ||||
597 | |||||
598 | /* If we ran off the end it is exactly zero or one-half, otherwise | ||||
599 | a little more. */ | ||||
600 | if (hexDigit == UINT_MAX(2147483647 *2U +1U)) | ||||
601 | return digitValue == 0 ? lfExactlyZero: lfExactlyHalf; | ||||
602 | else | ||||
603 | return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf; | ||||
604 | } | ||||
605 | |||||
606 | /* Return the fraction lost were a bignum truncated losing the least | ||||
607 | significant BITS bits. */ | ||||
608 | static lostFraction | ||||
609 | lostFractionThroughTruncation(const APFloatBase::integerPart *parts, | ||||
610 | unsigned int partCount, | ||||
611 | unsigned int bits) | ||||
612 | { | ||||
613 | unsigned int lsb; | ||||
614 | |||||
615 | lsb = APInt::tcLSB(parts, partCount); | ||||
616 | |||||
617 | /* Note this is guaranteed true if bits == 0, or LSB == UINT_MAX. */ | ||||
618 | if (bits <= lsb) | ||||
619 | return lfExactlyZero; | ||||
620 | if (bits == lsb + 1) | ||||
621 | return lfExactlyHalf; | ||||
622 | if (bits <= partCount * APFloatBase::integerPartWidth && | ||||
623 | APInt::tcExtractBit(parts, bits - 1)) | ||||
624 | return lfMoreThanHalf; | ||||
625 | |||||
626 | return lfLessThanHalf; | ||||
627 | } | ||||
628 | |||||
629 | /* Shift DST right BITS bits noting lost fraction. */ | ||||
630 | static lostFraction | ||||
631 | shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits) | ||||
632 | { | ||||
633 | lostFraction lost_fraction; | ||||
634 | |||||
635 | lost_fraction = lostFractionThroughTruncation(dst, parts, bits); | ||||
636 | |||||
637 | APInt::tcShiftRight(dst, parts, bits); | ||||
638 | |||||
639 | return lost_fraction; | ||||
640 | } | ||||
641 | |||||
642 | /* Combine the effect of two lost fractions. */ | ||||
643 | static lostFraction | ||||
644 | combineLostFractions(lostFraction moreSignificant, | ||||
645 | lostFraction lessSignificant) | ||||
646 | { | ||||
647 | if (lessSignificant != lfExactlyZero) { | ||||
648 | if (moreSignificant == lfExactlyZero) | ||||
649 | moreSignificant = lfLessThanHalf; | ||||
650 | else if (moreSignificant == lfExactlyHalf) | ||||
651 | moreSignificant = lfMoreThanHalf; | ||||
652 | } | ||||
653 | |||||
654 | return moreSignificant; | ||||
655 | } | ||||
656 | |||||
657 | /* The error from the true value, in half-ulps, on multiplying two | ||||
658 | floating point numbers, which differ from the value they | ||||
659 | approximate by at most HUE1 and HUE2 half-ulps, is strictly less | ||||
660 | than the returned value. | ||||
661 | |||||
662 | See "How to Read Floating Point Numbers Accurately" by William D | ||||
663 | Clinger. */ | ||||
664 | static unsigned int | ||||
665 | HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2) | ||||
666 | { | ||||
667 | assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8))(static_cast <bool> (HUerr1 < 2 || HUerr2 < 2 || ( HUerr1 + HUerr2 < 8)) ? void (0) : __assert_fail ("HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8)" , "llvm/lib/Support/APFloat.cpp", 667, __extension__ __PRETTY_FUNCTION__ )); | ||||
668 | |||||
669 | if (HUerr1 + HUerr2 == 0) | ||||
670 | return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */ | ||||
671 | else | ||||
672 | return inexactMultiply + 2 * (HUerr1 + HUerr2); | ||||
673 | } | ||||
674 | |||||
675 | /* The number of ulps from the boundary (zero, or half if ISNEAREST) | ||||
676 | when the least significant BITS are truncated. BITS cannot be | ||||
677 | zero. */ | ||||
678 | static APFloatBase::integerPart | ||||
679 | ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits, | ||||
680 | bool isNearest) { | ||||
681 | unsigned int count, partBits; | ||||
682 | APFloatBase::integerPart part, boundary; | ||||
683 | |||||
684 | assert(bits != 0)(static_cast <bool> (bits != 0) ? void (0) : __assert_fail ("bits != 0", "llvm/lib/Support/APFloat.cpp", 684, __extension__ __PRETTY_FUNCTION__)); | ||||
685 | |||||
686 | bits--; | ||||
687 | count = bits / APFloatBase::integerPartWidth; | ||||
688 | partBits = bits % APFloatBase::integerPartWidth + 1; | ||||
689 | |||||
690 | part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits)); | ||||
691 | |||||
692 | if (isNearest) | ||||
693 | boundary = (APFloatBase::integerPart) 1 << (partBits - 1); | ||||
694 | else | ||||
695 | boundary = 0; | ||||
696 | |||||
697 | if (count == 0) { | ||||
698 | if (part - boundary <= boundary - part) | ||||
699 | return part - boundary; | ||||
700 | else | ||||
701 | return boundary - part; | ||||
702 | } | ||||
703 | |||||
704 | if (part == boundary) { | ||||
705 | while (--count) | ||||
706 | if (parts[count]) | ||||
707 | return ~(APFloatBase::integerPart) 0; /* A lot. */ | ||||
708 | |||||
709 | return parts[0]; | ||||
710 | } else if (part == boundary - 1) { | ||||
711 | while (--count) | ||||
712 | if (~parts[count]) | ||||
713 | return ~(APFloatBase::integerPart) 0; /* A lot. */ | ||||
714 | |||||
715 | return -parts[0]; | ||||
716 | } | ||||
717 | |||||
718 | return ~(APFloatBase::integerPart) 0; /* A lot. */ | ||||
719 | } | ||||
720 | |||||
721 | /* Place pow(5, power) in DST, and return the number of parts used. | ||||
722 | DST must be at least one part larger than size of the answer. */ | ||||
723 | static unsigned int | ||||
724 | powerOf5(APFloatBase::integerPart *dst, unsigned int power) { | ||||
725 | static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 }; | ||||
726 | APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5]; | ||||
727 | pow5s[0] = 78125 * 5; | ||||
728 | |||||
729 | unsigned int partsCount[16] = { 1 }; | ||||
730 | APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5; | ||||
731 | unsigned int result; | ||||
732 | assert(power <= maxExponent)(static_cast <bool> (power <= maxExponent) ? void (0 ) : __assert_fail ("power <= maxExponent", "llvm/lib/Support/APFloat.cpp" , 732, __extension__ __PRETTY_FUNCTION__)); | ||||
733 | |||||
734 | p1 = dst; | ||||
735 | p2 = scratch; | ||||
736 | |||||
737 | *p1 = firstEightPowers[power & 7]; | ||||
738 | power >>= 3; | ||||
739 | |||||
740 | result = 1; | ||||
741 | pow5 = pow5s; | ||||
742 | |||||
743 | for (unsigned int n = 0; power; power >>= 1, n++) { | ||||
744 | unsigned int pc; | ||||
745 | |||||
746 | pc = partsCount[n]; | ||||
747 | |||||
748 | /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */ | ||||
749 | if (pc == 0) { | ||||
750 | pc = partsCount[n - 1]; | ||||
751 | APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc); | ||||
752 | pc *= 2; | ||||
753 | if (pow5[pc - 1] == 0) | ||||
754 | pc--; | ||||
755 | partsCount[n] = pc; | ||||
756 | } | ||||
757 | |||||
758 | if (power & 1) { | ||||
759 | APFloatBase::integerPart *tmp; | ||||
760 | |||||
761 | APInt::tcFullMultiply(p2, p1, pow5, result, pc); | ||||
762 | result += pc; | ||||
763 | if (p2[result - 1] == 0) | ||||
764 | result--; | ||||
765 | |||||
766 | /* Now result is in p1 with partsCount parts and p2 is scratch | ||||
767 | space. */ | ||||
768 | tmp = p1; | ||||
769 | p1 = p2; | ||||
770 | p2 = tmp; | ||||
771 | } | ||||
772 | |||||
773 | pow5 += pc; | ||||
774 | } | ||||
775 | |||||
776 | if (p1 != dst) | ||||
777 | APInt::tcAssign(dst, p1, result); | ||||
778 | |||||
779 | return result; | ||||
780 | } | ||||
781 | |||||
782 | /* Zero at the end to avoid modular arithmetic when adding one; used | ||||
783 | when rounding up during hexadecimal output. */ | ||||
784 | static const char hexDigitsLower[] = "0123456789abcdef0"; | ||||
785 | static const char hexDigitsUpper[] = "0123456789ABCDEF0"; | ||||
786 | static const char infinityL[] = "infinity"; | ||||
787 | static const char infinityU[] = "INFINITY"; | ||||
788 | static const char NaNL[] = "nan"; | ||||
789 | static const char NaNU[] = "NAN"; | ||||
790 | |||||
791 | /* Write out an integerPart in hexadecimal, starting with the most | ||||
792 | significant nibble. Write out exactly COUNT hexdigits, return | ||||
793 | COUNT. */ | ||||
794 | static unsigned int | ||||
795 | partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count, | ||||
796 | const char *hexDigitChars) | ||||
797 | { | ||||
798 | unsigned int result = count; | ||||
799 | |||||
800 | assert(count != 0 && count <= APFloatBase::integerPartWidth / 4)(static_cast <bool> (count != 0 && count <= APFloatBase ::integerPartWidth / 4) ? void (0) : __assert_fail ("count != 0 && count <= APFloatBase::integerPartWidth / 4" , "llvm/lib/Support/APFloat.cpp", 800, __extension__ __PRETTY_FUNCTION__ )); | ||||
801 | |||||
802 | part >>= (APFloatBase::integerPartWidth - 4 * count); | ||||
803 | while (count--) { | ||||
804 | dst[count] = hexDigitChars[part & 0xf]; | ||||
805 | part >>= 4; | ||||
806 | } | ||||
807 | |||||
808 | return result; | ||||
809 | } | ||||
810 | |||||
811 | /* Write out an unsigned decimal integer. */ | ||||
812 | static char * | ||||
813 | writeUnsignedDecimal (char *dst, unsigned int n) | ||||
814 | { | ||||
815 | char buff[40], *p; | ||||
816 | |||||
817 | p = buff; | ||||
818 | do | ||||
819 | *p++ = '0' + n % 10; | ||||
820 | while (n /= 10); | ||||
821 | |||||
822 | do | ||||
823 | *dst++ = *--p; | ||||
824 | while (p != buff); | ||||
825 | |||||
826 | return dst; | ||||
827 | } | ||||
828 | |||||
829 | /* Write out a signed decimal integer. */ | ||||
830 | static char * | ||||
831 | writeSignedDecimal (char *dst, int value) | ||||
832 | { | ||||
833 | if (value < 0) { | ||||
834 | *dst++ = '-'; | ||||
835 | dst = writeUnsignedDecimal(dst, -(unsigned) value); | ||||
836 | } else | ||||
837 | dst = writeUnsignedDecimal(dst, value); | ||||
838 | |||||
839 | return dst; | ||||
840 | } | ||||
841 | |||||
842 | namespace detail { | ||||
843 | /* Constructors. */ | ||||
844 | void IEEEFloat::initialize(const fltSemantics *ourSemantics) { | ||||
845 | unsigned int count; | ||||
846 | |||||
847 | semantics = ourSemantics; | ||||
848 | count = partCount(); | ||||
849 | if (count > 1) | ||||
850 | significand.parts = new integerPart[count]; | ||||
851 | } | ||||
852 | |||||
853 | void IEEEFloat::freeSignificand() { | ||||
854 | if (needsCleanup()) | ||||
855 | delete [] significand.parts; | ||||
856 | } | ||||
857 | |||||
858 | void IEEEFloat::assign(const IEEEFloat &rhs) { | ||||
859 | assert(semantics == rhs.semantics)(static_cast <bool> (semantics == rhs.semantics) ? void (0) : __assert_fail ("semantics == rhs.semantics", "llvm/lib/Support/APFloat.cpp" , 859, __extension__ __PRETTY_FUNCTION__)); | ||||
860 | |||||
861 | sign = rhs.sign; | ||||
862 | category = rhs.category; | ||||
863 | exponent = rhs.exponent; | ||||
864 | if (isFiniteNonZero() || category == fcNaN) | ||||
865 | copySignificand(rhs); | ||||
866 | } | ||||
867 | |||||
868 | void IEEEFloat::copySignificand(const IEEEFloat &rhs) { | ||||
869 | assert(isFiniteNonZero() || category == fcNaN)(static_cast <bool> (isFiniteNonZero() || category == fcNaN ) ? void (0) : __assert_fail ("isFiniteNonZero() || category == fcNaN" , "llvm/lib/Support/APFloat.cpp", 869, __extension__ __PRETTY_FUNCTION__ )); | ||||
870 | assert(rhs.partCount() >= partCount())(static_cast <bool> (rhs.partCount() >= partCount()) ? void (0) : __assert_fail ("rhs.partCount() >= partCount()" , "llvm/lib/Support/APFloat.cpp", 870, __extension__ __PRETTY_FUNCTION__ )); | ||||
871 | |||||
872 | APInt::tcAssign(significandParts(), rhs.significandParts(), | ||||
873 | partCount()); | ||||
874 | } | ||||
875 | |||||
876 | /* Make this number a NaN, with an arbitrary but deterministic value | ||||
877 | for the significand. If double or longer, this is a signalling NaN, | ||||
878 | which may not be ideal. If float, this is QNaN(0). */ | ||||
879 | void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) { | ||||
880 | category = fcNaN; | ||||
881 | sign = Negative; | ||||
882 | exponent = exponentNaN(); | ||||
883 | |||||
884 | integerPart *significand = significandParts(); | ||||
885 | unsigned numParts = partCount(); | ||||
886 | |||||
887 | APInt fill_storage; | ||||
888 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) { | ||||
889 | // Finite-only types do not distinguish signalling and quiet NaN, so | ||||
890 | // make them all signalling. | ||||
891 | SNaN = false; | ||||
892 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) { | ||||
893 | sign = true; | ||||
894 | fill_storage = APInt::getZero(semantics->precision - 1); | ||||
895 | } else { | ||||
896 | fill_storage = APInt::getAllOnes(semantics->precision - 1); | ||||
897 | } | ||||
898 | fill = &fill_storage; | ||||
899 | } | ||||
900 | |||||
901 | // Set the significand bits to the fill. | ||||
902 | if (!fill || fill->getNumWords() < numParts) | ||||
903 | APInt::tcSet(significand, 0, numParts); | ||||
904 | if (fill) { | ||||
905 | APInt::tcAssign(significand, fill->getRawData(), | ||||
906 | std::min(fill->getNumWords(), numParts)); | ||||
907 | |||||
908 | // Zero out the excess bits of the significand. | ||||
909 | unsigned bitsToPreserve = semantics->precision - 1; | ||||
910 | unsigned part = bitsToPreserve / 64; | ||||
911 | bitsToPreserve %= 64; | ||||
912 | significand[part] &= ((1ULL << bitsToPreserve) - 1); | ||||
913 | for (part++; part != numParts; ++part) | ||||
914 | significand[part] = 0; | ||||
915 | } | ||||
916 | |||||
917 | unsigned QNaNBit = semantics->precision - 2; | ||||
918 | |||||
919 | if (SNaN) { | ||||
920 | // We always have to clear the QNaN bit to make it an SNaN. | ||||
921 | APInt::tcClearBit(significand, QNaNBit); | ||||
922 | |||||
923 | // If there are no bits set in the payload, we have to set | ||||
924 | // *something* to make it a NaN instead of an infinity; | ||||
925 | // conventionally, this is the next bit down from the QNaN bit. | ||||
926 | if (APInt::tcIsZero(significand, numParts)) | ||||
927 | APInt::tcSetBit(significand, QNaNBit - 1); | ||||
928 | } else if (semantics->nanEncoding == fltNanEncoding::NegativeZero) { | ||||
929 | // The only NaN is a quiet NaN, and it has no bits sets in the significand. | ||||
930 | // Do nothing. | ||||
931 | } else { | ||||
932 | // We always have to set the QNaN bit to make it a QNaN. | ||||
933 | APInt::tcSetBit(significand, QNaNBit); | ||||
934 | } | ||||
935 | |||||
936 | // For x87 extended precision, we want to make a NaN, not a | ||||
937 | // pseudo-NaN. Maybe we should expose the ability to make | ||||
938 | // pseudo-NaNs? | ||||
939 | if (semantics == &semX87DoubleExtended) | ||||
940 | APInt::tcSetBit(significand, QNaNBit + 1); | ||||
941 | } | ||||
942 | |||||
943 | IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) { | ||||
944 | if (this != &rhs) { | ||||
945 | if (semantics != rhs.semantics) { | ||||
946 | freeSignificand(); | ||||
947 | initialize(rhs.semantics); | ||||
948 | } | ||||
949 | assign(rhs); | ||||
950 | } | ||||
951 | |||||
952 | return *this; | ||||
953 | } | ||||
954 | |||||
955 | IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) { | ||||
956 | freeSignificand(); | ||||
957 | |||||
958 | semantics = rhs.semantics; | ||||
959 | significand = rhs.significand; | ||||
960 | exponent = rhs.exponent; | ||||
961 | category = rhs.category; | ||||
962 | sign = rhs.sign; | ||||
963 | |||||
964 | rhs.semantics = &semBogus; | ||||
965 | return *this; | ||||
966 | } | ||||
967 | |||||
968 | bool IEEEFloat::isDenormal() const { | ||||
969 | return isFiniteNonZero() && (exponent == semantics->minExponent) && | ||||
970 | (APInt::tcExtractBit(significandParts(), | ||||
971 | semantics->precision - 1) == 0); | ||||
972 | } | ||||
973 | |||||
974 | bool IEEEFloat::isSmallest() const { | ||||
975 | // The smallest number by magnitude in our format will be the smallest | ||||
976 | // denormal, i.e. the floating point number with exponent being minimum | ||||
977 | // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0). | ||||
978 | return isFiniteNonZero() && exponent == semantics->minExponent && | ||||
979 | significandMSB() == 0; | ||||
980 | } | ||||
981 | |||||
982 | bool IEEEFloat::isSmallestNormalized() const { | ||||
983 | return getCategory() == fcNormal && exponent == semantics->minExponent && | ||||
984 | isSignificandAllZerosExceptMSB(); | ||||
985 | } | ||||
986 | |||||
987 | bool IEEEFloat::isSignificandAllOnes() const { | ||||
988 | // Test if the significand excluding the integral bit is all ones. This allows | ||||
989 | // us to test for binade boundaries. | ||||
990 | const integerPart *Parts = significandParts(); | ||||
991 | const unsigned PartCount = partCountForBits(semantics->precision); | ||||
992 | for (unsigned i = 0; i < PartCount - 1; i++) | ||||
993 | if (~Parts[i]) | ||||
994 | return false; | ||||
995 | |||||
996 | // Set the unused high bits to all ones when we compare. | ||||
997 | const unsigned NumHighBits = | ||||
998 | PartCount*integerPartWidth - semantics->precision + 1; | ||||
999 | assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&(static_cast <bool> (NumHighBits <= integerPartWidth && NumHighBits > 0 && "Can not have more high bits to fill than integerPartWidth" ) ? void (0) : __assert_fail ("NumHighBits <= integerPartWidth && NumHighBits > 0 && \"Can not have more high bits to fill than integerPartWidth\"" , "llvm/lib/Support/APFloat.cpp", 1000, __extension__ __PRETTY_FUNCTION__ )) | ||||
1000 | "Can not have more high bits to fill than integerPartWidth")(static_cast <bool> (NumHighBits <= integerPartWidth && NumHighBits > 0 && "Can not have more high bits to fill than integerPartWidth" ) ? void (0) : __assert_fail ("NumHighBits <= integerPartWidth && NumHighBits > 0 && \"Can not have more high bits to fill than integerPartWidth\"" , "llvm/lib/Support/APFloat.cpp", 1000, __extension__ __PRETTY_FUNCTION__ )); | ||||
1001 | const integerPart HighBitFill = | ||||
1002 | ~integerPart(0) << (integerPartWidth - NumHighBits); | ||||
1003 | if (~(Parts[PartCount - 1] | HighBitFill)) | ||||
1004 | return false; | ||||
1005 | |||||
1006 | return true; | ||||
1007 | } | ||||
1008 | |||||
1009 | bool IEEEFloat::isSignificandAllOnesExceptLSB() const { | ||||
1010 | // Test if the significand excluding the integral bit is all ones except for | ||||
1011 | // the least significant bit. | ||||
1012 | const integerPart *Parts = significandParts(); | ||||
1013 | |||||
1014 | if (Parts[0] & 1) | ||||
1015 | return false; | ||||
1016 | |||||
1017 | const unsigned PartCount = partCountForBits(semantics->precision); | ||||
1018 | for (unsigned i = 0; i < PartCount - 1; i++) { | ||||
1019 | if (~Parts[i] & ~unsigned{!i}) | ||||
1020 | return false; | ||||
1021 | } | ||||
1022 | |||||
1023 | // Set the unused high bits to all ones when we compare. | ||||
1024 | const unsigned NumHighBits = | ||||
1025 | PartCount * integerPartWidth - semantics->precision + 1; | ||||
1026 | assert(NumHighBits <= integerPartWidth && NumHighBits > 0 &&(static_cast <bool> (NumHighBits <= integerPartWidth && NumHighBits > 0 && "Can not have more high bits to fill than integerPartWidth" ) ? void (0) : __assert_fail ("NumHighBits <= integerPartWidth && NumHighBits > 0 && \"Can not have more high bits to fill than integerPartWidth\"" , "llvm/lib/Support/APFloat.cpp", 1027, __extension__ __PRETTY_FUNCTION__ )) | ||||
1027 | "Can not have more high bits to fill than integerPartWidth")(static_cast <bool> (NumHighBits <= integerPartWidth && NumHighBits > 0 && "Can not have more high bits to fill than integerPartWidth" ) ? void (0) : __assert_fail ("NumHighBits <= integerPartWidth && NumHighBits > 0 && \"Can not have more high bits to fill than integerPartWidth\"" , "llvm/lib/Support/APFloat.cpp", 1027, __extension__ __PRETTY_FUNCTION__ )); | ||||
1028 | const integerPart HighBitFill = ~integerPart(0) | ||||
1029 | << (integerPartWidth - NumHighBits); | ||||
1030 | if (~(Parts[PartCount - 1] | HighBitFill | 0x1)) | ||||
1031 | return false; | ||||
1032 | |||||
1033 | return true; | ||||
1034 | } | ||||
1035 | |||||
1036 | bool IEEEFloat::isSignificandAllZeros() const { | ||||
1037 | // Test if the significand excluding the integral bit is all zeros. This | ||||
1038 | // allows us to test for binade boundaries. | ||||
1039 | const integerPart *Parts = significandParts(); | ||||
1040 | const unsigned PartCount = partCountForBits(semantics->precision); | ||||
1041 | |||||
1042 | for (unsigned i = 0; i < PartCount - 1; i++) | ||||
1043 | if (Parts[i]) | ||||
1044 | return false; | ||||
1045 | |||||
1046 | // Compute how many bits are used in the final word. | ||||
1047 | const unsigned NumHighBits = | ||||
1048 | PartCount*integerPartWidth - semantics->precision + 1; | ||||
1049 | assert(NumHighBits < integerPartWidth && "Can not have more high bits to "(static_cast <bool> (NumHighBits < integerPartWidth && "Can not have more high bits to " "clear than integerPartWidth" ) ? void (0) : __assert_fail ("NumHighBits < integerPartWidth && \"Can not have more high bits to \" \"clear than integerPartWidth\"" , "llvm/lib/Support/APFloat.cpp", 1050, __extension__ __PRETTY_FUNCTION__ )) | ||||
1050 | "clear than integerPartWidth")(static_cast <bool> (NumHighBits < integerPartWidth && "Can not have more high bits to " "clear than integerPartWidth" ) ? void (0) : __assert_fail ("NumHighBits < integerPartWidth && \"Can not have more high bits to \" \"clear than integerPartWidth\"" , "llvm/lib/Support/APFloat.cpp", 1050, __extension__ __PRETTY_FUNCTION__ )); | ||||
1051 | const integerPart HighBitMask = ~integerPart(0) >> NumHighBits; | ||||
1052 | |||||
1053 | if (Parts[PartCount - 1] & HighBitMask) | ||||
1054 | return false; | ||||
1055 | |||||
1056 | return true; | ||||
1057 | } | ||||
1058 | |||||
1059 | bool IEEEFloat::isSignificandAllZerosExceptMSB() const { | ||||
1060 | const integerPart *Parts = significandParts(); | ||||
1061 | const unsigned PartCount = partCountForBits(semantics->precision); | ||||
1062 | |||||
1063 | for (unsigned i = 0; i < PartCount - 1; i++) { | ||||
1064 | if (Parts[i]) | ||||
1065 | return false; | ||||
1066 | } | ||||
1067 | |||||
1068 | const unsigned NumHighBits = | ||||
1069 | PartCount * integerPartWidth - semantics->precision + 1; | ||||
1070 | return Parts[PartCount - 1] == integerPart(1) | ||||
1071 | << (integerPartWidth - NumHighBits); | ||||
1072 | } | ||||
1073 | |||||
1074 | bool IEEEFloat::isLargest() const { | ||||
1075 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly && | ||||
1076 | semantics->nanEncoding == fltNanEncoding::AllOnes) { | ||||
1077 | // The largest number by magnitude in our format will be the floating point | ||||
1078 | // number with maximum exponent and with significand that is all ones except | ||||
1079 | // the LSB. | ||||
1080 | return isFiniteNonZero() && exponent == semantics->maxExponent && | ||||
1081 | isSignificandAllOnesExceptLSB(); | ||||
1082 | } else { | ||||
1083 | // The largest number by magnitude in our format will be the floating point | ||||
1084 | // number with maximum exponent and with significand that is all ones. | ||||
1085 | return isFiniteNonZero() && exponent == semantics->maxExponent && | ||||
1086 | isSignificandAllOnes(); | ||||
1087 | } | ||||
1088 | } | ||||
1089 | |||||
1090 | bool IEEEFloat::isInteger() const { | ||||
1091 | // This could be made more efficient; I'm going for obviously correct. | ||||
1092 | if (!isFinite()) return false; | ||||
1093 | IEEEFloat truncated = *this; | ||||
1094 | truncated.roundToIntegral(rmTowardZero); | ||||
1095 | return compare(truncated) == cmpEqual; | ||||
1096 | } | ||||
1097 | |||||
1098 | bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const { | ||||
1099 | if (this == &rhs) | ||||
1100 | return true; | ||||
1101 | if (semantics != rhs.semantics || | ||||
1102 | category != rhs.category || | ||||
1103 | sign != rhs.sign) | ||||
1104 | return false; | ||||
1105 | if (category==fcZero || category==fcInfinity) | ||||
1106 | return true; | ||||
1107 | |||||
1108 | if (isFiniteNonZero() && exponent != rhs.exponent) | ||||
1109 | return false; | ||||
1110 | |||||
1111 | return std::equal(significandParts(), significandParts() + partCount(), | ||||
1112 | rhs.significandParts()); | ||||
1113 | } | ||||
1114 | |||||
1115 | IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) { | ||||
1116 | initialize(&ourSemantics); | ||||
1117 | sign = 0; | ||||
1118 | category = fcNormal; | ||||
1119 | zeroSignificand(); | ||||
1120 | exponent = ourSemantics.precision - 1; | ||||
1121 | significandParts()[0] = value; | ||||
1122 | normalize(rmNearestTiesToEven, lfExactlyZero); | ||||
1123 | } | ||||
1124 | |||||
1125 | IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) { | ||||
1126 | initialize(&ourSemantics); | ||||
1127 | makeZero(false); | ||||
1128 | } | ||||
1129 | |||||
1130 | // Delegate to the previous constructor, because later copy constructor may | ||||
1131 | // actually inspects category, which can't be garbage. | ||||
1132 | IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag) | ||||
1133 | : IEEEFloat(ourSemantics) {} | ||||
1134 | |||||
1135 | IEEEFloat::IEEEFloat(const IEEEFloat &rhs) { | ||||
1136 | initialize(rhs.semantics); | ||||
1137 | assign(rhs); | ||||
1138 | } | ||||
1139 | |||||
1140 | IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) { | ||||
1141 | *this = std::move(rhs); | ||||
1142 | } | ||||
1143 | |||||
1144 | IEEEFloat::~IEEEFloat() { freeSignificand(); } | ||||
1145 | |||||
1146 | unsigned int IEEEFloat::partCount() const { | ||||
1147 | return partCountForBits(semantics->precision + 1); | ||||
1148 | } | ||||
1149 | |||||
1150 | const IEEEFloat::integerPart *IEEEFloat::significandParts() const { | ||||
1151 | return const_cast<IEEEFloat *>(this)->significandParts(); | ||||
1152 | } | ||||
1153 | |||||
1154 | IEEEFloat::integerPart *IEEEFloat::significandParts() { | ||||
1155 | if (partCount() > 1) | ||||
1156 | return significand.parts; | ||||
1157 | else | ||||
1158 | return &significand.part; | ||||
1159 | } | ||||
1160 | |||||
1161 | void IEEEFloat::zeroSignificand() { | ||||
1162 | APInt::tcSet(significandParts(), 0, partCount()); | ||||
1163 | } | ||||
1164 | |||||
1165 | /* Increment an fcNormal floating point number's significand. */ | ||||
1166 | void IEEEFloat::incrementSignificand() { | ||||
1167 | integerPart carry; | ||||
1168 | |||||
1169 | carry = APInt::tcIncrement(significandParts(), partCount()); | ||||
1170 | |||||
1171 | /* Our callers should never cause us to overflow. */ | ||||
1172 | assert(carry == 0)(static_cast <bool> (carry == 0) ? void (0) : __assert_fail ("carry == 0", "llvm/lib/Support/APFloat.cpp", 1172, __extension__ __PRETTY_FUNCTION__)); | ||||
1173 | (void)carry; | ||||
1174 | } | ||||
1175 | |||||
1176 | /* Add the significand of the RHS. Returns the carry flag. */ | ||||
1177 | IEEEFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) { | ||||
1178 | integerPart *parts; | ||||
1179 | |||||
1180 | parts = significandParts(); | ||||
1181 | |||||
1182 | assert(semantics == rhs.semantics)(static_cast <bool> (semantics == rhs.semantics) ? void (0) : __assert_fail ("semantics == rhs.semantics", "llvm/lib/Support/APFloat.cpp" , 1182, __extension__ __PRETTY_FUNCTION__)); | ||||
1183 | assert(exponent == rhs.exponent)(static_cast <bool> (exponent == rhs.exponent) ? void ( 0) : __assert_fail ("exponent == rhs.exponent", "llvm/lib/Support/APFloat.cpp" , 1183, __extension__ __PRETTY_FUNCTION__)); | ||||
1184 | |||||
1185 | return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount()); | ||||
1186 | } | ||||
1187 | |||||
1188 | /* Subtract the significand of the RHS with a borrow flag. Returns | ||||
1189 | the borrow flag. */ | ||||
1190 | IEEEFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs, | ||||
1191 | integerPart borrow) { | ||||
1192 | integerPart *parts; | ||||
1193 | |||||
1194 | parts = significandParts(); | ||||
1195 | |||||
1196 | assert(semantics == rhs.semantics)(static_cast <bool> (semantics == rhs.semantics) ? void (0) : __assert_fail ("semantics == rhs.semantics", "llvm/lib/Support/APFloat.cpp" , 1196, __extension__ __PRETTY_FUNCTION__)); | ||||
1197 | assert(exponent == rhs.exponent)(static_cast <bool> (exponent == rhs.exponent) ? void ( 0) : __assert_fail ("exponent == rhs.exponent", "llvm/lib/Support/APFloat.cpp" , 1197, __extension__ __PRETTY_FUNCTION__)); | ||||
1198 | |||||
1199 | return APInt::tcSubtract(parts, rhs.significandParts(), borrow, | ||||
1200 | partCount()); | ||||
1201 | } | ||||
1202 | |||||
1203 | /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it | ||||
1204 | on to the full-precision result of the multiplication. Returns the | ||||
1205 | lost fraction. */ | ||||
1206 | lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs, | ||||
1207 | IEEEFloat addend) { | ||||
1208 | unsigned int omsb; // One, not zero, based MSB. | ||||
1209 | unsigned int partsCount, newPartsCount, precision; | ||||
1210 | integerPart *lhsSignificand; | ||||
1211 | integerPart scratch[4]; | ||||
1212 | integerPart *fullSignificand; | ||||
1213 | lostFraction lost_fraction; | ||||
1214 | bool ignored; | ||||
1215 | |||||
1216 | assert(semantics == rhs.semantics)(static_cast <bool> (semantics == rhs.semantics) ? void (0) : __assert_fail ("semantics == rhs.semantics", "llvm/lib/Support/APFloat.cpp" , 1216, __extension__ __PRETTY_FUNCTION__)); | ||||
1217 | |||||
1218 | precision = semantics->precision; | ||||
1219 | |||||
1220 | // Allocate space for twice as many bits as the original significand, plus one | ||||
1221 | // extra bit for the addition to overflow into. | ||||
1222 | newPartsCount = partCountForBits(precision * 2 + 1); | ||||
1223 | |||||
1224 | if (newPartsCount > 4) | ||||
1225 | fullSignificand = new integerPart[newPartsCount]; | ||||
1226 | else | ||||
1227 | fullSignificand = scratch; | ||||
1228 | |||||
1229 | lhsSignificand = significandParts(); | ||||
1230 | partsCount = partCount(); | ||||
1231 | |||||
1232 | APInt::tcFullMultiply(fullSignificand, lhsSignificand, | ||||
1233 | rhs.significandParts(), partsCount, partsCount); | ||||
1234 | |||||
1235 | lost_fraction = lfExactlyZero; | ||||
1236 | omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1; | ||||
1237 | exponent += rhs.exponent; | ||||
1238 | |||||
1239 | // Assume the operands involved in the multiplication are single-precision | ||||
1240 | // FP, and the two multiplicants are: | ||||
1241 | // *this = a23 . a22 ... a0 * 2^e1 | ||||
1242 | // rhs = b23 . b22 ... b0 * 2^e2 | ||||
1243 | // the result of multiplication is: | ||||
1244 | // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2) | ||||
1245 | // Note that there are three significant bits at the left-hand side of the | ||||
1246 | // radix point: two for the multiplication, and an overflow bit for the | ||||
1247 | // addition (that will always be zero at this point). Move the radix point | ||||
1248 | // toward left by two bits, and adjust exponent accordingly. | ||||
1249 | exponent += 2; | ||||
1250 | |||||
1251 | if (addend.isNonZero()) { | ||||
1252 | // The intermediate result of the multiplication has "2 * precision" | ||||
1253 | // signicant bit; adjust the addend to be consistent with mul result. | ||||
1254 | // | ||||
1255 | Significand savedSignificand = significand; | ||||
1256 | const fltSemantics *savedSemantics = semantics; | ||||
1257 | fltSemantics extendedSemantics; | ||||
1258 | opStatus status; | ||||
1259 | unsigned int extendedPrecision; | ||||
1260 | |||||
1261 | // Normalize our MSB to one below the top bit to allow for overflow. | ||||
1262 | extendedPrecision = 2 * precision + 1; | ||||
1263 | if (omsb != extendedPrecision - 1) { | ||||
1264 | assert(extendedPrecision > omsb)(static_cast <bool> (extendedPrecision > omsb) ? void (0) : __assert_fail ("extendedPrecision > omsb", "llvm/lib/Support/APFloat.cpp" , 1264, __extension__ __PRETTY_FUNCTION__)); | ||||
1265 | APInt::tcShiftLeft(fullSignificand, newPartsCount, | ||||
1266 | (extendedPrecision - 1) - omsb); | ||||
1267 | exponent -= (extendedPrecision - 1) - omsb; | ||||
1268 | } | ||||
1269 | |||||
1270 | /* Create new semantics. */ | ||||
1271 | extendedSemantics = *semantics; | ||||
1272 | extendedSemantics.precision = extendedPrecision; | ||||
1273 | |||||
1274 | if (newPartsCount == 1) | ||||
1275 | significand.part = fullSignificand[0]; | ||||
1276 | else | ||||
1277 | significand.parts = fullSignificand; | ||||
1278 | semantics = &extendedSemantics; | ||||
1279 | |||||
1280 | // Make a copy so we can convert it to the extended semantics. | ||||
1281 | // Note that we cannot convert the addend directly, as the extendedSemantics | ||||
1282 | // is a local variable (which we take a reference to). | ||||
1283 | IEEEFloat extendedAddend(addend); | ||||
1284 | status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored); | ||||
1285 | assert(status == opOK)(static_cast <bool> (status == opOK) ? void (0) : __assert_fail ("status == opOK", "llvm/lib/Support/APFloat.cpp", 1285, __extension__ __PRETTY_FUNCTION__)); | ||||
1286 | (void)status; | ||||
1287 | |||||
1288 | // Shift the significand of the addend right by one bit. This guarantees | ||||
1289 | // that the high bit of the significand is zero (same as fullSignificand), | ||||
1290 | // so the addition will overflow (if it does overflow at all) into the top bit. | ||||
1291 | lost_fraction = extendedAddend.shiftSignificandRight(1); | ||||
1292 | assert(lost_fraction == lfExactlyZero &&(static_cast <bool> (lost_fraction == lfExactlyZero && "Lost precision while shifting addend for fused-multiply-add." ) ? void (0) : __assert_fail ("lost_fraction == lfExactlyZero && \"Lost precision while shifting addend for fused-multiply-add.\"" , "llvm/lib/Support/APFloat.cpp", 1293, __extension__ __PRETTY_FUNCTION__ )) | ||||
1293 | "Lost precision while shifting addend for fused-multiply-add.")(static_cast <bool> (lost_fraction == lfExactlyZero && "Lost precision while shifting addend for fused-multiply-add." ) ? void (0) : __assert_fail ("lost_fraction == lfExactlyZero && \"Lost precision while shifting addend for fused-multiply-add.\"" , "llvm/lib/Support/APFloat.cpp", 1293, __extension__ __PRETTY_FUNCTION__ )); | ||||
1294 | |||||
1295 | lost_fraction = addOrSubtractSignificand(extendedAddend, false); | ||||
1296 | |||||
1297 | /* Restore our state. */ | ||||
1298 | if (newPartsCount == 1) | ||||
1299 | fullSignificand[0] = significand.part; | ||||
1300 | significand = savedSignificand; | ||||
1301 | semantics = savedSemantics; | ||||
1302 | |||||
1303 | omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1; | ||||
1304 | } | ||||
1305 | |||||
1306 | // Convert the result having "2 * precision" significant-bits back to the one | ||||
1307 | // having "precision" significant-bits. First, move the radix point from | ||||
1308 | // poision "2*precision - 1" to "precision - 1". The exponent need to be | ||||
1309 | // adjusted by "2*precision - 1" - "precision - 1" = "precision". | ||||
1310 | exponent -= precision + 1; | ||||
1311 | |||||
1312 | // In case MSB resides at the left-hand side of radix point, shift the | ||||
1313 | // mantissa right by some amount to make sure the MSB reside right before | ||||
1314 | // the radix point (i.e. "MSB . rest-significant-bits"). | ||||
1315 | // | ||||
1316 | // Note that the result is not normalized when "omsb < precision". So, the | ||||
1317 | // caller needs to call IEEEFloat::normalize() if normalized value is | ||||
1318 | // expected. | ||||
1319 | if (omsb > precision) { | ||||
1320 | unsigned int bits, significantParts; | ||||
1321 | lostFraction lf; | ||||
1322 | |||||
1323 | bits = omsb - precision; | ||||
1324 | significantParts = partCountForBits(omsb); | ||||
1325 | lf = shiftRight(fullSignificand, significantParts, bits); | ||||
1326 | lost_fraction = combineLostFractions(lf, lost_fraction); | ||||
1327 | exponent += bits; | ||||
1328 | } | ||||
1329 | |||||
1330 | APInt::tcAssign(lhsSignificand, fullSignificand, partsCount); | ||||
1331 | |||||
1332 | if (newPartsCount > 4) | ||||
1333 | delete [] fullSignificand; | ||||
1334 | |||||
1335 | return lost_fraction; | ||||
1336 | } | ||||
1337 | |||||
1338 | lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs) { | ||||
1339 | return multiplySignificand(rhs, IEEEFloat(*semantics)); | ||||
1340 | } | ||||
1341 | |||||
1342 | /* Multiply the significands of LHS and RHS to DST. */ | ||||
1343 | lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) { | ||||
1344 | unsigned int bit, i, partsCount; | ||||
1345 | const integerPart *rhsSignificand; | ||||
1346 | integerPart *lhsSignificand, *dividend, *divisor; | ||||
1347 | integerPart scratch[4]; | ||||
1348 | lostFraction lost_fraction; | ||||
1349 | |||||
1350 | assert(semantics == rhs.semantics)(static_cast <bool> (semantics == rhs.semantics) ? void (0) : __assert_fail ("semantics == rhs.semantics", "llvm/lib/Support/APFloat.cpp" , 1350, __extension__ __PRETTY_FUNCTION__)); | ||||
1351 | |||||
1352 | lhsSignificand = significandParts(); | ||||
1353 | rhsSignificand = rhs.significandParts(); | ||||
1354 | partsCount = partCount(); | ||||
1355 | |||||
1356 | if (partsCount > 2) | ||||
1357 | dividend = new integerPart[partsCount * 2]; | ||||
1358 | else | ||||
1359 | dividend = scratch; | ||||
1360 | |||||
1361 | divisor = dividend + partsCount; | ||||
1362 | |||||
1363 | /* Copy the dividend and divisor as they will be modified in-place. */ | ||||
1364 | for (i = 0; i < partsCount; i++) { | ||||
1365 | dividend[i] = lhsSignificand[i]; | ||||
1366 | divisor[i] = rhsSignificand[i]; | ||||
1367 | lhsSignificand[i] = 0; | ||||
1368 | } | ||||
1369 | |||||
1370 | exponent -= rhs.exponent; | ||||
1371 | |||||
1372 | unsigned int precision = semantics->precision; | ||||
1373 | |||||
1374 | /* Normalize the divisor. */ | ||||
1375 | bit = precision - APInt::tcMSB(divisor, partsCount) - 1; | ||||
1376 | if (bit) { | ||||
1377 | exponent += bit; | ||||
1378 | APInt::tcShiftLeft(divisor, partsCount, bit); | ||||
1379 | } | ||||
1380 | |||||
1381 | /* Normalize the dividend. */ | ||||
1382 | bit = precision - APInt::tcMSB(dividend, partsCount) - 1; | ||||
1383 | if (bit) { | ||||
1384 | exponent -= bit; | ||||
1385 | APInt::tcShiftLeft(dividend, partsCount, bit); | ||||
1386 | } | ||||
1387 | |||||
1388 | /* Ensure the dividend >= divisor initially for the loop below. | ||||
1389 | Incidentally, this means that the division loop below is | ||||
1390 | guaranteed to set the integer bit to one. */ | ||||
1391 | if (APInt::tcCompare(dividend, divisor, partsCount) < 0) { | ||||
1392 | exponent--; | ||||
1393 | APInt::tcShiftLeft(dividend, partsCount, 1); | ||||
1394 | assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0)(static_cast <bool> (APInt::tcCompare(dividend, divisor , partsCount) >= 0) ? void (0) : __assert_fail ("APInt::tcCompare(dividend, divisor, partsCount) >= 0" , "llvm/lib/Support/APFloat.cpp", 1394, __extension__ __PRETTY_FUNCTION__ )); | ||||
1395 | } | ||||
1396 | |||||
1397 | /* Long division. */ | ||||
1398 | for (bit = precision; bit; bit -= 1) { | ||||
1399 | if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) { | ||||
1400 | APInt::tcSubtract(dividend, divisor, 0, partsCount); | ||||
1401 | APInt::tcSetBit(lhsSignificand, bit - 1); | ||||
1402 | } | ||||
1403 | |||||
1404 | APInt::tcShiftLeft(dividend, partsCount, 1); | ||||
1405 | } | ||||
1406 | |||||
1407 | /* Figure out the lost fraction. */ | ||||
1408 | int cmp = APInt::tcCompare(dividend, divisor, partsCount); | ||||
1409 | |||||
1410 | if (cmp > 0) | ||||
1411 | lost_fraction = lfMoreThanHalf; | ||||
1412 | else if (cmp == 0) | ||||
1413 | lost_fraction = lfExactlyHalf; | ||||
1414 | else if (APInt::tcIsZero(dividend, partsCount)) | ||||
1415 | lost_fraction = lfExactlyZero; | ||||
1416 | else | ||||
1417 | lost_fraction = lfLessThanHalf; | ||||
1418 | |||||
1419 | if (partsCount > 2) | ||||
1420 | delete [] dividend; | ||||
1421 | |||||
1422 | return lost_fraction; | ||||
1423 | } | ||||
1424 | |||||
1425 | unsigned int IEEEFloat::significandMSB() const { | ||||
1426 | return APInt::tcMSB(significandParts(), partCount()); | ||||
1427 | } | ||||
1428 | |||||
1429 | unsigned int IEEEFloat::significandLSB() const { | ||||
1430 | return APInt::tcLSB(significandParts(), partCount()); | ||||
1431 | } | ||||
1432 | |||||
1433 | /* Note that a zero result is NOT normalized to fcZero. */ | ||||
1434 | lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) { | ||||
1435 | /* Our exponent should not overflow. */ | ||||
1436 | assert((ExponentType) (exponent + bits) >= exponent)(static_cast <bool> ((ExponentType) (exponent + bits) >= exponent) ? void (0) : __assert_fail ("(ExponentType) (exponent + bits) >= exponent" , "llvm/lib/Support/APFloat.cpp", 1436, __extension__ __PRETTY_FUNCTION__ )); | ||||
1437 | |||||
1438 | exponent += bits; | ||||
1439 | |||||
1440 | return shiftRight(significandParts(), partCount(), bits); | ||||
1441 | } | ||||
1442 | |||||
1443 | /* Shift the significand left BITS bits, subtract BITS from its exponent. */ | ||||
1444 | void IEEEFloat::shiftSignificandLeft(unsigned int bits) { | ||||
1445 | assert(bits < semantics->precision)(static_cast <bool> (bits < semantics->precision) ? void (0) : __assert_fail ("bits < semantics->precision" , "llvm/lib/Support/APFloat.cpp", 1445, __extension__ __PRETTY_FUNCTION__ )); | ||||
1446 | |||||
1447 | if (bits) { | ||||
1448 | unsigned int partsCount = partCount(); | ||||
1449 | |||||
1450 | APInt::tcShiftLeft(significandParts(), partsCount, bits); | ||||
1451 | exponent -= bits; | ||||
1452 | |||||
1453 | assert(!APInt::tcIsZero(significandParts(), partsCount))(static_cast <bool> (!APInt::tcIsZero(significandParts( ), partsCount)) ? void (0) : __assert_fail ("!APInt::tcIsZero(significandParts(), partsCount)" , "llvm/lib/Support/APFloat.cpp", 1453, __extension__ __PRETTY_FUNCTION__ )); | ||||
1454 | } | ||||
1455 | } | ||||
1456 | |||||
1457 | IEEEFloat::cmpResult | ||||
1458 | IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const { | ||||
1459 | int compare; | ||||
1460 | |||||
1461 | assert(semantics == rhs.semantics)(static_cast <bool> (semantics == rhs.semantics) ? void (0) : __assert_fail ("semantics == rhs.semantics", "llvm/lib/Support/APFloat.cpp" , 1461, __extension__ __PRETTY_FUNCTION__)); | ||||
1462 | assert(isFiniteNonZero())(static_cast <bool> (isFiniteNonZero()) ? void (0) : __assert_fail ("isFiniteNonZero()", "llvm/lib/Support/APFloat.cpp", 1462, __extension__ __PRETTY_FUNCTION__)); | ||||
1463 | assert(rhs.isFiniteNonZero())(static_cast <bool> (rhs.isFiniteNonZero()) ? void (0) : __assert_fail ("rhs.isFiniteNonZero()", "llvm/lib/Support/APFloat.cpp" , 1463, __extension__ __PRETTY_FUNCTION__)); | ||||
1464 | |||||
1465 | compare = exponent - rhs.exponent; | ||||
1466 | |||||
1467 | /* If exponents are equal, do an unsigned bignum comparison of the | ||||
1468 | significands. */ | ||||
1469 | if (compare == 0) | ||||
1470 | compare = APInt::tcCompare(significandParts(), rhs.significandParts(), | ||||
1471 | partCount()); | ||||
1472 | |||||
1473 | if (compare > 0) | ||||
1474 | return cmpGreaterThan; | ||||
1475 | else if (compare < 0) | ||||
1476 | return cmpLessThan; | ||||
1477 | else | ||||
1478 | return cmpEqual; | ||||
1479 | } | ||||
1480 | |||||
1481 | /* Set the least significant BITS bits of a bignum, clear the | ||||
1482 | rest. */ | ||||
1483 | static void tcSetLeastSignificantBits(APInt::WordType *dst, unsigned parts, | ||||
1484 | unsigned bits) { | ||||
1485 | unsigned i = 0; | ||||
1486 | while (bits > APInt::APINT_BITS_PER_WORD) { | ||||
1487 | dst[i++] = ~(APInt::WordType)0; | ||||
1488 | bits -= APInt::APINT_BITS_PER_WORD; | ||||
1489 | } | ||||
1490 | |||||
1491 | if (bits) | ||||
1492 | dst[i++] = ~(APInt::WordType)0 >> (APInt::APINT_BITS_PER_WORD - bits); | ||||
1493 | |||||
1494 | while (i < parts) | ||||
1495 | dst[i++] = 0; | ||||
1496 | } | ||||
1497 | |||||
1498 | /* Handle overflow. Sign is preserved. We either become infinity or | ||||
1499 | the largest finite number. */ | ||||
1500 | IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) { | ||||
1501 | /* Infinity? */ | ||||
1502 | if (rounding_mode == rmNearestTiesToEven || | ||||
1503 | rounding_mode == rmNearestTiesToAway || | ||||
1504 | (rounding_mode == rmTowardPositive && !sign) || | ||||
1505 | (rounding_mode == rmTowardNegative && sign)) { | ||||
1506 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) | ||||
1507 | makeNaN(false, sign); | ||||
1508 | else | ||||
1509 | category = fcInfinity; | ||||
1510 | return (opStatus) (opOverflow | opInexact); | ||||
1511 | } | ||||
1512 | |||||
1513 | /* Otherwise we become the largest finite number. */ | ||||
1514 | category = fcNormal; | ||||
1515 | exponent = semantics->maxExponent; | ||||
1516 | tcSetLeastSignificantBits(significandParts(), partCount(), | ||||
1517 | semantics->precision); | ||||
1518 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly && | ||||
1519 | semantics->nanEncoding == fltNanEncoding::AllOnes) | ||||
1520 | APInt::tcClearBit(significandParts(), 0); | ||||
1521 | |||||
1522 | return opInexact; | ||||
1523 | } | ||||
1524 | |||||
1525 | /* Returns TRUE if, when truncating the current number, with BIT the | ||||
1526 | new LSB, with the given lost fraction and rounding mode, the result | ||||
1527 | would need to be rounded away from zero (i.e., by increasing the | ||||
1528 | signficand). This routine must work for fcZero of both signs, and | ||||
1529 | fcNormal numbers. */ | ||||
1530 | bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode, | ||||
1531 | lostFraction lost_fraction, | ||||
1532 | unsigned int bit) const { | ||||
1533 | /* NaNs and infinities should not have lost fractions. */ | ||||
1534 | assert(isFiniteNonZero() || category == fcZero)(static_cast <bool> (isFiniteNonZero() || category == fcZero ) ? void (0) : __assert_fail ("isFiniteNonZero() || category == fcZero" , "llvm/lib/Support/APFloat.cpp", 1534, __extension__ __PRETTY_FUNCTION__ )); | ||||
1535 | |||||
1536 | /* Current callers never pass this so we don't handle it. */ | ||||
1537 | assert(lost_fraction != lfExactlyZero)(static_cast <bool> (lost_fraction != lfExactlyZero) ? void (0) : __assert_fail ("lost_fraction != lfExactlyZero", "llvm/lib/Support/APFloat.cpp" , 1537, __extension__ __PRETTY_FUNCTION__)); | ||||
1538 | |||||
1539 | switch (rounding_mode) { | ||||
1540 | case rmNearestTiesToAway: | ||||
1541 | return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf; | ||||
1542 | |||||
1543 | case rmNearestTiesToEven: | ||||
1544 | if (lost_fraction == lfMoreThanHalf) | ||||
1545 | return true; | ||||
1546 | |||||
1547 | /* Our zeroes don't have a significand to test. */ | ||||
1548 | if (lost_fraction == lfExactlyHalf && category != fcZero) | ||||
1549 | return APInt::tcExtractBit(significandParts(), bit); | ||||
1550 | |||||
1551 | return false; | ||||
1552 | |||||
1553 | case rmTowardZero: | ||||
1554 | return false; | ||||
1555 | |||||
1556 | case rmTowardPositive: | ||||
1557 | return !sign; | ||||
1558 | |||||
1559 | case rmTowardNegative: | ||||
1560 | return sign; | ||||
1561 | |||||
1562 | default: | ||||
1563 | break; | ||||
1564 | } | ||||
1565 | llvm_unreachable("Invalid rounding mode found")::llvm::llvm_unreachable_internal("Invalid rounding mode found" , "llvm/lib/Support/APFloat.cpp", 1565); | ||||
1566 | } | ||||
1567 | |||||
1568 | IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode, | ||||
1569 | lostFraction lost_fraction) { | ||||
1570 | unsigned int omsb; /* One, not zero, based MSB. */ | ||||
1571 | int exponentChange; | ||||
1572 | |||||
1573 | if (!isFiniteNonZero()) | ||||
1574 | return opOK; | ||||
1575 | |||||
1576 | /* Before rounding normalize the exponent of fcNormal numbers. */ | ||||
1577 | omsb = significandMSB() + 1; | ||||
1578 | |||||
1579 | if (omsb) { | ||||
1580 | /* OMSB is numbered from 1. We want to place it in the integer | ||||
1581 | bit numbered PRECISION if possible, with a compensating change in | ||||
1582 | the exponent. */ | ||||
1583 | exponentChange = omsb - semantics->precision; | ||||
1584 | |||||
1585 | /* If the resulting exponent is too high, overflow according to | ||||
1586 | the rounding mode. */ | ||||
1587 | if (exponent + exponentChange > semantics->maxExponent) | ||||
1588 | return handleOverflow(rounding_mode); | ||||
1589 | |||||
1590 | /* Subnormal numbers have exponent minExponent, and their MSB | ||||
1591 | is forced based on that. */ | ||||
1592 | if (exponent + exponentChange < semantics->minExponent) | ||||
1593 | exponentChange = semantics->minExponent - exponent; | ||||
1594 | |||||
1595 | /* Shifting left is easy as we don't lose precision. */ | ||||
1596 | if (exponentChange < 0) { | ||||
1597 | assert(lost_fraction == lfExactlyZero)(static_cast <bool> (lost_fraction == lfExactlyZero) ? void (0) : __assert_fail ("lost_fraction == lfExactlyZero", "llvm/lib/Support/APFloat.cpp" , 1597, __extension__ __PRETTY_FUNCTION__)); | ||||
1598 | |||||
1599 | shiftSignificandLeft(-exponentChange); | ||||
1600 | |||||
1601 | return opOK; | ||||
1602 | } | ||||
1603 | |||||
1604 | if (exponentChange > 0) { | ||||
1605 | lostFraction lf; | ||||
1606 | |||||
1607 | /* Shift right and capture any new lost fraction. */ | ||||
1608 | lf = shiftSignificandRight(exponentChange); | ||||
1609 | |||||
1610 | lost_fraction = combineLostFractions(lf, lost_fraction); | ||||
1611 | |||||
1612 | /* Keep OMSB up-to-date. */ | ||||
1613 | if (omsb > (unsigned) exponentChange) | ||||
1614 | omsb -= exponentChange; | ||||
1615 | else | ||||
1616 | omsb = 0; | ||||
1617 | } | ||||
1618 | } | ||||
1619 | |||||
1620 | // The all-ones values is an overflow if NaN is all ones. If NaN is | ||||
1621 | // represented by negative zero, then it is a valid finite value. | ||||
1622 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly && | ||||
1623 | semantics->nanEncoding == fltNanEncoding::AllOnes && | ||||
1624 | exponent == semantics->maxExponent && isSignificandAllOnes()) | ||||
1625 | return handleOverflow(rounding_mode); | ||||
1626 | |||||
1627 | /* Now round the number according to rounding_mode given the lost | ||||
1628 | fraction. */ | ||||
1629 | |||||
1630 | /* As specified in IEEE 754, since we do not trap we do not report | ||||
1631 | underflow for exact results. */ | ||||
1632 | if (lost_fraction == lfExactlyZero) { | ||||
1633 | /* Canonicalize zeroes. */ | ||||
1634 | if (omsb == 0) { | ||||
1635 | category = fcZero; | ||||
1636 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
1637 | sign = false; | ||||
1638 | } | ||||
1639 | |||||
1640 | return opOK; | ||||
1641 | } | ||||
1642 | |||||
1643 | /* Increment the significand if we're rounding away from zero. */ | ||||
1644 | if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) { | ||||
1645 | if (omsb == 0) | ||||
1646 | exponent = semantics->minExponent; | ||||
1647 | |||||
1648 | incrementSignificand(); | ||||
1649 | omsb = significandMSB() + 1; | ||||
1650 | |||||
1651 | /* Did the significand increment overflow? */ | ||||
1652 | if (omsb == (unsigned) semantics->precision + 1) { | ||||
1653 | /* Renormalize by incrementing the exponent and shifting our | ||||
1654 | significand right one. However if we already have the | ||||
1655 | maximum exponent we overflow to infinity. */ | ||||
1656 | if (exponent == semantics->maxExponent) | ||||
1657 | // Invoke overflow handling with a rounding mode that will guarantee | ||||
1658 | // that the result gets turned into the correct infinity representation. | ||||
1659 | // This is needed instead of just setting the category to infinity to | ||||
1660 | // account for 8-bit floating point types that have no inf, only NaN. | ||||
1661 | return handleOverflow(sign ? rmTowardNegative : rmTowardPositive); | ||||
1662 | |||||
1663 | shiftSignificandRight(1); | ||||
1664 | |||||
1665 | return opInexact; | ||||
1666 | } | ||||
1667 | |||||
1668 | // The all-ones values is an overflow if NaN is all ones. If NaN is | ||||
1669 | // represented by negative zero, then it is a valid finite value. | ||||
1670 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly && | ||||
1671 | semantics->nanEncoding == fltNanEncoding::AllOnes && | ||||
1672 | exponent == semantics->maxExponent && isSignificandAllOnes()) | ||||
1673 | return handleOverflow(rounding_mode); | ||||
1674 | } | ||||
1675 | |||||
1676 | /* The normal case - we were and are not denormal, and any | ||||
1677 | significand increment above didn't overflow. */ | ||||
1678 | if (omsb == semantics->precision) | ||||
1679 | return opInexact; | ||||
1680 | |||||
1681 | /* We have a non-zero denormal. */ | ||||
1682 | assert(omsb < semantics->precision)(static_cast <bool> (omsb < semantics->precision) ? void (0) : __assert_fail ("omsb < semantics->precision" , "llvm/lib/Support/APFloat.cpp", 1682, __extension__ __PRETTY_FUNCTION__ )); | ||||
1683 | |||||
1684 | /* Canonicalize zeroes. */ | ||||
1685 | if (omsb == 0) { | ||||
1686 | category = fcZero; | ||||
1687 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
1688 | sign = false; | ||||
1689 | } | ||||
1690 | |||||
1691 | /* The fcZero case is a denormal that underflowed to zero. */ | ||||
1692 | return (opStatus) (opUnderflow | opInexact); | ||||
1693 | } | ||||
1694 | |||||
1695 | IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs, | ||||
1696 | bool subtract) { | ||||
1697 | switch (PackCategoriesIntoKey(category, rhs.category)((category) * 4 + (rhs.category))) { | ||||
1698 | default: | ||||
1699 | llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/Support/APFloat.cpp" , 1699); | ||||
1700 | |||||
1701 | case PackCategoriesIntoKey(fcZero, fcNaN)((fcZero) * 4 + (fcNaN)): | ||||
1702 | case PackCategoriesIntoKey(fcNormal, fcNaN)((fcNormal) * 4 + (fcNaN)): | ||||
1703 | case PackCategoriesIntoKey(fcInfinity, fcNaN)((fcInfinity) * 4 + (fcNaN)): | ||||
1704 | assign(rhs); | ||||
1705 | [[fallthrough]]; | ||||
1706 | case PackCategoriesIntoKey(fcNaN, fcZero)((fcNaN) * 4 + (fcZero)): | ||||
1707 | case PackCategoriesIntoKey(fcNaN, fcNormal)((fcNaN) * 4 + (fcNormal)): | ||||
1708 | case PackCategoriesIntoKey(fcNaN, fcInfinity)((fcNaN) * 4 + (fcInfinity)): | ||||
1709 | case PackCategoriesIntoKey(fcNaN, fcNaN)((fcNaN) * 4 + (fcNaN)): | ||||
1710 | if (isSignaling()) { | ||||
1711 | makeQuiet(); | ||||
1712 | return opInvalidOp; | ||||
1713 | } | ||||
1714 | return rhs.isSignaling() ? opInvalidOp : opOK; | ||||
1715 | |||||
1716 | case PackCategoriesIntoKey(fcNormal, fcZero)((fcNormal) * 4 + (fcZero)): | ||||
1717 | case PackCategoriesIntoKey(fcInfinity, fcNormal)((fcInfinity) * 4 + (fcNormal)): | ||||
1718 | case PackCategoriesIntoKey(fcInfinity, fcZero)((fcInfinity) * 4 + (fcZero)): | ||||
1719 | return opOK; | ||||
1720 | |||||
1721 | case PackCategoriesIntoKey(fcNormal, fcInfinity)((fcNormal) * 4 + (fcInfinity)): | ||||
1722 | case PackCategoriesIntoKey(fcZero, fcInfinity)((fcZero) * 4 + (fcInfinity)): | ||||
1723 | category = fcInfinity; | ||||
1724 | sign = rhs.sign ^ subtract; | ||||
1725 | return opOK; | ||||
1726 | |||||
1727 | case PackCategoriesIntoKey(fcZero, fcNormal)((fcZero) * 4 + (fcNormal)): | ||||
1728 | assign(rhs); | ||||
1729 | sign = rhs.sign ^ subtract; | ||||
1730 | return opOK; | ||||
1731 | |||||
1732 | case PackCategoriesIntoKey(fcZero, fcZero)((fcZero) * 4 + (fcZero)): | ||||
1733 | /* Sign depends on rounding mode; handled by caller. */ | ||||
1734 | return opOK; | ||||
1735 | |||||
1736 | case PackCategoriesIntoKey(fcInfinity, fcInfinity)((fcInfinity) * 4 + (fcInfinity)): | ||||
1737 | /* Differently signed infinities can only be validly | ||||
1738 | subtracted. */ | ||||
1739 | if (((sign ^ rhs.sign)!=0) != subtract) { | ||||
1740 | makeNaN(); | ||||
1741 | return opInvalidOp; | ||||
1742 | } | ||||
1743 | |||||
1744 | return opOK; | ||||
1745 | |||||
1746 | case PackCategoriesIntoKey(fcNormal, fcNormal)((fcNormal) * 4 + (fcNormal)): | ||||
1747 | return opDivByZero; | ||||
1748 | } | ||||
1749 | } | ||||
1750 | |||||
1751 | /* Add or subtract two normal numbers. */ | ||||
1752 | lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs, | ||||
1753 | bool subtract) { | ||||
1754 | integerPart carry; | ||||
1755 | lostFraction lost_fraction; | ||||
1756 | int bits; | ||||
1757 | |||||
1758 | /* Determine if the operation on the absolute values is effectively | ||||
1759 | an addition or subtraction. */ | ||||
1760 | subtract ^= static_cast<bool>(sign ^ rhs.sign); | ||||
1761 | |||||
1762 | /* Are we bigger exponent-wise than the RHS? */ | ||||
1763 | bits = exponent - rhs.exponent; | ||||
1764 | |||||
1765 | /* Subtraction is more subtle than one might naively expect. */ | ||||
1766 | if (subtract) { | ||||
1767 | IEEEFloat temp_rhs(rhs); | ||||
1768 | |||||
1769 | if (bits == 0) | ||||
1770 | lost_fraction = lfExactlyZero; | ||||
1771 | else if (bits > 0) { | ||||
1772 | lost_fraction = temp_rhs.shiftSignificandRight(bits - 1); | ||||
1773 | shiftSignificandLeft(1); | ||||
1774 | } else { | ||||
1775 | lost_fraction = shiftSignificandRight(-bits - 1); | ||||
1776 | temp_rhs.shiftSignificandLeft(1); | ||||
1777 | } | ||||
1778 | |||||
1779 | // Should we reverse the subtraction. | ||||
1780 | if (compareAbsoluteValue(temp_rhs) == cmpLessThan) { | ||||
1781 | carry = temp_rhs.subtractSignificand | ||||
1782 | (*this, lost_fraction != lfExactlyZero); | ||||
1783 | copySignificand(temp_rhs); | ||||
1784 | sign = !sign; | ||||
1785 | } else { | ||||
1786 | carry = subtractSignificand | ||||
1787 | (temp_rhs, lost_fraction != lfExactlyZero); | ||||
1788 | } | ||||
1789 | |||||
1790 | /* Invert the lost fraction - it was on the RHS and | ||||
1791 | subtracted. */ | ||||
1792 | if (lost_fraction == lfLessThanHalf) | ||||
1793 | lost_fraction = lfMoreThanHalf; | ||||
1794 | else if (lost_fraction == lfMoreThanHalf) | ||||
1795 | lost_fraction = lfLessThanHalf; | ||||
1796 | |||||
1797 | /* The code above is intended to ensure that no borrow is | ||||
1798 | necessary. */ | ||||
1799 | assert(!carry)(static_cast <bool> (!carry) ? void (0) : __assert_fail ("!carry", "llvm/lib/Support/APFloat.cpp", 1799, __extension__ __PRETTY_FUNCTION__)); | ||||
1800 | (void)carry; | ||||
1801 | } else { | ||||
1802 | if (bits > 0) { | ||||
1803 | IEEEFloat temp_rhs(rhs); | ||||
1804 | |||||
1805 | lost_fraction = temp_rhs.shiftSignificandRight(bits); | ||||
1806 | carry = addSignificand(temp_rhs); | ||||
1807 | } else { | ||||
1808 | lost_fraction = shiftSignificandRight(-bits); | ||||
1809 | carry = addSignificand(rhs); | ||||
1810 | } | ||||
1811 | |||||
1812 | /* We have a guard bit; generating a carry cannot happen. */ | ||||
1813 | assert(!carry)(static_cast <bool> (!carry) ? void (0) : __assert_fail ("!carry", "llvm/lib/Support/APFloat.cpp", 1813, __extension__ __PRETTY_FUNCTION__)); | ||||
1814 | (void)carry; | ||||
1815 | } | ||||
1816 | |||||
1817 | return lost_fraction; | ||||
1818 | } | ||||
1819 | |||||
1820 | IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) { | ||||
1821 | switch (PackCategoriesIntoKey(category, rhs.category)((category) * 4 + (rhs.category))) { | ||||
1822 | default: | ||||
1823 | llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/Support/APFloat.cpp" , 1823); | ||||
1824 | |||||
1825 | case PackCategoriesIntoKey(fcZero, fcNaN)((fcZero) * 4 + (fcNaN)): | ||||
1826 | case PackCategoriesIntoKey(fcNormal, fcNaN)((fcNormal) * 4 + (fcNaN)): | ||||
1827 | case PackCategoriesIntoKey(fcInfinity, fcNaN)((fcInfinity) * 4 + (fcNaN)): | ||||
1828 | assign(rhs); | ||||
1829 | sign = false; | ||||
1830 | [[fallthrough]]; | ||||
1831 | case PackCategoriesIntoKey(fcNaN, fcZero)((fcNaN) * 4 + (fcZero)): | ||||
1832 | case PackCategoriesIntoKey(fcNaN, fcNormal)((fcNaN) * 4 + (fcNormal)): | ||||
1833 | case PackCategoriesIntoKey(fcNaN, fcInfinity)((fcNaN) * 4 + (fcInfinity)): | ||||
1834 | case PackCategoriesIntoKey(fcNaN, fcNaN)((fcNaN) * 4 + (fcNaN)): | ||||
1835 | sign ^= rhs.sign; // restore the original sign | ||||
1836 | if (isSignaling()) { | ||||
1837 | makeQuiet(); | ||||
1838 | return opInvalidOp; | ||||
1839 | } | ||||
1840 | return rhs.isSignaling() ? opInvalidOp : opOK; | ||||
1841 | |||||
1842 | case PackCategoriesIntoKey(fcNormal, fcInfinity)((fcNormal) * 4 + (fcInfinity)): | ||||
1843 | case PackCategoriesIntoKey(fcInfinity, fcNormal)((fcInfinity) * 4 + (fcNormal)): | ||||
1844 | case PackCategoriesIntoKey(fcInfinity, fcInfinity)((fcInfinity) * 4 + (fcInfinity)): | ||||
1845 | category = fcInfinity; | ||||
1846 | return opOK; | ||||
1847 | |||||
1848 | case PackCategoriesIntoKey(fcZero, fcNormal)((fcZero) * 4 + (fcNormal)): | ||||
1849 | case PackCategoriesIntoKey(fcNormal, fcZero)((fcNormal) * 4 + (fcZero)): | ||||
1850 | case PackCategoriesIntoKey(fcZero, fcZero)((fcZero) * 4 + (fcZero)): | ||||
1851 | category = fcZero; | ||||
1852 | return opOK; | ||||
1853 | |||||
1854 | case PackCategoriesIntoKey(fcZero, fcInfinity)((fcZero) * 4 + (fcInfinity)): | ||||
1855 | case PackCategoriesIntoKey(fcInfinity, fcZero)((fcInfinity) * 4 + (fcZero)): | ||||
1856 | makeNaN(); | ||||
1857 | return opInvalidOp; | ||||
1858 | |||||
1859 | case PackCategoriesIntoKey(fcNormal, fcNormal)((fcNormal) * 4 + (fcNormal)): | ||||
1860 | return opOK; | ||||
1861 | } | ||||
1862 | } | ||||
1863 | |||||
1864 | IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) { | ||||
1865 | switch (PackCategoriesIntoKey(category, rhs.category)((category) * 4 + (rhs.category))) { | ||||
1866 | default: | ||||
1867 | llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/Support/APFloat.cpp" , 1867); | ||||
1868 | |||||
1869 | case PackCategoriesIntoKey(fcZero, fcNaN)((fcZero) * 4 + (fcNaN)): | ||||
1870 | case PackCategoriesIntoKey(fcNormal, fcNaN)((fcNormal) * 4 + (fcNaN)): | ||||
1871 | case PackCategoriesIntoKey(fcInfinity, fcNaN)((fcInfinity) * 4 + (fcNaN)): | ||||
1872 | assign(rhs); | ||||
1873 | sign = false; | ||||
1874 | [[fallthrough]]; | ||||
1875 | case PackCategoriesIntoKey(fcNaN, fcZero)((fcNaN) * 4 + (fcZero)): | ||||
1876 | case PackCategoriesIntoKey(fcNaN, fcNormal)((fcNaN) * 4 + (fcNormal)): | ||||
1877 | case PackCategoriesIntoKey(fcNaN, fcInfinity)((fcNaN) * 4 + (fcInfinity)): | ||||
1878 | case PackCategoriesIntoKey(fcNaN, fcNaN)((fcNaN) * 4 + (fcNaN)): | ||||
1879 | sign ^= rhs.sign; // restore the original sign | ||||
1880 | if (isSignaling()) { | ||||
1881 | makeQuiet(); | ||||
1882 | return opInvalidOp; | ||||
1883 | } | ||||
1884 | return rhs.isSignaling() ? opInvalidOp : opOK; | ||||
1885 | |||||
1886 | case PackCategoriesIntoKey(fcInfinity, fcZero)((fcInfinity) * 4 + (fcZero)): | ||||
1887 | case PackCategoriesIntoKey(fcInfinity, fcNormal)((fcInfinity) * 4 + (fcNormal)): | ||||
1888 | case PackCategoriesIntoKey(fcZero, fcInfinity)((fcZero) * 4 + (fcInfinity)): | ||||
1889 | case PackCategoriesIntoKey(fcZero, fcNormal)((fcZero) * 4 + (fcNormal)): | ||||
1890 | return opOK; | ||||
1891 | |||||
1892 | case PackCategoriesIntoKey(fcNormal, fcInfinity)((fcNormal) * 4 + (fcInfinity)): | ||||
1893 | category = fcZero; | ||||
1894 | return opOK; | ||||
1895 | |||||
1896 | case PackCategoriesIntoKey(fcNormal, fcZero)((fcNormal) * 4 + (fcZero)): | ||||
1897 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) | ||||
1898 | makeNaN(false, sign); | ||||
1899 | else | ||||
1900 | category = fcInfinity; | ||||
1901 | return opDivByZero; | ||||
1902 | |||||
1903 | case PackCategoriesIntoKey(fcInfinity, fcInfinity)((fcInfinity) * 4 + (fcInfinity)): | ||||
1904 | case PackCategoriesIntoKey(fcZero, fcZero)((fcZero) * 4 + (fcZero)): | ||||
1905 | makeNaN(); | ||||
1906 | return opInvalidOp; | ||||
1907 | |||||
1908 | case PackCategoriesIntoKey(fcNormal, fcNormal)((fcNormal) * 4 + (fcNormal)): | ||||
1909 | return opOK; | ||||
1910 | } | ||||
1911 | } | ||||
1912 | |||||
1913 | IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) { | ||||
1914 | switch (PackCategoriesIntoKey(category, rhs.category)((category) * 4 + (rhs.category))) { | ||||
1915 | default: | ||||
1916 | llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/Support/APFloat.cpp" , 1916); | ||||
1917 | |||||
1918 | case PackCategoriesIntoKey(fcZero, fcNaN)((fcZero) * 4 + (fcNaN)): | ||||
1919 | case PackCategoriesIntoKey(fcNormal, fcNaN)((fcNormal) * 4 + (fcNaN)): | ||||
1920 | case PackCategoriesIntoKey(fcInfinity, fcNaN)((fcInfinity) * 4 + (fcNaN)): | ||||
1921 | assign(rhs); | ||||
1922 | [[fallthrough]]; | ||||
1923 | case PackCategoriesIntoKey(fcNaN, fcZero)((fcNaN) * 4 + (fcZero)): | ||||
1924 | case PackCategoriesIntoKey(fcNaN, fcNormal)((fcNaN) * 4 + (fcNormal)): | ||||
1925 | case PackCategoriesIntoKey(fcNaN, fcInfinity)((fcNaN) * 4 + (fcInfinity)): | ||||
1926 | case PackCategoriesIntoKey(fcNaN, fcNaN)((fcNaN) * 4 + (fcNaN)): | ||||
1927 | if (isSignaling()) { | ||||
1928 | makeQuiet(); | ||||
1929 | return opInvalidOp; | ||||
1930 | } | ||||
1931 | return rhs.isSignaling() ? opInvalidOp : opOK; | ||||
1932 | |||||
1933 | case PackCategoriesIntoKey(fcZero, fcInfinity)((fcZero) * 4 + (fcInfinity)): | ||||
1934 | case PackCategoriesIntoKey(fcZero, fcNormal)((fcZero) * 4 + (fcNormal)): | ||||
1935 | case PackCategoriesIntoKey(fcNormal, fcInfinity)((fcNormal) * 4 + (fcInfinity)): | ||||
1936 | return opOK; | ||||
1937 | |||||
1938 | case PackCategoriesIntoKey(fcNormal, fcZero)((fcNormal) * 4 + (fcZero)): | ||||
1939 | case PackCategoriesIntoKey(fcInfinity, fcZero)((fcInfinity) * 4 + (fcZero)): | ||||
1940 | case PackCategoriesIntoKey(fcInfinity, fcNormal)((fcInfinity) * 4 + (fcNormal)): | ||||
1941 | case PackCategoriesIntoKey(fcInfinity, fcInfinity)((fcInfinity) * 4 + (fcInfinity)): | ||||
1942 | case PackCategoriesIntoKey(fcZero, fcZero)((fcZero) * 4 + (fcZero)): | ||||
1943 | makeNaN(); | ||||
1944 | return opInvalidOp; | ||||
1945 | |||||
1946 | case PackCategoriesIntoKey(fcNormal, fcNormal)((fcNormal) * 4 + (fcNormal)): | ||||
1947 | return opOK; | ||||
1948 | } | ||||
1949 | } | ||||
1950 | |||||
1951 | IEEEFloat::opStatus IEEEFloat::remainderSpecials(const IEEEFloat &rhs) { | ||||
1952 | switch (PackCategoriesIntoKey(category, rhs.category)((category) * 4 + (rhs.category))) { | ||||
1953 | default: | ||||
1954 | llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/Support/APFloat.cpp" , 1954); | ||||
1955 | |||||
1956 | case PackCategoriesIntoKey(fcZero, fcNaN)((fcZero) * 4 + (fcNaN)): | ||||
1957 | case PackCategoriesIntoKey(fcNormal, fcNaN)((fcNormal) * 4 + (fcNaN)): | ||||
1958 | case PackCategoriesIntoKey(fcInfinity, fcNaN)((fcInfinity) * 4 + (fcNaN)): | ||||
1959 | assign(rhs); | ||||
1960 | [[fallthrough]]; | ||||
1961 | case PackCategoriesIntoKey(fcNaN, fcZero)((fcNaN) * 4 + (fcZero)): | ||||
1962 | case PackCategoriesIntoKey(fcNaN, fcNormal)((fcNaN) * 4 + (fcNormal)): | ||||
1963 | case PackCategoriesIntoKey(fcNaN, fcInfinity)((fcNaN) * 4 + (fcInfinity)): | ||||
1964 | case PackCategoriesIntoKey(fcNaN, fcNaN)((fcNaN) * 4 + (fcNaN)): | ||||
1965 | if (isSignaling()) { | ||||
1966 | makeQuiet(); | ||||
1967 | return opInvalidOp; | ||||
1968 | } | ||||
1969 | return rhs.isSignaling() ? opInvalidOp : opOK; | ||||
1970 | |||||
1971 | case PackCategoriesIntoKey(fcZero, fcInfinity)((fcZero) * 4 + (fcInfinity)): | ||||
1972 | case PackCategoriesIntoKey(fcZero, fcNormal)((fcZero) * 4 + (fcNormal)): | ||||
1973 | case PackCategoriesIntoKey(fcNormal, fcInfinity)((fcNormal) * 4 + (fcInfinity)): | ||||
1974 | return opOK; | ||||
1975 | |||||
1976 | case PackCategoriesIntoKey(fcNormal, fcZero)((fcNormal) * 4 + (fcZero)): | ||||
1977 | case PackCategoriesIntoKey(fcInfinity, fcZero)((fcInfinity) * 4 + (fcZero)): | ||||
1978 | case PackCategoriesIntoKey(fcInfinity, fcNormal)((fcInfinity) * 4 + (fcNormal)): | ||||
1979 | case PackCategoriesIntoKey(fcInfinity, fcInfinity)((fcInfinity) * 4 + (fcInfinity)): | ||||
1980 | case PackCategoriesIntoKey(fcZero, fcZero)((fcZero) * 4 + (fcZero)): | ||||
1981 | makeNaN(); | ||||
1982 | return opInvalidOp; | ||||
1983 | |||||
1984 | case PackCategoriesIntoKey(fcNormal, fcNormal)((fcNormal) * 4 + (fcNormal)): | ||||
1985 | return opDivByZero; // fake status, indicating this is not a special case | ||||
1986 | } | ||||
1987 | } | ||||
1988 | |||||
1989 | /* Change sign. */ | ||||
1990 | void IEEEFloat::changeSign() { | ||||
1991 | // With NaN-as-negative-zero, neither NaN or negative zero can change | ||||
1992 | // their signs. | ||||
1993 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero && | ||||
1994 | (isZero() || isNaN())) | ||||
1995 | return; | ||||
1996 | /* Look mummy, this one's easy. */ | ||||
1997 | sign = !sign; | ||||
1998 | } | ||||
1999 | |||||
2000 | /* Normalized addition or subtraction. */ | ||||
2001 | IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs, | ||||
2002 | roundingMode rounding_mode, | ||||
2003 | bool subtract) { | ||||
2004 | opStatus fs; | ||||
2005 | |||||
2006 | fs = addOrSubtractSpecials(rhs, subtract); | ||||
2007 | |||||
2008 | /* This return code means it was not a simple case. */ | ||||
2009 | if (fs == opDivByZero) { | ||||
2010 | lostFraction lost_fraction; | ||||
2011 | |||||
2012 | lost_fraction = addOrSubtractSignificand(rhs, subtract); | ||||
2013 | fs = normalize(rounding_mode, lost_fraction); | ||||
2014 | |||||
2015 | /* Can only be zero if we lost no fraction. */ | ||||
2016 | assert(category != fcZero || lost_fraction == lfExactlyZero)(static_cast <bool> (category != fcZero || lost_fraction == lfExactlyZero) ? void (0) : __assert_fail ("category != fcZero || lost_fraction == lfExactlyZero" , "llvm/lib/Support/APFloat.cpp", 2016, __extension__ __PRETTY_FUNCTION__ )); | ||||
2017 | } | ||||
2018 | |||||
2019 | /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a | ||||
2020 | positive zero unless rounding to minus infinity, except that | ||||
2021 | adding two like-signed zeroes gives that zero. */ | ||||
2022 | if (category == fcZero) { | ||||
2023 | if (rhs.category != fcZero || (sign == rhs.sign) == subtract) | ||||
2024 | sign = (rounding_mode == rmTowardNegative); | ||||
2025 | // NaN-in-negative-zero means zeros need to be normalized to +0. | ||||
2026 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
2027 | sign = false; | ||||
2028 | } | ||||
2029 | |||||
2030 | return fs; | ||||
2031 | } | ||||
2032 | |||||
2033 | /* Normalized addition. */ | ||||
2034 | IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs, | ||||
2035 | roundingMode rounding_mode) { | ||||
2036 | return addOrSubtract(rhs, rounding_mode, false); | ||||
2037 | } | ||||
2038 | |||||
2039 | /* Normalized subtraction. */ | ||||
2040 | IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs, | ||||
2041 | roundingMode rounding_mode) { | ||||
2042 | return addOrSubtract(rhs, rounding_mode, true); | ||||
2043 | } | ||||
2044 | |||||
2045 | /* Normalized multiply. */ | ||||
2046 | IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs, | ||||
2047 | roundingMode rounding_mode) { | ||||
2048 | opStatus fs; | ||||
2049 | |||||
2050 | sign ^= rhs.sign; | ||||
2051 | fs = multiplySpecials(rhs); | ||||
2052 | |||||
2053 | if (isZero() && semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
2054 | sign = false; | ||||
2055 | if (isFiniteNonZero()) { | ||||
2056 | lostFraction lost_fraction = multiplySignificand(rhs); | ||||
2057 | fs = normalize(rounding_mode, lost_fraction); | ||||
2058 | if (lost_fraction != lfExactlyZero) | ||||
2059 | fs = (opStatus) (fs | opInexact); | ||||
2060 | } | ||||
2061 | |||||
2062 | return fs; | ||||
2063 | } | ||||
2064 | |||||
2065 | /* Normalized divide. */ | ||||
2066 | IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs, | ||||
2067 | roundingMode rounding_mode) { | ||||
2068 | opStatus fs; | ||||
2069 | |||||
2070 | sign ^= rhs.sign; | ||||
2071 | fs = divideSpecials(rhs); | ||||
2072 | |||||
2073 | if (isZero() && semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
2074 | sign = false; | ||||
2075 | if (isFiniteNonZero()) { | ||||
2076 | lostFraction lost_fraction = divideSignificand(rhs); | ||||
2077 | fs = normalize(rounding_mode, lost_fraction); | ||||
2078 | if (lost_fraction != lfExactlyZero) | ||||
2079 | fs = (opStatus) (fs | opInexact); | ||||
2080 | } | ||||
2081 | |||||
2082 | return fs; | ||||
2083 | } | ||||
2084 | |||||
2085 | /* Normalized remainder. */ | ||||
2086 | IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) { | ||||
2087 | opStatus fs; | ||||
2088 | unsigned int origSign = sign; | ||||
2089 | |||||
2090 | // First handle the special cases. | ||||
2091 | fs = remainderSpecials(rhs); | ||||
2092 | if (fs != opDivByZero) | ||||
2093 | return fs; | ||||
2094 | |||||
2095 | fs = opOK; | ||||
2096 | |||||
2097 | // Make sure the current value is less than twice the denom. If the addition | ||||
2098 | // did not succeed (an overflow has happened), which means that the finite | ||||
2099 | // value we currently posses must be less than twice the denom (as we are | ||||
2100 | // using the same semantics). | ||||
2101 | IEEEFloat P2 = rhs; | ||||
2102 | if (P2.add(rhs, rmNearestTiesToEven) == opOK) { | ||||
2103 | fs = mod(P2); | ||||
2104 | assert(fs == opOK)(static_cast <bool> (fs == opOK) ? void (0) : __assert_fail ("fs == opOK", "llvm/lib/Support/APFloat.cpp", 2104, __extension__ __PRETTY_FUNCTION__)); | ||||
2105 | } | ||||
2106 | |||||
2107 | // Lets work with absolute numbers. | ||||
2108 | IEEEFloat P = rhs; | ||||
2109 | P.sign = false; | ||||
2110 | sign = false; | ||||
2111 | |||||
2112 | // | ||||
2113 | // To calculate the remainder we use the following scheme. | ||||
2114 | // | ||||
2115 | // The remainder is defained as follows: | ||||
2116 | // | ||||
2117 | // remainder = numer - rquot * denom = x - r * p | ||||
2118 | // | ||||
2119 | // Where r is the result of: x/p, rounded toward the nearest integral value | ||||
2120 | // (with halfway cases rounded toward the even number). | ||||
2121 | // | ||||
2122 | // Currently, (after x mod 2p): | ||||
2123 | // r is the number of 2p's present inside x, which is inherently, an even | ||||
2124 | // number of p's. | ||||
2125 | // | ||||
2126 | // We may split the remaining calculation into 4 options: | ||||
2127 | // - if x < 0.5p then we round to the nearest number with is 0, and are done. | ||||
2128 | // - if x == 0.5p then we round to the nearest even number which is 0, and we | ||||
2129 | // are done as well. | ||||
2130 | // - if 0.5p < x < p then we round to nearest number which is 1, and we have | ||||
2131 | // to subtract 1p at least once. | ||||
2132 | // - if x >= p then we must subtract p at least once, as x must be a | ||||
2133 | // remainder. | ||||
2134 | // | ||||
2135 | // By now, we were done, or we added 1 to r, which in turn, now an odd number. | ||||
2136 | // | ||||
2137 | // We can now split the remaining calculation to the following 3 options: | ||||
2138 | // - if x < 0.5p then we round to the nearest number with is 0, and are done. | ||||
2139 | // - if x == 0.5p then we round to the nearest even number. As r is odd, we | ||||
2140 | // must round up to the next even number. so we must subtract p once more. | ||||
2141 | // - if x > 0.5p (and inherently x < p) then we must round r up to the next | ||||
2142 | // integral, and subtract p once more. | ||||
2143 | // | ||||
2144 | |||||
2145 | // Extend the semantics to prevent an overflow/underflow or inexact result. | ||||
2146 | bool losesInfo; | ||||
2147 | fltSemantics extendedSemantics = *semantics; | ||||
2148 | extendedSemantics.maxExponent++; | ||||
2149 | extendedSemantics.minExponent--; | ||||
2150 | extendedSemantics.precision += 2; | ||||
2151 | |||||
2152 | IEEEFloat VEx = *this; | ||||
2153 | fs = VEx.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo); | ||||
2154 | assert(fs == opOK && !losesInfo)(static_cast <bool> (fs == opOK && !losesInfo) ? void (0) : __assert_fail ("fs == opOK && !losesInfo" , "llvm/lib/Support/APFloat.cpp", 2154, __extension__ __PRETTY_FUNCTION__ )); | ||||
2155 | IEEEFloat PEx = P; | ||||
2156 | fs = PEx.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo); | ||||
2157 | assert(fs == opOK && !losesInfo)(static_cast <bool> (fs == opOK && !losesInfo) ? void (0) : __assert_fail ("fs == opOK && !losesInfo" , "llvm/lib/Support/APFloat.cpp", 2157, __extension__ __PRETTY_FUNCTION__ )); | ||||
2158 | |||||
2159 | // It is simpler to work with 2x instead of 0.5p, and we do not need to lose | ||||
2160 | // any fraction. | ||||
2161 | fs = VEx.add(VEx, rmNearestTiesToEven); | ||||
2162 | assert(fs == opOK)(static_cast <bool> (fs == opOK) ? void (0) : __assert_fail ("fs == opOK", "llvm/lib/Support/APFloat.cpp", 2162, __extension__ __PRETTY_FUNCTION__)); | ||||
2163 | |||||
2164 | if (VEx.compare(PEx) == cmpGreaterThan) { | ||||
2165 | fs = subtract(P, rmNearestTiesToEven); | ||||
2166 | assert(fs == opOK)(static_cast <bool> (fs == opOK) ? void (0) : __assert_fail ("fs == opOK", "llvm/lib/Support/APFloat.cpp", 2166, __extension__ __PRETTY_FUNCTION__)); | ||||
2167 | |||||
2168 | // Make VEx = this.add(this), but because we have different semantics, we do | ||||
2169 | // not want to `convert` again, so we just subtract PEx twice (which equals | ||||
2170 | // to the desired value). | ||||
2171 | fs = VEx.subtract(PEx, rmNearestTiesToEven); | ||||
2172 | assert(fs == opOK)(static_cast <bool> (fs == opOK) ? void (0) : __assert_fail ("fs == opOK", "llvm/lib/Support/APFloat.cpp", 2172, __extension__ __PRETTY_FUNCTION__)); | ||||
2173 | fs = VEx.subtract(PEx, rmNearestTiesToEven); | ||||
2174 | assert(fs == opOK)(static_cast <bool> (fs == opOK) ? void (0) : __assert_fail ("fs == opOK", "llvm/lib/Support/APFloat.cpp", 2174, __extension__ __PRETTY_FUNCTION__)); | ||||
2175 | |||||
2176 | cmpResult result = VEx.compare(PEx); | ||||
2177 | if (result == cmpGreaterThan || result == cmpEqual) { | ||||
2178 | fs = subtract(P, rmNearestTiesToEven); | ||||
2179 | assert(fs == opOK)(static_cast <bool> (fs == opOK) ? void (0) : __assert_fail ("fs == opOK", "llvm/lib/Support/APFloat.cpp", 2179, __extension__ __PRETTY_FUNCTION__)); | ||||
2180 | } | ||||
2181 | } | ||||
2182 | |||||
2183 | if (isZero()) { | ||||
2184 | sign = origSign; // IEEE754 requires this | ||||
2185 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
2186 | // But some 8-bit floats only have positive 0. | ||||
2187 | sign = false; | ||||
2188 | } | ||||
2189 | |||||
2190 | else | ||||
2191 | sign ^= origSign; | ||||
2192 | return fs; | ||||
2193 | } | ||||
2194 | |||||
2195 | /* Normalized llvm frem (C fmod). */ | ||||
2196 | IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) { | ||||
2197 | opStatus fs; | ||||
2198 | fs = modSpecials(rhs); | ||||
2199 | unsigned int origSign = sign; | ||||
2200 | |||||
2201 | while (isFiniteNonZero() && rhs.isFiniteNonZero() && | ||||
2202 | compareAbsoluteValue(rhs) != cmpLessThan) { | ||||
2203 | int Exp = ilogb(*this) - ilogb(rhs); | ||||
2204 | IEEEFloat V = scalbn(rhs, Exp, rmNearestTiesToEven); | ||||
2205 | // V can overflow to NaN with fltNonfiniteBehavior::NanOnly, so explicitly | ||||
2206 | // check for it. | ||||
2207 | if (V.isNaN() || compareAbsoluteValue(V) == cmpLessThan) | ||||
2208 | V = scalbn(rhs, Exp - 1, rmNearestTiesToEven); | ||||
2209 | V.sign = sign; | ||||
2210 | |||||
2211 | fs = subtract(V, rmNearestTiesToEven); | ||||
2212 | assert(fs==opOK)(static_cast <bool> (fs==opOK) ? void (0) : __assert_fail ("fs==opOK", "llvm/lib/Support/APFloat.cpp", 2212, __extension__ __PRETTY_FUNCTION__)); | ||||
2213 | } | ||||
2214 | if (isZero()) { | ||||
2215 | sign = origSign; // fmod requires this | ||||
2216 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
2217 | sign = false; | ||||
2218 | } | ||||
2219 | return fs; | ||||
2220 | } | ||||
2221 | |||||
2222 | /* Normalized fused-multiply-add. */ | ||||
2223 | IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand, | ||||
2224 | const IEEEFloat &addend, | ||||
2225 | roundingMode rounding_mode) { | ||||
2226 | opStatus fs; | ||||
2227 | |||||
2228 | /* Post-multiplication sign, before addition. */ | ||||
2229 | sign ^= multiplicand.sign; | ||||
2230 | |||||
2231 | /* If and only if all arguments are normal do we need to do an | ||||
2232 | extended-precision calculation. */ | ||||
2233 | if (isFiniteNonZero() && | ||||
2234 | multiplicand.isFiniteNonZero() && | ||||
2235 | addend.isFinite()) { | ||||
2236 | lostFraction lost_fraction; | ||||
2237 | |||||
2238 | lost_fraction = multiplySignificand(multiplicand, addend); | ||||
2239 | fs = normalize(rounding_mode, lost_fraction); | ||||
2240 | if (lost_fraction != lfExactlyZero) | ||||
2241 | fs = (opStatus) (fs | opInexact); | ||||
2242 | |||||
2243 | /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a | ||||
2244 | positive zero unless rounding to minus infinity, except that | ||||
2245 | adding two like-signed zeroes gives that zero. */ | ||||
2246 | if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign) { | ||||
2247 | sign = (rounding_mode == rmTowardNegative); | ||||
2248 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
2249 | sign = false; | ||||
2250 | } | ||||
2251 | } else { | ||||
2252 | fs = multiplySpecials(multiplicand); | ||||
2253 | |||||
2254 | /* FS can only be opOK or opInvalidOp. There is no more work | ||||
2255 | to do in the latter case. The IEEE-754R standard says it is | ||||
2256 | implementation-defined in this case whether, if ADDEND is a | ||||
2257 | quiet NaN, we raise invalid op; this implementation does so. | ||||
2258 | |||||
2259 | If we need to do the addition we can do so with normal | ||||
2260 | precision. */ | ||||
2261 | if (fs == opOK) | ||||
2262 | fs = addOrSubtract(addend, rounding_mode, false); | ||||
2263 | } | ||||
2264 | |||||
2265 | return fs; | ||||
2266 | } | ||||
2267 | |||||
2268 | /* Rounding-mode correct round to integral value. */ | ||||
2269 | IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) { | ||||
2270 | opStatus fs; | ||||
2271 | |||||
2272 | if (isInfinity()) | ||||
2273 | // [IEEE Std 754-2008 6.1]: | ||||
2274 | // The behavior of infinity in floating-point arithmetic is derived from the | ||||
2275 | // limiting cases of real arithmetic with operands of arbitrarily | ||||
2276 | // large magnitude, when such a limit exists. | ||||
2277 | // ... | ||||
2278 | // Operations on infinite operands are usually exact and therefore signal no | ||||
2279 | // exceptions ... | ||||
2280 | return opOK; | ||||
2281 | |||||
2282 | if (isNaN()) { | ||||
2283 | if (isSignaling()) { | ||||
2284 | // [IEEE Std 754-2008 6.2]: | ||||
2285 | // Under default exception handling, any operation signaling an invalid | ||||
2286 | // operation exception and for which a floating-point result is to be | ||||
2287 | // delivered shall deliver a quiet NaN. | ||||
2288 | makeQuiet(); | ||||
2289 | // [IEEE Std 754-2008 6.2]: | ||||
2290 | // Signaling NaNs shall be reserved operands that, under default exception | ||||
2291 | // handling, signal the invalid operation exception(see 7.2) for every | ||||
2292 | // general-computational and signaling-computational operation except for | ||||
2293 | // the conversions described in 5.12. | ||||
2294 | return opInvalidOp; | ||||
2295 | } else { | ||||
2296 | // [IEEE Std 754-2008 6.2]: | ||||
2297 | // For an operation with quiet NaN inputs, other than maximum and minimum | ||||
2298 | // operations, if a floating-point result is to be delivered the result | ||||
2299 | // shall be a quiet NaN which should be one of the input NaNs. | ||||
2300 | // ... | ||||
2301 | // Every general-computational and quiet-computational operation involving | ||||
2302 | // one or more input NaNs, none of them signaling, shall signal no | ||||
2303 | // exception, except fusedMultiplyAdd might signal the invalid operation | ||||
2304 | // exception(see 7.2). | ||||
2305 | return opOK; | ||||
2306 | } | ||||
2307 | } | ||||
2308 | |||||
2309 | if (isZero()) { | ||||
2310 | // [IEEE Std 754-2008 6.3]: | ||||
2311 | // ... the sign of the result of conversions, the quantize operation, the | ||||
2312 | // roundToIntegral operations, and the roundToIntegralExact(see 5.3.1) is | ||||
2313 | // the sign of the first or only operand. | ||||
2314 | return opOK; | ||||
2315 | } | ||||
2316 | |||||
2317 | // If the exponent is large enough, we know that this value is already | ||||
2318 | // integral, and the arithmetic below would potentially cause it to saturate | ||||
2319 | // to +/-Inf. Bail out early instead. | ||||
2320 | if (exponent+1 >= (int)semanticsPrecision(*semantics)) | ||||
2321 | return opOK; | ||||
2322 | |||||
2323 | // The algorithm here is quite simple: we add 2^(p-1), where p is the | ||||
2324 | // precision of our format, and then subtract it back off again. The choice | ||||
2325 | // of rounding modes for the addition/subtraction determines the rounding mode | ||||
2326 | // for our integral rounding as well. | ||||
2327 | // NOTE: When the input value is negative, we do subtraction followed by | ||||
2328 | // addition instead. | ||||
2329 | APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1); | ||||
2330 | IntegerConstant <<= semanticsPrecision(*semantics)-1; | ||||
2331 | IEEEFloat MagicConstant(*semantics); | ||||
2332 | fs = MagicConstant.convertFromAPInt(IntegerConstant, false, | ||||
2333 | rmNearestTiesToEven); | ||||
2334 | assert(fs == opOK)(static_cast <bool> (fs == opOK) ? void (0) : __assert_fail ("fs == opOK", "llvm/lib/Support/APFloat.cpp", 2334, __extension__ __PRETTY_FUNCTION__)); | ||||
2335 | MagicConstant.sign = sign; | ||||
2336 | |||||
2337 | // Preserve the input sign so that we can handle the case of zero result | ||||
2338 | // correctly. | ||||
2339 | bool inputSign = isNegative(); | ||||
2340 | |||||
2341 | fs = add(MagicConstant, rounding_mode); | ||||
2342 | |||||
2343 | // Current value and 'MagicConstant' are both integers, so the result of the | ||||
2344 | // subtraction is always exact according to Sterbenz' lemma. | ||||
2345 | subtract(MagicConstant, rounding_mode); | ||||
2346 | |||||
2347 | // Restore the input sign. | ||||
2348 | if (inputSign != isNegative()) | ||||
2349 | changeSign(); | ||||
2350 | |||||
2351 | return fs; | ||||
2352 | } | ||||
2353 | |||||
2354 | |||||
2355 | /* Comparison requires normalized numbers. */ | ||||
2356 | IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const { | ||||
2357 | cmpResult result; | ||||
2358 | |||||
2359 | assert(semantics == rhs.semantics)(static_cast <bool> (semantics == rhs.semantics) ? void (0) : __assert_fail ("semantics == rhs.semantics", "llvm/lib/Support/APFloat.cpp" , 2359, __extension__ __PRETTY_FUNCTION__)); | ||||
2360 | |||||
2361 | switch (PackCategoriesIntoKey(category, rhs.category)((category) * 4 + (rhs.category))) { | ||||
2362 | default: | ||||
2363 | llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/Support/APFloat.cpp" , 2363); | ||||
2364 | |||||
2365 | case PackCategoriesIntoKey(fcNaN, fcZero)((fcNaN) * 4 + (fcZero)): | ||||
2366 | case PackCategoriesIntoKey(fcNaN, fcNormal)((fcNaN) * 4 + (fcNormal)): | ||||
2367 | case PackCategoriesIntoKey(fcNaN, fcInfinity)((fcNaN) * 4 + (fcInfinity)): | ||||
2368 | case PackCategoriesIntoKey(fcNaN, fcNaN)((fcNaN) * 4 + (fcNaN)): | ||||
2369 | case PackCategoriesIntoKey(fcZero, fcNaN)((fcZero) * 4 + (fcNaN)): | ||||
2370 | case PackCategoriesIntoKey(fcNormal, fcNaN)((fcNormal) * 4 + (fcNaN)): | ||||
2371 | case PackCategoriesIntoKey(fcInfinity, fcNaN)((fcInfinity) * 4 + (fcNaN)): | ||||
2372 | return cmpUnordered; | ||||
2373 | |||||
2374 | case PackCategoriesIntoKey(fcInfinity, fcNormal)((fcInfinity) * 4 + (fcNormal)): | ||||
2375 | case PackCategoriesIntoKey(fcInfinity, fcZero)((fcInfinity) * 4 + (fcZero)): | ||||
2376 | case PackCategoriesIntoKey(fcNormal, fcZero)((fcNormal) * 4 + (fcZero)): | ||||
2377 | if (sign) | ||||
2378 | return cmpLessThan; | ||||
2379 | else | ||||
2380 | return cmpGreaterThan; | ||||
2381 | |||||
2382 | case PackCategoriesIntoKey(fcNormal, fcInfinity)((fcNormal) * 4 + (fcInfinity)): | ||||
2383 | case PackCategoriesIntoKey(fcZero, fcInfinity)((fcZero) * 4 + (fcInfinity)): | ||||
2384 | case PackCategoriesIntoKey(fcZero, fcNormal)((fcZero) * 4 + (fcNormal)): | ||||
2385 | if (rhs.sign) | ||||
2386 | return cmpGreaterThan; | ||||
2387 | else | ||||
2388 | return cmpLessThan; | ||||
2389 | |||||
2390 | case PackCategoriesIntoKey(fcInfinity, fcInfinity)((fcInfinity) * 4 + (fcInfinity)): | ||||
2391 | if (sign == rhs.sign) | ||||
2392 | return cmpEqual; | ||||
2393 | else if (sign) | ||||
2394 | return cmpLessThan; | ||||
2395 | else | ||||
2396 | return cmpGreaterThan; | ||||
2397 | |||||
2398 | case PackCategoriesIntoKey(fcZero, fcZero)((fcZero) * 4 + (fcZero)): | ||||
2399 | return cmpEqual; | ||||
2400 | |||||
2401 | case PackCategoriesIntoKey(fcNormal, fcNormal)((fcNormal) * 4 + (fcNormal)): | ||||
2402 | break; | ||||
2403 | } | ||||
2404 | |||||
2405 | /* Two normal numbers. Do they have the same sign? */ | ||||
2406 | if (sign != rhs.sign) { | ||||
2407 | if (sign) | ||||
2408 | result = cmpLessThan; | ||||
2409 | else | ||||
2410 | result = cmpGreaterThan; | ||||
2411 | } else { | ||||
2412 | /* Compare absolute values; invert result if negative. */ | ||||
2413 | result = compareAbsoluteValue(rhs); | ||||
2414 | |||||
2415 | if (sign) { | ||||
2416 | if (result == cmpLessThan) | ||||
2417 | result = cmpGreaterThan; | ||||
2418 | else if (result == cmpGreaterThan) | ||||
2419 | result = cmpLessThan; | ||||
2420 | } | ||||
2421 | } | ||||
2422 | |||||
2423 | return result; | ||||
2424 | } | ||||
2425 | |||||
2426 | /// IEEEFloat::convert - convert a value of one floating point type to another. | ||||
2427 | /// The return value corresponds to the IEEE754 exceptions. *losesInfo | ||||
2428 | /// records whether the transformation lost information, i.e. whether | ||||
2429 | /// converting the result back to the original type will produce the | ||||
2430 | /// original value (this is almost the same as return value==fsOK, but there | ||||
2431 | /// are edge cases where this is not so). | ||||
2432 | |||||
2433 | IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics, | ||||
2434 | roundingMode rounding_mode, | ||||
2435 | bool *losesInfo) { | ||||
2436 | lostFraction lostFraction; | ||||
2437 | unsigned int newPartCount, oldPartCount; | ||||
2438 | opStatus fs; | ||||
2439 | int shift; | ||||
2440 | const fltSemantics &fromSemantics = *semantics; | ||||
2441 | bool is_signaling = isSignaling(); | ||||
2442 | |||||
2443 | lostFraction = lfExactlyZero; | ||||
2444 | newPartCount = partCountForBits(toSemantics.precision + 1); | ||||
2445 | oldPartCount = partCount(); | ||||
2446 | shift = toSemantics.precision - fromSemantics.precision; | ||||
2447 | |||||
2448 | bool X86SpecialNan = false; | ||||
2449 | if (&fromSemantics == &semX87DoubleExtended && | ||||
2450 | &toSemantics != &semX87DoubleExtended && category == fcNaN && | ||||
2451 | (!(*significandParts() & 0x8000000000000000ULL) || | ||||
2452 | !(*significandParts() & 0x4000000000000000ULL))) { | ||||
2453 | // x86 has some unusual NaNs which cannot be represented in any other | ||||
2454 | // format; note them here. | ||||
2455 | X86SpecialNan = true; | ||||
2456 | } | ||||
2457 | |||||
2458 | // If this is a truncation of a denormal number, and the target semantics | ||||
2459 | // has larger exponent range than the source semantics (this can happen | ||||
2460 | // when truncating from PowerPC double-double to double format), the | ||||
2461 | // right shift could lose result mantissa bits. Adjust exponent instead | ||||
2462 | // of performing excessive shift. | ||||
2463 | // Also do a similar trick in case shifting denormal would produce zero | ||||
2464 | // significand as this case isn't handled correctly by normalize. | ||||
2465 | if (shift < 0 && isFiniteNonZero()) { | ||||
2466 | int omsb = significandMSB() + 1; | ||||
2467 | int exponentChange = omsb - fromSemantics.precision; | ||||
2468 | if (exponent + exponentChange < toSemantics.minExponent) | ||||
2469 | exponentChange = toSemantics.minExponent - exponent; | ||||
2470 | if (exponentChange < shift) | ||||
2471 | exponentChange = shift; | ||||
2472 | if (exponentChange < 0) { | ||||
2473 | shift -= exponentChange; | ||||
2474 | exponent += exponentChange; | ||||
2475 | } else if (omsb <= -shift) { | ||||
2476 | exponentChange = omsb + shift - 1; // leave at least one bit set | ||||
2477 | shift -= exponentChange; | ||||
2478 | exponent += exponentChange; | ||||
2479 | } | ||||
2480 | } | ||||
2481 | |||||
2482 | // If this is a truncation, perform the shift before we narrow the storage. | ||||
2483 | if (shift
| ||||
2484 | (category == fcNaN && semantics->nonFiniteBehavior != | ||||
2485 | fltNonfiniteBehavior::NanOnly))) | ||||
2486 | lostFraction = shiftRight(significandParts(), oldPartCount, -shift); | ||||
2487 | |||||
2488 | // Fix the storage so it can hold to new value. | ||||
2489 | if (newPartCount > oldPartCount) { | ||||
2490 | // The new type requires more storage; make it available. | ||||
2491 | integerPart *newParts; | ||||
2492 | newParts = new integerPart[newPartCount]; | ||||
2493 | APInt::tcSet(newParts, 0, newPartCount); | ||||
2494 | if (isFiniteNonZero() || category==fcNaN) | ||||
2495 | APInt::tcAssign(newParts, significandParts(), oldPartCount); | ||||
2496 | freeSignificand(); | ||||
2497 | significand.parts = newParts; | ||||
2498 | } else if (newPartCount
| ||||
2499 | // Switch to built-in storage for a single part. | ||||
2500 | integerPart newPart = 0; | ||||
2501 | if (isFiniteNonZero() || category==fcNaN) | ||||
2502 | newPart = significandParts()[0]; | ||||
2503 | freeSignificand(); | ||||
2504 | significand.part = newPart; | ||||
2505 | } | ||||
2506 | |||||
2507 | // Now that we have the right storage, switch the semantics. | ||||
2508 | semantics = &toSemantics; | ||||
2509 | |||||
2510 | // If this is an extension, perform the shift now that the storage is | ||||
2511 | // available. | ||||
2512 | if (shift > 0 && (isFiniteNonZero() || category==fcNaN)) | ||||
2513 | APInt::tcShiftLeft(significandParts(), newPartCount, shift); | ||||
2514 | |||||
2515 | if (isFiniteNonZero()) { | ||||
| |||||
2516 | fs = normalize(rounding_mode, lostFraction); | ||||
2517 | *losesInfo = (fs != opOK); | ||||
2518 | } else if (category == fcNaN) { | ||||
2519 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) { | ||||
2520 | *losesInfo = | ||||
2521 | fromSemantics.nonFiniteBehavior != fltNonfiniteBehavior::NanOnly; | ||||
2522 | makeNaN(false, sign); | ||||
2523 | return is_signaling ? opInvalidOp : opOK; | ||||
2524 | } | ||||
2525 | |||||
2526 | // If NaN is negative zero, we need to create a new NaN to avoid converting | ||||
2527 | // NaN to -Inf. | ||||
2528 | if (fromSemantics.nanEncoding == fltNanEncoding::NegativeZero && | ||||
2529 | semantics->nanEncoding != fltNanEncoding::NegativeZero) | ||||
2530 | makeNaN(false, false); | ||||
2531 | |||||
2532 | *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan; | ||||
2533 | |||||
2534 | // For x87 extended precision, we want to make a NaN, not a special NaN if | ||||
2535 | // the input wasn't special either. | ||||
2536 | if (!X86SpecialNan && semantics == &semX87DoubleExtended) | ||||
2537 | APInt::tcSetBit(significandParts(), semantics->precision - 1); | ||||
2538 | |||||
2539 | // Convert of sNaN creates qNaN and raises an exception (invalid op). | ||||
2540 | // This also guarantees that a sNaN does not become Inf on a truncation | ||||
2541 | // that loses all payload bits. | ||||
2542 | if (is_signaling) { | ||||
2543 | makeQuiet(); | ||||
2544 | fs = opInvalidOp; | ||||
2545 | } else { | ||||
2546 | fs = opOK; | ||||
2547 | } | ||||
2548 | } else if (category == fcInfinity && | ||||
2549 | semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) { | ||||
2550 | makeNaN(false, sign); | ||||
2551 | *losesInfo = true; | ||||
2552 | fs = opInexact; | ||||
2553 | } else if (category == fcZero && | ||||
2554 | semantics->nanEncoding == fltNanEncoding::NegativeZero) { | ||||
2555 | // Negative zero loses info, but positive zero doesn't. | ||||
2556 | *losesInfo = | ||||
2557 | fromSemantics.nanEncoding != fltNanEncoding::NegativeZero && sign; | ||||
2558 | fs = *losesInfo ? opInexact : opOK; | ||||
2559 | // NaN is negative zero means -0 -> +0, which can lose information | ||||
2560 | sign = false; | ||||
2561 | } else { | ||||
2562 | *losesInfo = false; | ||||
2563 | fs = opOK; | ||||
2564 | } | ||||
2565 | |||||
2566 | return fs; | ||||
2567 | } | ||||
2568 | |||||
2569 | /* Convert a floating point number to an integer according to the | ||||
2570 | rounding mode. If the rounded integer value is out of range this | ||||
2571 | returns an invalid operation exception and the contents of the | ||||
2572 | destination parts are unspecified. If the rounded value is in | ||||
2573 | range but the floating point number is not the exact integer, the C | ||||
2574 | standard doesn't require an inexact exception to be raised. IEEE | ||||
2575 | 854 does require it so we do that. | ||||
2576 | |||||
2577 | Note that for conversions to integer type the C standard requires | ||||
2578 | round-to-zero to always be used. */ | ||||
2579 | IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger( | ||||
2580 | MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned, | ||||
2581 | roundingMode rounding_mode, bool *isExact) const { | ||||
2582 | lostFraction lost_fraction; | ||||
2583 | const integerPart *src; | ||||
2584 | unsigned int dstPartsCount, truncatedBits; | ||||
2585 | |||||
2586 | *isExact = false; | ||||
2587 | |||||
2588 | /* Handle the three special cases first. */ | ||||
2589 | if (category == fcInfinity || category == fcNaN) | ||||
2590 | return opInvalidOp; | ||||
2591 | |||||
2592 | dstPartsCount = partCountForBits(width); | ||||
2593 | assert(dstPartsCount <= parts.size() && "Integer too big")(static_cast <bool> (dstPartsCount <= parts.size() && "Integer too big") ? void (0) : __assert_fail ("dstPartsCount <= parts.size() && \"Integer too big\"" , "llvm/lib/Support/APFloat.cpp", 2593, __extension__ __PRETTY_FUNCTION__ )); | ||||
2594 | |||||
2595 | if (category == fcZero) { | ||||
2596 | APInt::tcSet(parts.data(), 0, dstPartsCount); | ||||
2597 | // Negative zero can't be represented as an int. | ||||
2598 | *isExact = !sign; | ||||
2599 | return opOK; | ||||
2600 | } | ||||
2601 | |||||
2602 | src = significandParts(); | ||||
2603 | |||||
2604 | /* Step 1: place our absolute value, with any fraction truncated, in | ||||
2605 | the destination. */ | ||||
2606 | if (exponent < 0) { | ||||
2607 | /* Our absolute value is less than one; truncate everything. */ | ||||
2608 | APInt::tcSet(parts.data(), 0, dstPartsCount); | ||||
2609 | /* For exponent -1 the integer bit represents .5, look at that. | ||||
2610 | For smaller exponents leftmost truncated bit is 0. */ | ||||
2611 | truncatedBits = semantics->precision -1U - exponent; | ||||
2612 | } else { | ||||
2613 | /* We want the most significant (exponent + 1) bits; the rest are | ||||
2614 | truncated. */ | ||||
2615 | unsigned int bits = exponent + 1U; | ||||
2616 | |||||
2617 | /* Hopelessly large in magnitude? */ | ||||
2618 | if (bits > width) | ||||
2619 | return opInvalidOp; | ||||
2620 | |||||
2621 | if (bits < semantics->precision) { | ||||
2622 | /* We truncate (semantics->precision - bits) bits. */ | ||||
2623 | truncatedBits = semantics->precision - bits; | ||||
2624 | APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits); | ||||
2625 | } else { | ||||
2626 | /* We want at least as many bits as are available. */ | ||||
2627 | APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision, | ||||
2628 | 0); | ||||
2629 | APInt::tcShiftLeft(parts.data(), dstPartsCount, | ||||
2630 | bits - semantics->precision); | ||||
2631 | truncatedBits = 0; | ||||
2632 | } | ||||
2633 | } | ||||
2634 | |||||
2635 | /* Step 2: work out any lost fraction, and increment the absolute | ||||
2636 | value if we would round away from zero. */ | ||||
2637 | if (truncatedBits) { | ||||
2638 | lost_fraction = lostFractionThroughTruncation(src, partCount(), | ||||
2639 | truncatedBits); | ||||
2640 | if (lost_fraction != lfExactlyZero && | ||||
2641 | roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) { | ||||
2642 | if (APInt::tcIncrement(parts.data(), dstPartsCount)) | ||||
2643 | return opInvalidOp; /* Overflow. */ | ||||
2644 | } | ||||
2645 | } else { | ||||
2646 | lost_fraction = lfExactlyZero; | ||||
2647 | } | ||||
2648 | |||||
2649 | /* Step 3: check if we fit in the destination. */ | ||||
2650 | unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1; | ||||
2651 | |||||
2652 | if (sign) { | ||||
2653 | if (!isSigned) { | ||||
2654 | /* Negative numbers cannot be represented as unsigned. */ | ||||
2655 | if (omsb != 0) | ||||
2656 | return opInvalidOp; | ||||
2657 | } else { | ||||
2658 | /* It takes omsb bits to represent the unsigned integer value. | ||||
2659 | We lose a bit for the sign, but care is needed as the | ||||
2660 | maximally negative integer is a special case. */ | ||||
2661 | if (omsb == width && | ||||
2662 | APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb) | ||||
2663 | return opInvalidOp; | ||||
2664 | |||||
2665 | /* This case can happen because of rounding. */ | ||||
2666 | if (omsb > width) | ||||
2667 | return opInvalidOp; | ||||
2668 | } | ||||
2669 | |||||
2670 | APInt::tcNegate (parts.data(), dstPartsCount); | ||||
2671 | } else { | ||||
2672 | if (omsb >= width + !isSigned) | ||||
2673 | return opInvalidOp; | ||||
2674 | } | ||||
2675 | |||||
2676 | if (lost_fraction == lfExactlyZero) { | ||||
2677 | *isExact = true; | ||||
2678 | return opOK; | ||||
2679 | } else | ||||
2680 | return opInexact; | ||||
2681 | } | ||||
2682 | |||||
2683 | /* Same as convertToSignExtendedInteger, except we provide | ||||
2684 | deterministic values in case of an invalid operation exception, | ||||
2685 | namely zero for NaNs and the minimal or maximal value respectively | ||||
2686 | for underflow or overflow. | ||||
2687 | The *isExact output tells whether the result is exact, in the sense | ||||
2688 | that converting it back to the original floating point type produces | ||||
2689 | the original value. This is almost equivalent to result==opOK, | ||||
2690 | except for negative zeroes. | ||||
2691 | */ | ||||
2692 | IEEEFloat::opStatus | ||||
2693 | IEEEFloat::convertToInteger(MutableArrayRef<integerPart> parts, | ||||
2694 | unsigned int width, bool isSigned, | ||||
2695 | roundingMode rounding_mode, bool *isExact) const { | ||||
2696 | opStatus fs; | ||||
2697 | |||||
2698 | fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode, | ||||
2699 | isExact); | ||||
2700 | |||||
2701 | if (fs == opInvalidOp) { | ||||
2702 | unsigned int bits, dstPartsCount; | ||||
2703 | |||||
2704 | dstPartsCount = partCountForBits(width); | ||||
2705 | assert(dstPartsCount <= parts.size() && "Integer too big")(static_cast <bool> (dstPartsCount <= parts.size() && "Integer too big") ? void (0) : __assert_fail ("dstPartsCount <= parts.size() && \"Integer too big\"" , "llvm/lib/Support/APFloat.cpp", 2705, __extension__ __PRETTY_FUNCTION__ )); | ||||
2706 | |||||
2707 | if (category == fcNaN) | ||||
2708 | bits = 0; | ||||
2709 | else if (sign) | ||||
2710 | bits = isSigned; | ||||
2711 | else | ||||
2712 | bits = width - isSigned; | ||||
2713 | |||||
2714 | tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits); | ||||
2715 | if (sign && isSigned) | ||||
2716 | APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1); | ||||
2717 | } | ||||
2718 | |||||
2719 | return fs; | ||||
2720 | } | ||||
2721 | |||||
2722 | /* Convert an unsigned integer SRC to a floating point number, | ||||
2723 | rounding according to ROUNDING_MODE. The sign of the floating | ||||
2724 | point number is not modified. */ | ||||
2725 | IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts( | ||||
2726 | const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) { | ||||
2727 | unsigned int omsb, precision, dstCount; | ||||
2728 | integerPart *dst; | ||||
2729 | lostFraction lost_fraction; | ||||
2730 | |||||
2731 | category = fcNormal; | ||||
2732 | omsb = APInt::tcMSB(src, srcCount) + 1; | ||||
2733 | dst = significandParts(); | ||||
2734 | dstCount = partCount(); | ||||
2735 | precision = semantics->precision; | ||||
2736 | |||||
2737 | /* We want the most significant PRECISION bits of SRC. There may not | ||||
2738 | be that many; extract what we can. */ | ||||
2739 | if (precision <= omsb) { | ||||
2740 | exponent = omsb - 1; | ||||
2741 | lost_fraction = lostFractionThroughTruncation(src, srcCount, | ||||
2742 | omsb - precision); | ||||
2743 | APInt::tcExtract(dst, dstCount, src, precision, omsb - precision); | ||||
2744 | } else { | ||||
2745 | exponent = precision - 1; | ||||
2746 | lost_fraction = lfExactlyZero; | ||||
2747 | APInt::tcExtract(dst, dstCount, src, omsb, 0); | ||||
2748 | } | ||||
2749 | |||||
2750 | return normalize(rounding_mode, lost_fraction); | ||||
2751 | } | ||||
2752 | |||||
2753 | IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned, | ||||
2754 | roundingMode rounding_mode) { | ||||
2755 | unsigned int partCount = Val.getNumWords(); | ||||
2756 | APInt api = Val; | ||||
2757 | |||||
2758 | sign = false; | ||||
2759 | if (isSigned && api.isNegative()) { | ||||
2760 | sign = true; | ||||
2761 | api = -api; | ||||
2762 | } | ||||
2763 | |||||
2764 | return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode); | ||||
2765 | } | ||||
2766 | |||||
2767 | /* Convert a two's complement integer SRC to a floating point number, | ||||
2768 | rounding according to ROUNDING_MODE. ISSIGNED is true if the | ||||
2769 | integer is signed, in which case it must be sign-extended. */ | ||||
2770 | IEEEFloat::opStatus | ||||
2771 | IEEEFloat::convertFromSignExtendedInteger(const integerPart *src, | ||||
2772 | unsigned int srcCount, bool isSigned, | ||||
2773 | roundingMode rounding_mode) { | ||||
2774 | opStatus status; | ||||
2775 | |||||
2776 | if (isSigned && | ||||
2777 | APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) { | ||||
2778 | integerPart *copy; | ||||
2779 | |||||
2780 | /* If we're signed and negative negate a copy. */ | ||||
2781 | sign = true; | ||||
2782 | copy = new integerPart[srcCount]; | ||||
2783 | APInt::tcAssign(copy, src, srcCount); | ||||
2784 | APInt::tcNegate(copy, srcCount); | ||||
2785 | status = convertFromUnsignedParts(copy, srcCount, rounding_mode); | ||||
2786 | delete [] copy; | ||||
2787 | } else { | ||||
2788 | sign = false; | ||||
2789 | status = convertFromUnsignedParts(src, srcCount, rounding_mode); | ||||
2790 | } | ||||
2791 | |||||
2792 | return status; | ||||
2793 | } | ||||
2794 | |||||
2795 | /* FIXME: should this just take a const APInt reference? */ | ||||
2796 | IEEEFloat::opStatus | ||||
2797 | IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts, | ||||
2798 | unsigned int width, bool isSigned, | ||||
2799 | roundingMode rounding_mode) { | ||||
2800 | unsigned int partCount = partCountForBits(width); | ||||
2801 | APInt api = APInt(width, ArrayRef(parts, partCount)); | ||||
2802 | |||||
2803 | sign = false; | ||||
2804 | if (isSigned && APInt::tcExtractBit(parts, width - 1)) { | ||||
2805 | sign = true; | ||||
2806 | api = -api; | ||||
2807 | } | ||||
2808 | |||||
2809 | return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode); | ||||
2810 | } | ||||
2811 | |||||
2812 | Expected<IEEEFloat::opStatus> | ||||
2813 | IEEEFloat::convertFromHexadecimalString(StringRef s, | ||||
2814 | roundingMode rounding_mode) { | ||||
2815 | lostFraction lost_fraction = lfExactlyZero; | ||||
2816 | |||||
2817 | category = fcNormal; | ||||
2818 | zeroSignificand(); | ||||
2819 | exponent = 0; | ||||
2820 | |||||
2821 | integerPart *significand = significandParts(); | ||||
2822 | unsigned partsCount = partCount(); | ||||
2823 | unsigned bitPos = partsCount * integerPartWidth; | ||||
2824 | bool computedTrailingFraction = false; | ||||
2825 | |||||
2826 | // Skip leading zeroes and any (hexa)decimal point. | ||||
2827 | StringRef::iterator begin = s.begin(); | ||||
2828 | StringRef::iterator end = s.end(); | ||||
2829 | StringRef::iterator dot; | ||||
2830 | auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot); | ||||
2831 | if (!PtrOrErr) | ||||
2832 | return PtrOrErr.takeError(); | ||||
2833 | StringRef::iterator p = *PtrOrErr; | ||||
2834 | StringRef::iterator firstSignificantDigit = p; | ||||
2835 | |||||
2836 | while (p != end) { | ||||
2837 | integerPart hex_value; | ||||
2838 | |||||
2839 | if (*p == '.') { | ||||
2840 | if (dot != end) | ||||
2841 | return createError("String contains multiple dots"); | ||||
2842 | dot = p++; | ||||
2843 | continue; | ||||
2844 | } | ||||
2845 | |||||
2846 | hex_value = hexDigitValue(*p); | ||||
2847 | if (hex_value == UINT_MAX(2147483647 *2U +1U)) | ||||
2848 | break; | ||||
2849 | |||||
2850 | p++; | ||||
2851 | |||||
2852 | // Store the number while we have space. | ||||
2853 | if (bitPos) { | ||||
2854 | bitPos -= 4; | ||||
2855 | hex_value <<= bitPos % integerPartWidth; | ||||
2856 | significand[bitPos / integerPartWidth] |= hex_value; | ||||
2857 | } else if (!computedTrailingFraction) { | ||||
2858 | auto FractOrErr = trailingHexadecimalFraction(p, end, hex_value); | ||||
2859 | if (!FractOrErr) | ||||
2860 | return FractOrErr.takeError(); | ||||
2861 | lost_fraction = *FractOrErr; | ||||
2862 | computedTrailingFraction = true; | ||||
2863 | } | ||||
2864 | } | ||||
2865 | |||||
2866 | /* Hex floats require an exponent but not a hexadecimal point. */ | ||||
2867 | if (p == end) | ||||
2868 | return createError("Hex strings require an exponent"); | ||||
2869 | if (*p != 'p' && *p != 'P') | ||||
2870 | return createError("Invalid character in significand"); | ||||
2871 | if (p == begin) | ||||
2872 | return createError("Significand has no digits"); | ||||
2873 | if (dot != end && p - begin == 1) | ||||
2874 | return createError("Significand has no digits"); | ||||
2875 | |||||
2876 | /* Ignore the exponent if we are zero. */ | ||||
2877 | if (p != firstSignificantDigit) { | ||||
2878 | int expAdjustment; | ||||
2879 | |||||
2880 | /* Implicit hexadecimal point? */ | ||||
2881 | if (dot == end) | ||||
2882 | dot = p; | ||||
2883 | |||||
2884 | /* Calculate the exponent adjustment implicit in the number of | ||||
2885 | significant digits. */ | ||||
2886 | expAdjustment = static_cast<int>(dot - firstSignificantDigit); | ||||
2887 | if (expAdjustment < 0) | ||||
2888 | expAdjustment++; | ||||
2889 | expAdjustment = expAdjustment * 4 - 1; | ||||
2890 | |||||
2891 | /* Adjust for writing the significand starting at the most | ||||
2892 | significant nibble. */ | ||||
2893 | expAdjustment += semantics->precision; | ||||
2894 | expAdjustment -= partsCount * integerPartWidth; | ||||
2895 | |||||
2896 | /* Adjust for the given exponent. */ | ||||
2897 | auto ExpOrErr = totalExponent(p + 1, end, expAdjustment); | ||||
2898 | if (!ExpOrErr) | ||||
2899 | return ExpOrErr.takeError(); | ||||
2900 | exponent = *ExpOrErr; | ||||
2901 | } | ||||
2902 | |||||
2903 | return normalize(rounding_mode, lost_fraction); | ||||
2904 | } | ||||
2905 | |||||
2906 | IEEEFloat::opStatus | ||||
2907 | IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts, | ||||
2908 | unsigned sigPartCount, int exp, | ||||
2909 | roundingMode rounding_mode) { | ||||
2910 | unsigned int parts, pow5PartCount; | ||||
2911 | fltSemantics calcSemantics = { 32767, -32767, 0, 0 }; | ||||
2912 | integerPart pow5Parts[maxPowerOfFiveParts]; | ||||
2913 | bool isNearest; | ||||
2914 | |||||
2915 | isNearest = (rounding_mode == rmNearestTiesToEven || | ||||
2916 | rounding_mode == rmNearestTiesToAway); | ||||
2917 | |||||
2918 | parts = partCountForBits(semantics->precision + 11); | ||||
2919 | |||||
2920 | /* Calculate pow(5, abs(exp)). */ | ||||
2921 | pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp); | ||||
2922 | |||||
2923 | for (;; parts *= 2) { | ||||
2924 | opStatus sigStatus, powStatus; | ||||
2925 | unsigned int excessPrecision, truncatedBits; | ||||
2926 | |||||
2927 | calcSemantics.precision = parts * integerPartWidth - 1; | ||||
2928 | excessPrecision = calcSemantics.precision - semantics->precision; | ||||
2929 | truncatedBits = excessPrecision; | ||||
2930 | |||||
2931 | IEEEFloat decSig(calcSemantics, uninitialized); | ||||
2932 | decSig.makeZero(sign); | ||||
2933 | IEEEFloat pow5(calcSemantics); | ||||
2934 | |||||
2935 | sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount, | ||||
2936 | rmNearestTiesToEven); | ||||
2937 | powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount, | ||||
2938 | rmNearestTiesToEven); | ||||
2939 | /* Add exp, as 10^n = 5^n * 2^n. */ | ||||
2940 | decSig.exponent += exp; | ||||
2941 | |||||
2942 | lostFraction calcLostFraction; | ||||
2943 | integerPart HUerr, HUdistance; | ||||
2944 | unsigned int powHUerr; | ||||
2945 | |||||
2946 | if (exp >= 0) { | ||||
2947 | /* multiplySignificand leaves the precision-th bit set to 1. */ | ||||
2948 | calcLostFraction = decSig.multiplySignificand(pow5); | ||||
2949 | powHUerr = powStatus != opOK; | ||||
2950 | } else { | ||||
2951 | calcLostFraction = decSig.divideSignificand(pow5); | ||||
2952 | /* Denormal numbers have less precision. */ | ||||
2953 | if (decSig.exponent < semantics->minExponent) { | ||||
2954 | excessPrecision += (semantics->minExponent - decSig.exponent); | ||||
2955 | truncatedBits = excessPrecision; | ||||
2956 | if (excessPrecision > calcSemantics.precision) | ||||
2957 | excessPrecision = calcSemantics.precision; | ||||
2958 | } | ||||
2959 | /* Extra half-ulp lost in reciprocal of exponent. */ | ||||
2960 | powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2; | ||||
2961 | } | ||||
2962 | |||||
2963 | /* Both multiplySignificand and divideSignificand return the | ||||
2964 | result with the integer bit set. */ | ||||
2965 | assert(APInt::tcExtractBit(static_cast <bool> (APInt::tcExtractBit (decSig.significandParts (), calcSemantics.precision - 1) == 1) ? void (0) : __assert_fail ("APInt::tcExtractBit (decSig.significandParts(), calcSemantics.precision - 1) == 1" , "llvm/lib/Support/APFloat.cpp", 2966, __extension__ __PRETTY_FUNCTION__ )) | ||||
2966 | (decSig.significandParts(), calcSemantics.precision - 1) == 1)(static_cast <bool> (APInt::tcExtractBit (decSig.significandParts (), calcSemantics.precision - 1) == 1) ? void (0) : __assert_fail ("APInt::tcExtractBit (decSig.significandParts(), calcSemantics.precision - 1) == 1" , "llvm/lib/Support/APFloat.cpp", 2966, __extension__ __PRETTY_FUNCTION__ )); | ||||
2967 | |||||
2968 | HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK, | ||||
2969 | powHUerr); | ||||
2970 | HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(), | ||||
2971 | excessPrecision, isNearest); | ||||
2972 | |||||
2973 | /* Are we guaranteed to round correctly if we truncate? */ | ||||
2974 | if (HUdistance >= HUerr) { | ||||
2975 | APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(), | ||||
2976 | calcSemantics.precision - excessPrecision, | ||||
2977 | excessPrecision); | ||||
2978 | /* Take the exponent of decSig. If we tcExtract-ed less bits | ||||
2979 | above we must adjust our exponent to compensate for the | ||||
2980 | implicit right shift. */ | ||||
2981 | exponent = (decSig.exponent + semantics->precision | ||||
2982 | - (calcSemantics.precision - excessPrecision)); | ||||
2983 | calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(), | ||||
2984 | decSig.partCount(), | ||||
2985 | truncatedBits); | ||||
2986 | return normalize(rounding_mode, calcLostFraction); | ||||
2987 | } | ||||
2988 | } | ||||
2989 | } | ||||
2990 | |||||
2991 | Expected<IEEEFloat::opStatus> | ||||
2992 | IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) { | ||||
2993 | decimalInfo D; | ||||
2994 | opStatus fs; | ||||
2995 | |||||
2996 | /* Scan the text. */ | ||||
2997 | StringRef::iterator p = str.begin(); | ||||
2998 | if (Error Err = interpretDecimal(p, str.end(), &D)) | ||||
2999 | return std::move(Err); | ||||
3000 | |||||
3001 | /* Handle the quick cases. First the case of no significant digits, | ||||
3002 | i.e. zero, and then exponents that are obviously too large or too | ||||
3003 | small. Writing L for log 10 / log 2, a number d.ddddd*10^exp | ||||
3004 | definitely overflows if | ||||
3005 | |||||
3006 | (exp - 1) * L >= maxExponent | ||||
3007 | |||||
3008 | and definitely underflows to zero where | ||||
3009 | |||||
3010 | (exp + 1) * L <= minExponent - precision | ||||
3011 | |||||
3012 | With integer arithmetic the tightest bounds for L are | ||||
3013 | |||||
3014 | 93/28 < L < 196/59 [ numerator <= 256 ] | ||||
3015 | 42039/12655 < L < 28738/8651 [ numerator <= 65536 ] | ||||
3016 | */ | ||||
3017 | |||||
3018 | // Test if we have a zero number allowing for strings with no null terminators | ||||
3019 | // and zero decimals with non-zero exponents. | ||||
3020 | // | ||||
3021 | // We computed firstSigDigit by ignoring all zeros and dots. Thus if | ||||
3022 | // D->firstSigDigit equals str.end(), every digit must be a zero and there can | ||||
3023 | // be at most one dot. On the other hand, if we have a zero with a non-zero | ||||
3024 | // exponent, then we know that D.firstSigDigit will be non-numeric. | ||||
3025 | if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) { | ||||
3026 | category = fcZero; | ||||
3027 | fs = opOK; | ||||
3028 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
3029 | sign = false; | ||||
3030 | |||||
3031 | /* Check whether the normalized exponent is high enough to overflow | ||||
3032 | max during the log-rebasing in the max-exponent check below. */ | ||||
3033 | } else if (D.normalizedExponent - 1 > INT_MAX2147483647 / 42039) { | ||||
3034 | fs = handleOverflow(rounding_mode); | ||||
3035 | |||||
3036 | /* If it wasn't, then it also wasn't high enough to overflow max | ||||
3037 | during the log-rebasing in the min-exponent check. Check that it | ||||
3038 | won't overflow min in either check, then perform the min-exponent | ||||
3039 | check. */ | ||||
3040 | } else if (D.normalizedExponent - 1 < INT_MIN(-2147483647 -1) / 42039 || | ||||
3041 | (D.normalizedExponent + 1) * 28738 <= | ||||
3042 | 8651 * (semantics->minExponent - (int) semantics->precision)) { | ||||
3043 | /* Underflow to zero and round. */ | ||||
3044 | category = fcNormal; | ||||
3045 | zeroSignificand(); | ||||
3046 | fs = normalize(rounding_mode, lfLessThanHalf); | ||||
3047 | |||||
3048 | /* We can finally safely perform the max-exponent check. */ | ||||
3049 | } else if ((D.normalizedExponent - 1) * 42039 | ||||
3050 | >= 12655 * semantics->maxExponent) { | ||||
3051 | /* Overflow and round. */ | ||||
3052 | fs = handleOverflow(rounding_mode); | ||||
3053 | } else { | ||||
3054 | integerPart *decSignificand; | ||||
3055 | unsigned int partCount; | ||||
3056 | |||||
3057 | /* A tight upper bound on number of bits required to hold an | ||||
3058 | N-digit decimal integer is N * 196 / 59. Allocate enough space | ||||
3059 | to hold the full significand, and an extra part required by | ||||
3060 | tcMultiplyPart. */ | ||||
3061 | partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1; | ||||
3062 | partCount = partCountForBits(1 + 196 * partCount / 59); | ||||
3063 | decSignificand = new integerPart[partCount + 1]; | ||||
3064 | partCount = 0; | ||||
3065 | |||||
3066 | /* Convert to binary efficiently - we do almost all multiplication | ||||
3067 | in an integerPart. When this would overflow do we do a single | ||||
3068 | bignum multiplication, and then revert again to multiplication | ||||
3069 | in an integerPart. */ | ||||
3070 | do { | ||||
3071 | integerPart decValue, val, multiplier; | ||||
3072 | |||||
3073 | val = 0; | ||||
3074 | multiplier = 1; | ||||
3075 | |||||
3076 | do { | ||||
3077 | if (*p == '.') { | ||||
3078 | p++; | ||||
3079 | if (p == str.end()) { | ||||
3080 | break; | ||||
3081 | } | ||||
3082 | } | ||||
3083 | decValue = decDigitValue(*p++); | ||||
3084 | if (decValue >= 10U) { | ||||
3085 | delete[] decSignificand; | ||||
3086 | return createError("Invalid character in significand"); | ||||
3087 | } | ||||
3088 | multiplier *= 10; | ||||
3089 | val = val * 10 + decValue; | ||||
3090 | /* The maximum number that can be multiplied by ten with any | ||||
3091 | digit added without overflowing an integerPart. */ | ||||
3092 | } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10); | ||||
3093 | |||||
3094 | /* Multiply out the current part. */ | ||||
3095 | APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val, | ||||
3096 | partCount, partCount + 1, false); | ||||
3097 | |||||
3098 | /* If we used another part (likely but not guaranteed), increase | ||||
3099 | the count. */ | ||||
3100 | if (decSignificand[partCount]) | ||||
3101 | partCount++; | ||||
3102 | } while (p <= D.lastSigDigit); | ||||
3103 | |||||
3104 | category = fcNormal; | ||||
3105 | fs = roundSignificandWithExponent(decSignificand, partCount, | ||||
3106 | D.exponent, rounding_mode); | ||||
3107 | |||||
3108 | delete [] decSignificand; | ||||
3109 | } | ||||
3110 | |||||
3111 | return fs; | ||||
3112 | } | ||||
3113 | |||||
3114 | bool IEEEFloat::convertFromStringSpecials(StringRef str) { | ||||
3115 | const size_t MIN_NAME_SIZE = 3; | ||||
3116 | |||||
3117 | if (str.size() < MIN_NAME_SIZE) | ||||
3118 | return false; | ||||
3119 | |||||
3120 | if (str.equals("inf") || str.equals("INFINITY") || str.equals("+Inf")) { | ||||
3121 | makeInf(false); | ||||
3122 | return true; | ||||
3123 | } | ||||
3124 | |||||
3125 | bool IsNegative = str.front() == '-'; | ||||
3126 | if (IsNegative) { | ||||
3127 | str = str.drop_front(); | ||||
3128 | if (str.size() < MIN_NAME_SIZE) | ||||
3129 | return false; | ||||
3130 | |||||
3131 | if (str.equals("inf") || str.equals("INFINITY") || str.equals("Inf")) { | ||||
3132 | makeInf(true); | ||||
3133 | return true; | ||||
3134 | } | ||||
3135 | } | ||||
3136 | |||||
3137 | // If we have a 's' (or 'S') prefix, then this is a Signaling NaN. | ||||
3138 | bool IsSignaling = str.front() == 's' || str.front() == 'S'; | ||||
3139 | if (IsSignaling) { | ||||
3140 | str = str.drop_front(); | ||||
3141 | if (str.size() < MIN_NAME_SIZE) | ||||
3142 | return false; | ||||
3143 | } | ||||
3144 | |||||
3145 | if (str.startswith("nan") || str.startswith("NaN")) { | ||||
3146 | str = str.drop_front(3); | ||||
3147 | |||||
3148 | // A NaN without payload. | ||||
3149 | if (str.empty()) { | ||||
3150 | makeNaN(IsSignaling, IsNegative); | ||||
3151 | return true; | ||||
3152 | } | ||||
3153 | |||||
3154 | // Allow the payload to be inside parentheses. | ||||
3155 | if (str.front() == '(') { | ||||
3156 | // Parentheses should be balanced (and not empty). | ||||
3157 | if (str.size() <= 2 || str.back() != ')') | ||||
3158 | return false; | ||||
3159 | |||||
3160 | str = str.slice(1, str.size() - 1); | ||||
3161 | } | ||||
3162 | |||||
3163 | // Determine the payload number's radix. | ||||
3164 | unsigned Radix = 10; | ||||
3165 | if (str[0] == '0') { | ||||
3166 | if (str.size() > 1 && tolower(str[1]) == 'x') { | ||||
3167 | str = str.drop_front(2); | ||||
3168 | Radix = 16; | ||||
3169 | } else | ||||
3170 | Radix = 8; | ||||
3171 | } | ||||
3172 | |||||
3173 | // Parse the payload and make the NaN. | ||||
3174 | APInt Payload; | ||||
3175 | if (!str.getAsInteger(Radix, Payload)) { | ||||
3176 | makeNaN(IsSignaling, IsNegative, &Payload); | ||||
3177 | return true; | ||||
3178 | } | ||||
3179 | } | ||||
3180 | |||||
3181 | return false; | ||||
3182 | } | ||||
3183 | |||||
3184 | Expected<IEEEFloat::opStatus> | ||||
3185 | IEEEFloat::convertFromString(StringRef str, roundingMode rounding_mode) { | ||||
3186 | if (str.empty()) | ||||
3187 | return createError("Invalid string length"); | ||||
3188 | |||||
3189 | // Handle special cases. | ||||
3190 | if (convertFromStringSpecials(str)) | ||||
3191 | return opOK; | ||||
3192 | |||||
3193 | /* Handle a leading minus sign. */ | ||||
3194 | StringRef::iterator p = str.begin(); | ||||
3195 | size_t slen = str.size(); | ||||
3196 | sign = *p == '-' ? 1 : 0; | ||||
3197 | if (*p == '-' || *p == '+') { | ||||
3198 | p++; | ||||
3199 | slen--; | ||||
3200 | if (!slen) | ||||
3201 | return createError("String has no digits"); | ||||
3202 | } | ||||
3203 | |||||
3204 | if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) { | ||||
3205 | if (slen == 2) | ||||
3206 | return createError("Invalid string"); | ||||
3207 | return convertFromHexadecimalString(StringRef(p + 2, slen - 2), | ||||
3208 | rounding_mode); | ||||
3209 | } | ||||
3210 | |||||
3211 | return convertFromDecimalString(StringRef(p, slen), rounding_mode); | ||||
3212 | } | ||||
3213 | |||||
3214 | /* Write out a hexadecimal representation of the floating point value | ||||
3215 | to DST, which must be of sufficient size, in the C99 form | ||||
3216 | [-]0xh.hhhhp[+-]d. Return the number of characters written, | ||||
3217 | excluding the terminating NUL. | ||||
3218 | |||||
3219 | If UPPERCASE, the output is in upper case, otherwise in lower case. | ||||
3220 | |||||
3221 | HEXDIGITS digits appear altogether, rounding the value if | ||||
3222 | necessary. If HEXDIGITS is 0, the minimal precision to display the | ||||
3223 | number precisely is used instead. If nothing would appear after | ||||
3224 | the decimal point it is suppressed. | ||||
3225 | |||||
3226 | The decimal exponent is always printed and has at least one digit. | ||||
3227 | Zero values display an exponent of zero. Infinities and NaNs | ||||
3228 | appear as "infinity" or "nan" respectively. | ||||
3229 | |||||
3230 | The above rules are as specified by C99. There is ambiguity about | ||||
3231 | what the leading hexadecimal digit should be. This implementation | ||||
3232 | uses whatever is necessary so that the exponent is displayed as | ||||
3233 | stored. This implies the exponent will fall within the IEEE format | ||||
3234 | range, and the leading hexadecimal digit will be 0 (for denormals), | ||||
3235 | 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with | ||||
3236 | any other digits zero). | ||||
3237 | */ | ||||
3238 | unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits, | ||||
3239 | bool upperCase, | ||||
3240 | roundingMode rounding_mode) const { | ||||
3241 | char *p; | ||||
3242 | |||||
3243 | p = dst; | ||||
3244 | if (sign) | ||||
3245 | *dst++ = '-'; | ||||
3246 | |||||
3247 | switch (category) { | ||||
3248 | case fcInfinity: | ||||
3249 | memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1); | ||||
3250 | dst += sizeof infinityL - 1; | ||||
3251 | break; | ||||
3252 | |||||
3253 | case fcNaN: | ||||
3254 | memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1); | ||||
3255 | dst += sizeof NaNU - 1; | ||||
3256 | break; | ||||
3257 | |||||
3258 | case fcZero: | ||||
3259 | *dst++ = '0'; | ||||
3260 | *dst++ = upperCase ? 'X': 'x'; | ||||
3261 | *dst++ = '0'; | ||||
3262 | if (hexDigits > 1) { | ||||
3263 | *dst++ = '.'; | ||||
3264 | memset (dst, '0', hexDigits - 1); | ||||
3265 | dst += hexDigits - 1; | ||||
3266 | } | ||||
3267 | *dst++ = upperCase ? 'P': 'p'; | ||||
3268 | *dst++ = '0'; | ||||
3269 | break; | ||||
3270 | |||||
3271 | case fcNormal: | ||||
3272 | dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode); | ||||
3273 | break; | ||||
3274 | } | ||||
3275 | |||||
3276 | *dst = 0; | ||||
3277 | |||||
3278 | return static_cast<unsigned int>(dst - p); | ||||
3279 | } | ||||
3280 | |||||
3281 | /* Does the hard work of outputting the correctly rounded hexadecimal | ||||
3282 | form of a normal floating point number with the specified number of | ||||
3283 | hexadecimal digits. If HEXDIGITS is zero the minimum number of | ||||
3284 | digits necessary to print the value precisely is output. */ | ||||
3285 | char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits, | ||||
3286 | bool upperCase, | ||||
3287 | roundingMode rounding_mode) const { | ||||
3288 | unsigned int count, valueBits, shift, partsCount, outputDigits; | ||||
3289 | const char *hexDigitChars; | ||||
3290 | const integerPart *significand; | ||||
3291 | char *p; | ||||
3292 | bool roundUp; | ||||
3293 | |||||
3294 | *dst++ = '0'; | ||||
3295 | *dst++ = upperCase ? 'X': 'x'; | ||||
3296 | |||||
3297 | roundUp = false; | ||||
3298 | hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower; | ||||
3299 | |||||
3300 | significand = significandParts(); | ||||
3301 | partsCount = partCount(); | ||||
3302 | |||||
3303 | /* +3 because the first digit only uses the single integer bit, so | ||||
3304 | we have 3 virtual zero most-significant-bits. */ | ||||
3305 | valueBits = semantics->precision + 3; | ||||
3306 | shift = integerPartWidth - valueBits % integerPartWidth; | ||||
3307 | |||||
3308 | /* The natural number of digits required ignoring trailing | ||||
3309 | insignificant zeroes. */ | ||||
3310 | outputDigits = (valueBits - significandLSB () + 3) / 4; | ||||
3311 | |||||
3312 | /* hexDigits of zero means use the required number for the | ||||
3313 | precision. Otherwise, see if we are truncating. If we are, | ||||
3314 | find out if we need to round away from zero. */ | ||||
3315 | if (hexDigits) { | ||||
3316 | if (hexDigits < outputDigits) { | ||||
3317 | /* We are dropping non-zero bits, so need to check how to round. | ||||
3318 | "bits" is the number of dropped bits. */ | ||||
3319 | unsigned int bits; | ||||
3320 | lostFraction fraction; | ||||
3321 | |||||
3322 | bits = valueBits - hexDigits * 4; | ||||
3323 | fraction = lostFractionThroughTruncation (significand, partsCount, bits); | ||||
3324 | roundUp = roundAwayFromZero(rounding_mode, fraction, bits); | ||||
3325 | } | ||||
3326 | outputDigits = hexDigits; | ||||
3327 | } | ||||
3328 | |||||
3329 | /* Write the digits consecutively, and start writing in the location | ||||
3330 | of the hexadecimal point. We move the most significant digit | ||||
3331 | left and add the hexadecimal point later. */ | ||||
3332 | p = ++dst; | ||||
3333 | |||||
3334 | count = (valueBits + integerPartWidth - 1) / integerPartWidth; | ||||
3335 | |||||
3336 | while (outputDigits && count) { | ||||
3337 | integerPart part; | ||||
3338 | |||||
3339 | /* Put the most significant integerPartWidth bits in "part". */ | ||||
3340 | if (--count == partsCount) | ||||
3341 | part = 0; /* An imaginary higher zero part. */ | ||||
3342 | else | ||||
3343 | part = significand[count] << shift; | ||||
3344 | |||||
3345 | if (count && shift) | ||||
3346 | part |= significand[count - 1] >> (integerPartWidth - shift); | ||||
3347 | |||||
3348 | /* Convert as much of "part" to hexdigits as we can. */ | ||||
3349 | unsigned int curDigits = integerPartWidth / 4; | ||||
3350 | |||||
3351 | if (curDigits > outputDigits) | ||||
3352 | curDigits = outputDigits; | ||||
3353 | dst += partAsHex (dst, part, curDigits, hexDigitChars); | ||||
3354 | outputDigits -= curDigits; | ||||
3355 | } | ||||
3356 | |||||
3357 | if (roundUp) { | ||||
3358 | char *q = dst; | ||||
3359 | |||||
3360 | /* Note that hexDigitChars has a trailing '0'. */ | ||||
3361 | do { | ||||
3362 | q--; | ||||
3363 | *q = hexDigitChars[hexDigitValue (*q) + 1]; | ||||
3364 | } while (*q == '0'); | ||||
3365 | assert(q >= p)(static_cast <bool> (q >= p) ? void (0) : __assert_fail ("q >= p", "llvm/lib/Support/APFloat.cpp", 3365, __extension__ __PRETTY_FUNCTION__)); | ||||
3366 | } else { | ||||
3367 | /* Add trailing zeroes. */ | ||||
3368 | memset (dst, '0', outputDigits); | ||||
3369 | dst += outputDigits; | ||||
3370 | } | ||||
3371 | |||||
3372 | /* Move the most significant digit to before the point, and if there | ||||
3373 | is something after the decimal point add it. This must come | ||||
3374 | after rounding above. */ | ||||
3375 | p[-1] = p[0]; | ||||
3376 | if (dst -1 == p) | ||||
3377 | dst--; | ||||
3378 | else | ||||
3379 | p[0] = '.'; | ||||
3380 | |||||
3381 | /* Finally output the exponent. */ | ||||
3382 | *dst++ = upperCase ? 'P': 'p'; | ||||
3383 | |||||
3384 | return writeSignedDecimal (dst, exponent); | ||||
3385 | } | ||||
3386 | |||||
3387 | hash_code hash_value(const IEEEFloat &Arg) { | ||||
3388 | if (!Arg.isFiniteNonZero()) | ||||
3389 | return hash_combine((uint8_t)Arg.category, | ||||
3390 | // NaN has no sign, fix it at zero. | ||||
3391 | Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign, | ||||
3392 | Arg.semantics->precision); | ||||
3393 | |||||
3394 | // Normal floats need their exponent and significand hashed. | ||||
3395 | return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign, | ||||
3396 | Arg.semantics->precision, Arg.exponent, | ||||
3397 | hash_combine_range( | ||||
3398 | Arg.significandParts(), | ||||
3399 | Arg.significandParts() + Arg.partCount())); | ||||
3400 | } | ||||
3401 | |||||
3402 | // Conversion from APFloat to/from host float/double. It may eventually be | ||||
3403 | // possible to eliminate these and have everybody deal with APFloats, but that | ||||
3404 | // will take a while. This approach will not easily extend to long double. | ||||
3405 | // Current implementation requires integerPartWidth==64, which is correct at | ||||
3406 | // the moment but could be made more general. | ||||
3407 | |||||
3408 | // Denormals have exponent minExponent in APFloat, but minExponent-1 in | ||||
3409 | // the actual IEEE respresentations. We compensate for that here. | ||||
3410 | |||||
3411 | APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const { | ||||
3412 | assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended)(static_cast <bool> (semantics == (const llvm::fltSemantics *)&semX87DoubleExtended) ? void (0) : __assert_fail ("semantics == (const llvm::fltSemantics*)&semX87DoubleExtended" , "llvm/lib/Support/APFloat.cpp", 3412, __extension__ __PRETTY_FUNCTION__ )); | ||||
3413 | assert(partCount()==2)(static_cast <bool> (partCount()==2) ? void (0) : __assert_fail ("partCount()==2", "llvm/lib/Support/APFloat.cpp", 3413, __extension__ __PRETTY_FUNCTION__)); | ||||
3414 | |||||
3415 | uint64_t myexponent, mysignificand; | ||||
3416 | |||||
3417 | if (isFiniteNonZero()) { | ||||
3418 | myexponent = exponent+16383; //bias | ||||
3419 | mysignificand = significandParts()[0]; | ||||
3420 | if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL)) | ||||
3421 | myexponent = 0; // denormal | ||||
3422 | } else if (category==fcZero) { | ||||
3423 | myexponent = 0; | ||||
3424 | mysignificand = 0; | ||||
3425 | } else if (category==fcInfinity) { | ||||
3426 | myexponent = 0x7fff; | ||||
3427 | mysignificand = 0x8000000000000000ULL; | ||||
3428 | } else { | ||||
3429 | assert(category == fcNaN && "Unknown category")(static_cast <bool> (category == fcNaN && "Unknown category" ) ? void (0) : __assert_fail ("category == fcNaN && \"Unknown category\"" , "llvm/lib/Support/APFloat.cpp", 3429, __extension__ __PRETTY_FUNCTION__ )); | ||||
3430 | myexponent = 0x7fff; | ||||
3431 | mysignificand = significandParts()[0]; | ||||
3432 | } | ||||
3433 | |||||
3434 | uint64_t words[2]; | ||||
3435 | words[0] = mysignificand; | ||||
3436 | words[1] = ((uint64_t)(sign & 1) << 15) | | ||||
3437 | (myexponent & 0x7fffLL); | ||||
3438 | return APInt(80, words); | ||||
3439 | } | ||||
3440 | |||||
3441 | APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const { | ||||
3442 | assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)(static_cast <bool> (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy) ? void (0) : __assert_fail ( "semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy" , "llvm/lib/Support/APFloat.cpp", 3442, __extension__ __PRETTY_FUNCTION__ )); | ||||
3443 | assert(partCount()==2)(static_cast <bool> (partCount()==2) ? void (0) : __assert_fail ("partCount()==2", "llvm/lib/Support/APFloat.cpp", 3443, __extension__ __PRETTY_FUNCTION__)); | ||||
3444 | |||||
3445 | uint64_t words[2]; | ||||
3446 | opStatus fs; | ||||
3447 | bool losesInfo; | ||||
3448 | |||||
3449 | // Convert number to double. To avoid spurious underflows, we re- | ||||
3450 | // normalize against the "double" minExponent first, and only *then* | ||||
3451 | // truncate the mantissa. The result of that second conversion | ||||
3452 | // may be inexact, but should never underflow. | ||||
3453 | // Declare fltSemantics before APFloat that uses it (and | ||||
3454 | // saves pointer to it) to ensure correct destruction order. | ||||
3455 | fltSemantics extendedSemantics = *semantics; | ||||
3456 | extendedSemantics.minExponent = semIEEEdouble.minExponent; | ||||
3457 | IEEEFloat extended(*this); | ||||
3458 | fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo); | ||||
3459 | assert(fs == opOK && !losesInfo)(static_cast <bool> (fs == opOK && !losesInfo) ? void (0) : __assert_fail ("fs == opOK && !losesInfo" , "llvm/lib/Support/APFloat.cpp", 3459, __extension__ __PRETTY_FUNCTION__ )); | ||||
3460 | (void)fs; | ||||
3461 | |||||
3462 | IEEEFloat u(extended); | ||||
3463 | fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo); | ||||
3464 | assert(fs == opOK || fs == opInexact)(static_cast <bool> (fs == opOK || fs == opInexact) ? void (0) : __assert_fail ("fs == opOK || fs == opInexact", "llvm/lib/Support/APFloat.cpp" , 3464, __extension__ __PRETTY_FUNCTION__)); | ||||
3465 | (void)fs; | ||||
3466 | words[0] = *u.convertDoubleAPFloatToAPInt().getRawData(); | ||||
3467 | |||||
3468 | // If conversion was exact or resulted in a special case, we're done; | ||||
3469 | // just set the second double to zero. Otherwise, re-convert back to | ||||
3470 | // the extended format and compute the difference. This now should | ||||
3471 | // convert exactly to double. | ||||
3472 | if (u.isFiniteNonZero() && losesInfo) { | ||||
3473 | fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo); | ||||
3474 | assert(fs == opOK && !losesInfo)(static_cast <bool> (fs == opOK && !losesInfo) ? void (0) : __assert_fail ("fs == opOK && !losesInfo" , "llvm/lib/Support/APFloat.cpp", 3474, __extension__ __PRETTY_FUNCTION__ )); | ||||
3475 | (void)fs; | ||||
3476 | |||||
3477 | IEEEFloat v(extended); | ||||
3478 | v.subtract(u, rmNearestTiesToEven); | ||||
3479 | fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo); | ||||
3480 | assert(fs == opOK && !losesInfo)(static_cast <bool> (fs == opOK && !losesInfo) ? void (0) : __assert_fail ("fs == opOK && !losesInfo" , "llvm/lib/Support/APFloat.cpp", 3480, __extension__ __PRETTY_FUNCTION__ )); | ||||
3481 | (void)fs; | ||||
3482 | words[1] = *v.convertDoubleAPFloatToAPInt().getRawData(); | ||||
3483 | } else { | ||||
3484 | words[1] = 0; | ||||
3485 | } | ||||
3486 | |||||
3487 | return APInt(128, words); | ||||
3488 | } | ||||
3489 | |||||
3490 | template <const fltSemantics &S> | ||||
3491 | APInt IEEEFloat::convertIEEEFloatToAPInt() const { | ||||
3492 | assert(semantics == &S)(static_cast <bool> (semantics == &S) ? void (0) : __assert_fail ("semantics == &S", "llvm/lib/Support/APFloat.cpp", 3492 , __extension__ __PRETTY_FUNCTION__)); | ||||
3493 | |||||
3494 | constexpr int bias = -(S.minExponent - 1); | ||||
3495 | constexpr unsigned int trailing_significand_bits = S.precision - 1; | ||||
3496 | constexpr int integer_bit_part = trailing_significand_bits / integerPartWidth; | ||||
3497 | constexpr integerPart integer_bit = | ||||
3498 | integerPart{1} << (trailing_significand_bits % integerPartWidth); | ||||
3499 | constexpr uint64_t significand_mask = integer_bit - 1; | ||||
3500 | constexpr unsigned int exponent_bits = | ||||
3501 | S.sizeInBits - 1 - trailing_significand_bits; | ||||
3502 | static_assert(exponent_bits < 64); | ||||
3503 | constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1; | ||||
3504 | |||||
3505 | uint64_t myexponent; | ||||
3506 | std::array<integerPart, partCountForBits(trailing_significand_bits)> | ||||
3507 | mysignificand; | ||||
3508 | |||||
3509 | if (isFiniteNonZero()) { | ||||
3510 | myexponent = exponent + bias; | ||||
3511 | std::copy_n(significandParts(), mysignificand.size(), | ||||
3512 | mysignificand.begin()); | ||||
3513 | if (myexponent == 1 && | ||||
3514 | !(significandParts()[integer_bit_part] & integer_bit)) | ||||
3515 | myexponent = 0; // denormal | ||||
3516 | } else if (category == fcZero) { | ||||
3517 | myexponent = ::exponentZero(S) + bias; | ||||
3518 | mysignificand.fill(0); | ||||
3519 | } else if (category == fcInfinity) { | ||||
3520 | if (S.nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) { | ||||
3521 | llvm_unreachable("semantics don't support inf!")::llvm::llvm_unreachable_internal("semantics don't support inf!" , "llvm/lib/Support/APFloat.cpp", 3521); | ||||
3522 | } | ||||
3523 | myexponent = ::exponentInf(S) + bias; | ||||
3524 | mysignificand.fill(0); | ||||
3525 | } else { | ||||
3526 | assert(category == fcNaN && "Unknown category!")(static_cast <bool> (category == fcNaN && "Unknown category!" ) ? void (0) : __assert_fail ("category == fcNaN && \"Unknown category!\"" , "llvm/lib/Support/APFloat.cpp", 3526, __extension__ __PRETTY_FUNCTION__ )); | ||||
3527 | myexponent = ::exponentNaN(S) + bias; | ||||
3528 | std::copy_n(significandParts(), mysignificand.size(), | ||||
3529 | mysignificand.begin()); | ||||
3530 | } | ||||
3531 | std::array<uint64_t, (S.sizeInBits + 63) / 64> words; | ||||
3532 | auto words_iter = | ||||
3533 | std::copy_n(mysignificand.begin(), mysignificand.size(), words.begin()); | ||||
3534 | if constexpr (significand_mask != 0) { | ||||
3535 | // Clear the integer bit. | ||||
3536 | words[mysignificand.size() - 1] &= significand_mask; | ||||
3537 | } | ||||
3538 | std::fill(words_iter, words.end(), uint64_t{0}); | ||||
3539 | constexpr size_t last_word = words.size() - 1; | ||||
3540 | uint64_t shifted_sign = static_cast<uint64_t>(sign & 1) | ||||
3541 | << ((S.sizeInBits - 1) % 64); | ||||
3542 | words[last_word] |= shifted_sign; | ||||
3543 | uint64_t shifted_exponent = (myexponent & exponent_mask) | ||||
3544 | << (trailing_significand_bits % 64); | ||||
3545 | words[last_word] |= shifted_exponent; | ||||
3546 | if constexpr (last_word == 0) { | ||||
3547 | return APInt(S.sizeInBits, words[0]); | ||||
3548 | } | ||||
3549 | return APInt(S.sizeInBits, words); | ||||
3550 | } | ||||
3551 | |||||
3552 | APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const { | ||||
3553 | assert(partCount() == 2)(static_cast <bool> (partCount() == 2) ? void (0) : __assert_fail ("partCount() == 2", "llvm/lib/Support/APFloat.cpp", 3553, __extension__ __PRETTY_FUNCTION__)); | ||||
3554 | return convertIEEEFloatToAPInt<semIEEEquad>(); | ||||
3555 | } | ||||
3556 | |||||
3557 | APInt IEEEFloat::convertDoubleAPFloatToAPInt() const { | ||||
3558 | assert(partCount()==1)(static_cast <bool> (partCount()==1) ? void (0) : __assert_fail ("partCount()==1", "llvm/lib/Support/APFloat.cpp", 3558, __extension__ __PRETTY_FUNCTION__)); | ||||
3559 | return convertIEEEFloatToAPInt<semIEEEdouble>(); | ||||
3560 | } | ||||
3561 | |||||
3562 | APInt IEEEFloat::convertFloatAPFloatToAPInt() const { | ||||
3563 | assert(partCount()==1)(static_cast <bool> (partCount()==1) ? void (0) : __assert_fail ("partCount()==1", "llvm/lib/Support/APFloat.cpp", 3563, __extension__ __PRETTY_FUNCTION__)); | ||||
3564 | return convertIEEEFloatToAPInt<semIEEEsingle>(); | ||||
3565 | } | ||||
3566 | |||||
3567 | APInt IEEEFloat::convertBFloatAPFloatToAPInt() const { | ||||
3568 | assert(partCount() == 1)(static_cast <bool> (partCount() == 1) ? void (0) : __assert_fail ("partCount() == 1", "llvm/lib/Support/APFloat.cpp", 3568, __extension__ __PRETTY_FUNCTION__)); | ||||
3569 | return convertIEEEFloatToAPInt<semBFloat>(); | ||||
3570 | } | ||||
3571 | |||||
3572 | APInt IEEEFloat::convertHalfAPFloatToAPInt() const { | ||||
3573 | assert(partCount()==1)(static_cast <bool> (partCount()==1) ? void (0) : __assert_fail ("partCount()==1", "llvm/lib/Support/APFloat.cpp", 3573, __extension__ __PRETTY_FUNCTION__)); | ||||
3574 | return convertIEEEFloatToAPInt<semIEEEhalf>(); | ||||
3575 | } | ||||
3576 | |||||
3577 | APInt IEEEFloat::convertFloat8E5M2APFloatToAPInt() const { | ||||
3578 | assert(partCount() == 1)(static_cast <bool> (partCount() == 1) ? void (0) : __assert_fail ("partCount() == 1", "llvm/lib/Support/APFloat.cpp", 3578, __extension__ __PRETTY_FUNCTION__)); | ||||
3579 | return convertIEEEFloatToAPInt<semFloat8E5M2>(); | ||||
3580 | } | ||||
3581 | |||||
3582 | APInt IEEEFloat::convertFloat8E5M2FNUZAPFloatToAPInt() const { | ||||
3583 | assert(partCount() == 1)(static_cast <bool> (partCount() == 1) ? void (0) : __assert_fail ("partCount() == 1", "llvm/lib/Support/APFloat.cpp", 3583, __extension__ __PRETTY_FUNCTION__)); | ||||
3584 | return convertIEEEFloatToAPInt<semFloat8E5M2FNUZ>(); | ||||
3585 | } | ||||
3586 | |||||
3587 | APInt IEEEFloat::convertFloat8E4M3FNAPFloatToAPInt() const { | ||||
3588 | assert(partCount() == 1)(static_cast <bool> (partCount() == 1) ? void (0) : __assert_fail ("partCount() == 1", "llvm/lib/Support/APFloat.cpp", 3588, __extension__ __PRETTY_FUNCTION__)); | ||||
3589 | return convertIEEEFloatToAPInt<semFloat8E4M3FN>(); | ||||
3590 | } | ||||
3591 | |||||
3592 | APInt IEEEFloat::convertFloat8E4M3FNUZAPFloatToAPInt() const { | ||||
3593 | assert(partCount() == 1)(static_cast <bool> (partCount() == 1) ? void (0) : __assert_fail ("partCount() == 1", "llvm/lib/Support/APFloat.cpp", 3593, __extension__ __PRETTY_FUNCTION__)); | ||||
3594 | return convertIEEEFloatToAPInt<semFloat8E4M3FNUZ>(); | ||||
3595 | } | ||||
3596 | |||||
3597 | APInt IEEEFloat::convertFloat8E4M3B11FNUZAPFloatToAPInt() const { | ||||
3598 | assert(partCount() == 1)(static_cast <bool> (partCount() == 1) ? void (0) : __assert_fail ("partCount() == 1", "llvm/lib/Support/APFloat.cpp", 3598, __extension__ __PRETTY_FUNCTION__)); | ||||
3599 | return convertIEEEFloatToAPInt<semFloat8E4M3B11FNUZ>(); | ||||
3600 | } | ||||
3601 | |||||
3602 | // This function creates an APInt that is just a bit map of the floating | ||||
3603 | // point constant as it would appear in memory. It is not a conversion, | ||||
3604 | // and treating the result as a normal integer is unlikely to be useful. | ||||
3605 | |||||
3606 | APInt IEEEFloat::bitcastToAPInt() const { | ||||
3607 | if (semantics == (const llvm::fltSemantics*)&semIEEEhalf) | ||||
3608 | return convertHalfAPFloatToAPInt(); | ||||
3609 | |||||
3610 | if (semantics == (const llvm::fltSemantics *)&semBFloat) | ||||
3611 | return convertBFloatAPFloatToAPInt(); | ||||
3612 | |||||
3613 | if (semantics == (const llvm::fltSemantics*)&semIEEEsingle) | ||||
3614 | return convertFloatAPFloatToAPInt(); | ||||
3615 | |||||
3616 | if (semantics == (const llvm::fltSemantics*)&semIEEEdouble) | ||||
3617 | return convertDoubleAPFloatToAPInt(); | ||||
3618 | |||||
3619 | if (semantics == (const llvm::fltSemantics*)&semIEEEquad) | ||||
3620 | return convertQuadrupleAPFloatToAPInt(); | ||||
3621 | |||||
3622 | if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy) | ||||
3623 | return convertPPCDoubleDoubleAPFloatToAPInt(); | ||||
3624 | |||||
3625 | if (semantics == (const llvm::fltSemantics *)&semFloat8E5M2) | ||||
3626 | return convertFloat8E5M2APFloatToAPInt(); | ||||
3627 | |||||
3628 | if (semantics == (const llvm::fltSemantics *)&semFloat8E5M2FNUZ) | ||||
3629 | return convertFloat8E5M2FNUZAPFloatToAPInt(); | ||||
3630 | |||||
3631 | if (semantics == (const llvm::fltSemantics *)&semFloat8E4M3FN) | ||||
3632 | return convertFloat8E4M3FNAPFloatToAPInt(); | ||||
3633 | |||||
3634 | if (semantics == (const llvm::fltSemantics *)&semFloat8E4M3FNUZ) | ||||
3635 | return convertFloat8E4M3FNUZAPFloatToAPInt(); | ||||
3636 | |||||
3637 | if (semantics == (const llvm::fltSemantics *)&semFloat8E4M3B11FNUZ) | ||||
3638 | return convertFloat8E4M3B11FNUZAPFloatToAPInt(); | ||||
3639 | |||||
3640 | assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&(static_cast <bool> (semantics == (const llvm::fltSemantics *)&semX87DoubleExtended && "unknown format!") ? void (0) : __assert_fail ("semantics == (const llvm::fltSemantics*)&semX87DoubleExtended && \"unknown format!\"" , "llvm/lib/Support/APFloat.cpp", 3641, __extension__ __PRETTY_FUNCTION__ )) | ||||
3641 | "unknown format!")(static_cast <bool> (semantics == (const llvm::fltSemantics *)&semX87DoubleExtended && "unknown format!") ? void (0) : __assert_fail ("semantics == (const llvm::fltSemantics*)&semX87DoubleExtended && \"unknown format!\"" , "llvm/lib/Support/APFloat.cpp", 3641, __extension__ __PRETTY_FUNCTION__ )); | ||||
3642 | return convertF80LongDoubleAPFloatToAPInt(); | ||||
3643 | } | ||||
3644 | |||||
3645 | float IEEEFloat::convertToFloat() const { | ||||
3646 | assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&(static_cast <bool> (semantics == (const llvm::fltSemantics *)&semIEEEsingle && "Float semantics are not IEEEsingle" ) ? void (0) : __assert_fail ("semantics == (const llvm::fltSemantics*)&semIEEEsingle && \"Float semantics are not IEEEsingle\"" , "llvm/lib/Support/APFloat.cpp", 3647, __extension__ __PRETTY_FUNCTION__ )) | ||||
3647 | "Float semantics are not IEEEsingle")(static_cast <bool> (semantics == (const llvm::fltSemantics *)&semIEEEsingle && "Float semantics are not IEEEsingle" ) ? void (0) : __assert_fail ("semantics == (const llvm::fltSemantics*)&semIEEEsingle && \"Float semantics are not IEEEsingle\"" , "llvm/lib/Support/APFloat.cpp", 3647, __extension__ __PRETTY_FUNCTION__ )); | ||||
3648 | APInt api = bitcastToAPInt(); | ||||
3649 | return api.bitsToFloat(); | ||||
3650 | } | ||||
3651 | |||||
3652 | double IEEEFloat::convertToDouble() const { | ||||
3653 | assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&(static_cast <bool> (semantics == (const llvm::fltSemantics *)&semIEEEdouble && "Float semantics are not IEEEdouble" ) ? void (0) : __assert_fail ("semantics == (const llvm::fltSemantics*)&semIEEEdouble && \"Float semantics are not IEEEdouble\"" , "llvm/lib/Support/APFloat.cpp", 3654, __extension__ __PRETTY_FUNCTION__ )) | ||||
3654 | "Float semantics are not IEEEdouble")(static_cast <bool> (semantics == (const llvm::fltSemantics *)&semIEEEdouble && "Float semantics are not IEEEdouble" ) ? void (0) : __assert_fail ("semantics == (const llvm::fltSemantics*)&semIEEEdouble && \"Float semantics are not IEEEdouble\"" , "llvm/lib/Support/APFloat.cpp", 3654, __extension__ __PRETTY_FUNCTION__ )); | ||||
3655 | APInt api = bitcastToAPInt(); | ||||
3656 | return api.bitsToDouble(); | ||||
3657 | } | ||||
3658 | |||||
3659 | /// Integer bit is explicit in this format. Intel hardware (387 and later) | ||||
3660 | /// does not support these bit patterns: | ||||
3661 | /// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity") | ||||
3662 | /// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN") | ||||
3663 | /// exponent!=0 nor all 1's, integer bit 0 ("unnormal") | ||||
3664 | /// exponent = 0, integer bit 1 ("pseudodenormal") | ||||
3665 | /// At the moment, the first three are treated as NaNs, the last one as Normal. | ||||
3666 | void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) { | ||||
3667 | uint64_t i1 = api.getRawData()[0]; | ||||
3668 | uint64_t i2 = api.getRawData()[1]; | ||||
3669 | uint64_t myexponent = (i2 & 0x7fff); | ||||
3670 | uint64_t mysignificand = i1; | ||||
3671 | uint8_t myintegerbit = mysignificand >> 63; | ||||
3672 | |||||
3673 | initialize(&semX87DoubleExtended); | ||||
3674 | assert(partCount()==2)(static_cast <bool> (partCount()==2) ? void (0) : __assert_fail ("partCount()==2", "llvm/lib/Support/APFloat.cpp", 3674, __extension__ __PRETTY_FUNCTION__)); | ||||
3675 | |||||
3676 | sign = static_cast<unsigned int>(i2>>15); | ||||
3677 | if (myexponent == 0 && mysignificand == 0) { | ||||
3678 | makeZero(sign); | ||||
3679 | } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) { | ||||
3680 | makeInf(sign); | ||||
3681 | } else if ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) || | ||||
3682 | (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) { | ||||
3683 | category = fcNaN; | ||||
3684 | exponent = exponentNaN(); | ||||
3685 | significandParts()[0] = mysignificand; | ||||
3686 | significandParts()[1] = 0; | ||||
3687 | } else { | ||||
3688 | category = fcNormal; | ||||
3689 | exponent = myexponent - 16383; | ||||
3690 | significandParts()[0] = mysignificand; | ||||
3691 | significandParts()[1] = 0; | ||||
3692 | if (myexponent==0) // denormal | ||||
3693 | exponent = -16382; | ||||
3694 | } | ||||
3695 | } | ||||
3696 | |||||
3697 | void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) { | ||||
3698 | uint64_t i1 = api.getRawData()[0]; | ||||
3699 | uint64_t i2 = api.getRawData()[1]; | ||||
3700 | opStatus fs; | ||||
3701 | bool losesInfo; | ||||
3702 | |||||
3703 | // Get the first double and convert to our format. | ||||
3704 | initFromDoubleAPInt(APInt(64, i1)); | ||||
3705 | fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo); | ||||
3706 | assert(fs == opOK && !losesInfo)(static_cast <bool> (fs == opOK && !losesInfo) ? void (0) : __assert_fail ("fs == opOK && !losesInfo" , "llvm/lib/Support/APFloat.cpp", 3706, __extension__ __PRETTY_FUNCTION__ )); | ||||
3707 | (void)fs; | ||||
3708 | |||||
3709 | // Unless we have a special case, add in second double. | ||||
3710 | if (isFiniteNonZero()) { | ||||
3711 | IEEEFloat v(semIEEEdouble, APInt(64, i2)); | ||||
3712 | fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo); | ||||
3713 | assert(fs == opOK && !losesInfo)(static_cast <bool> (fs == opOK && !losesInfo) ? void (0) : __assert_fail ("fs == opOK && !losesInfo" , "llvm/lib/Support/APFloat.cpp", 3713, __extension__ __PRETTY_FUNCTION__ )); | ||||
3714 | (void)fs; | ||||
3715 | |||||
3716 | add(v, rmNearestTiesToEven); | ||||
3717 | } | ||||
3718 | } | ||||
3719 | |||||
3720 | template <const fltSemantics &S> | ||||
3721 | void IEEEFloat::initFromIEEEAPInt(const APInt &api) { | ||||
3722 | assert(api.getBitWidth() == S.sizeInBits)(static_cast <bool> (api.getBitWidth() == S.sizeInBits) ? void (0) : __assert_fail ("api.getBitWidth() == S.sizeInBits" , "llvm/lib/Support/APFloat.cpp", 3722, __extension__ __PRETTY_FUNCTION__ )); | ||||
3723 | constexpr integerPart integer_bit = integerPart{1} | ||||
3724 | << ((S.precision - 1) % integerPartWidth); | ||||
3725 | constexpr uint64_t significand_mask = integer_bit - 1; | ||||
3726 | constexpr unsigned int trailing_significand_bits = S.precision - 1; | ||||
3727 | constexpr unsigned int stored_significand_parts = | ||||
3728 | partCountForBits(trailing_significand_bits); | ||||
3729 | constexpr unsigned int exponent_bits = | ||||
3730 | S.sizeInBits - 1 - trailing_significand_bits; | ||||
3731 | static_assert(exponent_bits < 64); | ||||
3732 | constexpr uint64_t exponent_mask = (uint64_t{1} << exponent_bits) - 1; | ||||
3733 | constexpr int bias = -(S.minExponent - 1); | ||||
3734 | |||||
3735 | // Copy the bits of the significand. We need to clear out the exponent and | ||||
3736 | // sign bit in the last word. | ||||
3737 | std::array<integerPart, stored_significand_parts> mysignificand; | ||||
3738 | std::copy_n(api.getRawData(), mysignificand.size(), mysignificand.begin()); | ||||
3739 | if constexpr (significand_mask != 0) { | ||||
3740 | mysignificand[mysignificand.size() - 1] &= significand_mask; | ||||
3741 | } | ||||
3742 | |||||
3743 | // We assume the last word holds the sign bit, the exponent, and potentially | ||||
3744 | // some of the trailing significand field. | ||||
3745 | uint64_t last_word = api.getRawData()[api.getNumWords() - 1]; | ||||
3746 | uint64_t myexponent = | ||||
3747 | (last_word >> (trailing_significand_bits % 64)) & exponent_mask; | ||||
3748 | |||||
3749 | initialize(&S); | ||||
3750 | assert(partCount() == mysignificand.size())(static_cast <bool> (partCount() == mysignificand.size( )) ? void (0) : __assert_fail ("partCount() == mysignificand.size()" , "llvm/lib/Support/APFloat.cpp", 3750, __extension__ __PRETTY_FUNCTION__ )); | ||||
3751 | |||||
3752 | sign = static_cast<unsigned int>(last_word >> ((S.sizeInBits - 1) % 64)); | ||||
3753 | |||||
3754 | bool all_zero_significand = | ||||
3755 | llvm::all_of(mysignificand, [](integerPart bits) { return bits == 0; }); | ||||
3756 | |||||
3757 | bool is_zero = myexponent == 0 && all_zero_significand; | ||||
3758 | |||||
3759 | if constexpr (S.nonFiniteBehavior == fltNonfiniteBehavior::IEEE754) { | ||||
3760 | if (myexponent - bias == ::exponentInf(S) && all_zero_significand) { | ||||
3761 | makeInf(sign); | ||||
3762 | return; | ||||
3763 | } | ||||
3764 | } | ||||
3765 | |||||
3766 | bool is_nan = false; | ||||
3767 | |||||
3768 | if constexpr (S.nanEncoding == fltNanEncoding::IEEE) { | ||||
3769 | is_nan = myexponent - bias == ::exponentNaN(S) && !all_zero_significand; | ||||
3770 | } else if constexpr (S.nanEncoding == fltNanEncoding::AllOnes) { | ||||
3771 | bool all_ones_significand = | ||||
3772 | std::all_of(mysignificand.begin(), mysignificand.end() - 1, | ||||
3773 | [](integerPart bits) { return bits == ~integerPart{0}; }) && | ||||
3774 | (!significand_mask || | ||||
3775 | mysignificand[mysignificand.size() - 1] == significand_mask); | ||||
3776 | is_nan = myexponent - bias == ::exponentNaN(S) && all_ones_significand; | ||||
3777 | } else if constexpr (S.nanEncoding == fltNanEncoding::NegativeZero) { | ||||
3778 | is_nan = is_zero && sign; | ||||
3779 | } | ||||
3780 | |||||
3781 | if (is_nan) { | ||||
3782 | category = fcNaN; | ||||
3783 | exponent = ::exponentNaN(S); | ||||
3784 | std::copy_n(mysignificand.begin(), mysignificand.size(), | ||||
3785 | significandParts()); | ||||
3786 | return; | ||||
3787 | } | ||||
3788 | |||||
3789 | if (is_zero) { | ||||
3790 | makeZero(sign); | ||||
3791 | return; | ||||
3792 | } | ||||
3793 | |||||
3794 | category = fcNormal; | ||||
3795 | exponent = myexponent - bias; | ||||
3796 | std::copy_n(mysignificand.begin(), mysignificand.size(), significandParts()); | ||||
3797 | if (myexponent == 0) // denormal | ||||
3798 | exponent = S.minExponent; | ||||
3799 | else | ||||
3800 | significandParts()[mysignificand.size()-1] |= integer_bit; // integer bit | ||||
3801 | } | ||||
3802 | |||||
3803 | void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) { | ||||
3804 | initFromIEEEAPInt<semIEEEquad>(api); | ||||
3805 | } | ||||
3806 | |||||
3807 | void IEEEFloat::initFromDoubleAPInt(const APInt &api) { | ||||
3808 | initFromIEEEAPInt<semIEEEdouble>(api); | ||||
3809 | } | ||||
3810 | |||||
3811 | void IEEEFloat::initFromFloatAPInt(const APInt &api) { | ||||
3812 | initFromIEEEAPInt<semIEEEsingle>(api); | ||||
3813 | } | ||||
3814 | |||||
3815 | void IEEEFloat::initFromBFloatAPInt(const APInt &api) { | ||||
3816 | initFromIEEEAPInt<semBFloat>(api); | ||||
3817 | } | ||||
3818 | |||||
3819 | void IEEEFloat::initFromHalfAPInt(const APInt &api) { | ||||
3820 | initFromIEEEAPInt<semIEEEhalf>(api); | ||||
3821 | } | ||||
3822 | |||||
3823 | void IEEEFloat::initFromFloat8E5M2APInt(const APInt &api) { | ||||
3824 | initFromIEEEAPInt<semFloat8E5M2>(api); | ||||
3825 | } | ||||
3826 | |||||
3827 | void IEEEFloat::initFromFloat8E5M2FNUZAPInt(const APInt &api) { | ||||
3828 | initFromIEEEAPInt<semFloat8E5M2FNUZ>(api); | ||||
3829 | } | ||||
3830 | |||||
3831 | void IEEEFloat::initFromFloat8E4M3FNAPInt(const APInt &api) { | ||||
3832 | initFromIEEEAPInt<semFloat8E4M3FN>(api); | ||||
3833 | } | ||||
3834 | |||||
3835 | void IEEEFloat::initFromFloat8E4M3FNUZAPInt(const APInt &api) { | ||||
3836 | initFromIEEEAPInt<semFloat8E4M3FNUZ>(api); | ||||
3837 | } | ||||
3838 | |||||
3839 | void IEEEFloat::initFromFloat8E4M3B11FNUZAPInt(const APInt &api) { | ||||
3840 | initFromIEEEAPInt<semFloat8E4M3B11FNUZ>(api); | ||||
3841 | } | ||||
3842 | |||||
3843 | /// Treat api as containing the bits of a floating point number. | ||||
3844 | void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) { | ||||
3845 | assert(api.getBitWidth() == Sem->sizeInBits)(static_cast <bool> (api.getBitWidth() == Sem->sizeInBits ) ? void (0) : __assert_fail ("api.getBitWidth() == Sem->sizeInBits" , "llvm/lib/Support/APFloat.cpp", 3845, __extension__ __PRETTY_FUNCTION__ )); | ||||
3846 | if (Sem == &semIEEEhalf) | ||||
3847 | return initFromHalfAPInt(api); | ||||
3848 | if (Sem == &semBFloat) | ||||
3849 | return initFromBFloatAPInt(api); | ||||
3850 | if (Sem == &semIEEEsingle) | ||||
3851 | return initFromFloatAPInt(api); | ||||
3852 | if (Sem == &semIEEEdouble) | ||||
3853 | return initFromDoubleAPInt(api); | ||||
3854 | if (Sem == &semX87DoubleExtended) | ||||
3855 | return initFromF80LongDoubleAPInt(api); | ||||
3856 | if (Sem == &semIEEEquad) | ||||
3857 | return initFromQuadrupleAPInt(api); | ||||
3858 | if (Sem == &semPPCDoubleDoubleLegacy) | ||||
3859 | return initFromPPCDoubleDoubleAPInt(api); | ||||
3860 | if (Sem == &semFloat8E5M2) | ||||
3861 | return initFromFloat8E5M2APInt(api); | ||||
3862 | if (Sem == &semFloat8E5M2FNUZ) | ||||
3863 | return initFromFloat8E5M2FNUZAPInt(api); | ||||
3864 | if (Sem == &semFloat8E4M3FN) | ||||
3865 | return initFromFloat8E4M3FNAPInt(api); | ||||
3866 | if (Sem == &semFloat8E4M3FNUZ) | ||||
3867 | return initFromFloat8E4M3FNUZAPInt(api); | ||||
3868 | if (Sem == &semFloat8E4M3B11FNUZ) | ||||
3869 | return initFromFloat8E4M3B11FNUZAPInt(api); | ||||
3870 | |||||
3871 | llvm_unreachable(nullptr)::llvm::llvm_unreachable_internal(nullptr, "llvm/lib/Support/APFloat.cpp" , 3871); | ||||
3872 | } | ||||
3873 | |||||
3874 | /// Make this number the largest magnitude normal number in the given | ||||
3875 | /// semantics. | ||||
3876 | void IEEEFloat::makeLargest(bool Negative) { | ||||
3877 | // We want (in interchange format): | ||||
3878 | // sign = {Negative} | ||||
3879 | // exponent = 1..10 | ||||
3880 | // significand = 1..1 | ||||
3881 | category = fcNormal; | ||||
3882 | sign = Negative; | ||||
3883 | exponent = semantics->maxExponent; | ||||
3884 | |||||
3885 | // Use memset to set all but the highest integerPart to all ones. | ||||
3886 | integerPart *significand = significandParts(); | ||||
3887 | unsigned PartCount = partCount(); | ||||
3888 | memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1)); | ||||
3889 | |||||
3890 | // Set the high integerPart especially setting all unused top bits for | ||||
3891 | // internal consistency. | ||||
3892 | const unsigned NumUnusedHighBits = | ||||
3893 | PartCount*integerPartWidth - semantics->precision; | ||||
3894 | significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth) | ||||
3895 | ? (~integerPart(0) >> NumUnusedHighBits) | ||||
3896 | : 0; | ||||
3897 | |||||
3898 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly && | ||||
3899 | semantics->nanEncoding == fltNanEncoding::AllOnes) | ||||
3900 | significand[0] &= ~integerPart(1); | ||||
3901 | } | ||||
3902 | |||||
3903 | /// Make this number the smallest magnitude denormal number in the given | ||||
3904 | /// semantics. | ||||
3905 | void IEEEFloat::makeSmallest(bool Negative) { | ||||
3906 | // We want (in interchange format): | ||||
3907 | // sign = {Negative} | ||||
3908 | // exponent = 0..0 | ||||
3909 | // significand = 0..01 | ||||
3910 | category = fcNormal; | ||||
3911 | sign = Negative; | ||||
3912 | exponent = semantics->minExponent; | ||||
3913 | APInt::tcSet(significandParts(), 1, partCount()); | ||||
3914 | } | ||||
3915 | |||||
3916 | void IEEEFloat::makeSmallestNormalized(bool Negative) { | ||||
3917 | // We want (in interchange format): | ||||
3918 | // sign = {Negative} | ||||
3919 | // exponent = 0..0 | ||||
3920 | // significand = 10..0 | ||||
3921 | |||||
3922 | category = fcNormal; | ||||
3923 | zeroSignificand(); | ||||
3924 | sign = Negative; | ||||
3925 | exponent = semantics->minExponent; | ||||
3926 | APInt::tcSetBit(significandParts(), semantics->precision - 1); | ||||
3927 | } | ||||
3928 | |||||
3929 | IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) { | ||||
3930 | initFromAPInt(&Sem, API); | ||||
3931 | } | ||||
3932 | |||||
3933 | IEEEFloat::IEEEFloat(float f) { | ||||
3934 | initFromAPInt(&semIEEEsingle, APInt::floatToBits(f)); | ||||
3935 | } | ||||
3936 | |||||
3937 | IEEEFloat::IEEEFloat(double d) { | ||||
3938 | initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d)); | ||||
3939 | } | ||||
3940 | |||||
3941 | namespace { | ||||
3942 | void append(SmallVectorImpl<char> &Buffer, StringRef Str) { | ||||
3943 | Buffer.append(Str.begin(), Str.end()); | ||||
3944 | } | ||||
3945 | |||||
3946 | /// Removes data from the given significand until it is no more | ||||
3947 | /// precise than is required for the desired precision. | ||||
3948 | void AdjustToPrecision(APInt &significand, | ||||
3949 | int &exp, unsigned FormatPrecision) { | ||||
3950 | unsigned bits = significand.getActiveBits(); | ||||
3951 | |||||
3952 | // 196/59 is a very slight overestimate of lg_2(10). | ||||
3953 | unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59; | ||||
3954 | |||||
3955 | if (bits <= bitsRequired) return; | ||||
3956 | |||||
3957 | unsigned tensRemovable = (bits - bitsRequired) * 59 / 196; | ||||
3958 | if (!tensRemovable) return; | ||||
3959 | |||||
3960 | exp += tensRemovable; | ||||
3961 | |||||
3962 | APInt divisor(significand.getBitWidth(), 1); | ||||
3963 | APInt powten(significand.getBitWidth(), 10); | ||||
3964 | while (true) { | ||||
3965 | if (tensRemovable & 1) | ||||
3966 | divisor *= powten; | ||||
3967 | tensRemovable >>= 1; | ||||
3968 | if (!tensRemovable) break; | ||||
3969 | powten *= powten; | ||||
3970 | } | ||||
3971 | |||||
3972 | significand = significand.udiv(divisor); | ||||
3973 | |||||
3974 | // Truncate the significand down to its active bit count. | ||||
3975 | significand = significand.trunc(significand.getActiveBits()); | ||||
3976 | } | ||||
3977 | |||||
3978 | |||||
3979 | void AdjustToPrecision(SmallVectorImpl<char> &buffer, | ||||
3980 | int &exp, unsigned FormatPrecision) { | ||||
3981 | unsigned N = buffer.size(); | ||||
3982 | if (N <= FormatPrecision) return; | ||||
3983 | |||||
3984 | // The most significant figures are the last ones in the buffer. | ||||
3985 | unsigned FirstSignificant = N - FormatPrecision; | ||||
3986 | |||||
3987 | // Round. | ||||
3988 | // FIXME: this probably shouldn't use 'round half up'. | ||||
3989 | |||||
3990 | // Rounding down is just a truncation, except we also want to drop | ||||
3991 | // trailing zeros from the new result. | ||||
3992 | if (buffer[FirstSignificant - 1] < '5') { | ||||
3993 | while (FirstSignificant < N && buffer[FirstSignificant] == '0') | ||||
3994 | FirstSignificant++; | ||||
3995 | |||||
3996 | exp += FirstSignificant; | ||||
3997 | buffer.erase(&buffer[0], &buffer[FirstSignificant]); | ||||
3998 | return; | ||||
3999 | } | ||||
4000 | |||||
4001 | // Rounding up requires a decimal add-with-carry. If we continue | ||||
4002 | // the carry, the newly-introduced zeros will just be truncated. | ||||
4003 | for (unsigned I = FirstSignificant; I != N; ++I) { | ||||
4004 | if (buffer[I] == '9') { | ||||
4005 | FirstSignificant++; | ||||
4006 | } else { | ||||
4007 | buffer[I]++; | ||||
4008 | break; | ||||
4009 | } | ||||
4010 | } | ||||
4011 | |||||
4012 | // If we carried through, we have exactly one digit of precision. | ||||
4013 | if (FirstSignificant == N) { | ||||
4014 | exp += FirstSignificant; | ||||
4015 | buffer.clear(); | ||||
4016 | buffer.push_back('1'); | ||||
4017 | return; | ||||
4018 | } | ||||
4019 | |||||
4020 | exp += FirstSignificant; | ||||
4021 | buffer.erase(&buffer[0], &buffer[FirstSignificant]); | ||||
4022 | } | ||||
4023 | } // namespace | ||||
4024 | |||||
4025 | void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision, | ||||
4026 | unsigned FormatMaxPadding, bool TruncateZero) const { | ||||
4027 | switch (category) { | ||||
4028 | case fcInfinity: | ||||
4029 | if (isNegative()) | ||||
4030 | return append(Str, "-Inf"); | ||||
4031 | else | ||||
4032 | return append(Str, "+Inf"); | ||||
4033 | |||||
4034 | case fcNaN: return append(Str, "NaN"); | ||||
4035 | |||||
4036 | case fcZero: | ||||
4037 | if (isNegative()) | ||||
4038 | Str.push_back('-'); | ||||
4039 | |||||
4040 | if (!FormatMaxPadding) { | ||||
4041 | if (TruncateZero) | ||||
4042 | append(Str, "0.0E+0"); | ||||
4043 | else { | ||||
4044 | append(Str, "0.0"); | ||||
4045 | if (FormatPrecision > 1) | ||||
4046 | Str.append(FormatPrecision - 1, '0'); | ||||
4047 | append(Str, "e+00"); | ||||
4048 | } | ||||
4049 | } else | ||||
4050 | Str.push_back('0'); | ||||
4051 | return; | ||||
4052 | |||||
4053 | case fcNormal: | ||||
4054 | break; | ||||
4055 | } | ||||
4056 | |||||
4057 | if (isNegative()) | ||||
4058 | Str.push_back('-'); | ||||
4059 | |||||
4060 | // Decompose the number into an APInt and an exponent. | ||||
4061 | int exp = exponent - ((int) semantics->precision - 1); | ||||
4062 | APInt significand( | ||||
4063 | semantics->precision, | ||||
4064 | ArrayRef(significandParts(), partCountForBits(semantics->precision))); | ||||
4065 | |||||
4066 | // Set FormatPrecision if zero. We want to do this before we | ||||
4067 | // truncate trailing zeros, as those are part of the precision. | ||||
4068 | if (!FormatPrecision) { | ||||
4069 | // We use enough digits so the number can be round-tripped back to an | ||||
4070 | // APFloat. The formula comes from "How to Print Floating-Point Numbers | ||||
4071 | // Accurately" by Steele and White. | ||||
4072 | // FIXME: Using a formula based purely on the precision is conservative; | ||||
4073 | // we can print fewer digits depending on the actual value being printed. | ||||
4074 | |||||
4075 | // FormatPrecision = 2 + floor(significandBits / lg_2(10)) | ||||
4076 | FormatPrecision = 2 + semantics->precision * 59 / 196; | ||||
4077 | } | ||||
4078 | |||||
4079 | // Ignore trailing binary zeros. | ||||
4080 | int trailingZeros = significand.countr_zero(); | ||||
4081 | exp += trailingZeros; | ||||
4082 | significand.lshrInPlace(trailingZeros); | ||||
4083 | |||||
4084 | // Change the exponent from 2^e to 10^e. | ||||
4085 | if (exp == 0) { | ||||
4086 | // Nothing to do. | ||||
4087 | } else if (exp > 0) { | ||||
4088 | // Just shift left. | ||||
4089 | significand = significand.zext(semantics->precision + exp); | ||||
4090 | significand <<= exp; | ||||
4091 | exp = 0; | ||||
4092 | } else { /* exp < 0 */ | ||||
4093 | int texp = -exp; | ||||
4094 | |||||
4095 | // We transform this using the identity: | ||||
4096 | // (N)(2^-e) == (N)(5^e)(10^-e) | ||||
4097 | // This means we have to multiply N (the significand) by 5^e. | ||||
4098 | // To avoid overflow, we have to operate on numbers large | ||||
4099 | // enough to store N * 5^e: | ||||
4100 | // log2(N * 5^e) == log2(N) + e * log2(5) | ||||
4101 | // <= semantics->precision + e * 137 / 59 | ||||
4102 | // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59) | ||||
4103 | |||||
4104 | unsigned precision = semantics->precision + (137 * texp + 136) / 59; | ||||
4105 | |||||
4106 | // Multiply significand by 5^e. | ||||
4107 | // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8) | ||||
4108 | significand = significand.zext(precision); | ||||
4109 | APInt five_to_the_i(precision, 5); | ||||
4110 | while (true) { | ||||
4111 | if (texp & 1) significand *= five_to_the_i; | ||||
4112 | |||||
4113 | texp >>= 1; | ||||
4114 | if (!texp) break; | ||||
4115 | five_to_the_i *= five_to_the_i; | ||||
4116 | } | ||||
4117 | } | ||||
4118 | |||||
4119 | AdjustToPrecision(significand, exp, FormatPrecision); | ||||
4120 | |||||
4121 | SmallVector<char, 256> buffer; | ||||
4122 | |||||
4123 | // Fill the buffer. | ||||
4124 | unsigned precision = significand.getBitWidth(); | ||||
4125 | if (precision < 4) { | ||||
4126 | // We need enough precision to store the value 10. | ||||
4127 | precision = 4; | ||||
4128 | significand = significand.zext(precision); | ||||
4129 | } | ||||
4130 | APInt ten(precision, 10); | ||||
4131 | APInt digit(precision, 0); | ||||
4132 | |||||
4133 | bool inTrail = true; | ||||
4134 | while (significand != 0) { | ||||
4135 | // digit <- significand % 10 | ||||
4136 | // significand <- significand / 10 | ||||
4137 | APInt::udivrem(significand, ten, significand, digit); | ||||
4138 | |||||
4139 | unsigned d = digit.getZExtValue(); | ||||
4140 | |||||
4141 | // Drop trailing zeros. | ||||
4142 | if (inTrail && !d) exp++; | ||||
4143 | else { | ||||
4144 | buffer.push_back((char) ('0' + d)); | ||||
4145 | inTrail = false; | ||||
4146 | } | ||||
4147 | } | ||||
4148 | |||||
4149 | assert(!buffer.empty() && "no characters in buffer!")(static_cast <bool> (!buffer.empty() && "no characters in buffer!" ) ? void (0) : __assert_fail ("!buffer.empty() && \"no characters in buffer!\"" , "llvm/lib/Support/APFloat.cpp", 4149, __extension__ __PRETTY_FUNCTION__ )); | ||||
4150 | |||||
4151 | // Drop down to FormatPrecision. | ||||
4152 | // TODO: don't do more precise calculations above than are required. | ||||
4153 | AdjustToPrecision(buffer, exp, FormatPrecision); | ||||
4154 | |||||
4155 | unsigned NDigits = buffer.size(); | ||||
4156 | |||||
4157 | // Check whether we should use scientific notation. | ||||
4158 | bool FormatScientific; | ||||
4159 | if (!FormatMaxPadding) | ||||
4160 | FormatScientific = true; | ||||
4161 | else { | ||||
4162 | if (exp >= 0) { | ||||
4163 | // 765e3 --> 765000 | ||||
4164 | // ^^^ | ||||
4165 | // But we shouldn't make the number look more precise than it is. | ||||
4166 | FormatScientific = ((unsigned) exp > FormatMaxPadding || | ||||
4167 | NDigits + (unsigned) exp > FormatPrecision); | ||||
4168 | } else { | ||||
4169 | // Power of the most significant digit. | ||||
4170 | int MSD = exp + (int) (NDigits - 1); | ||||
4171 | if (MSD >= 0) { | ||||
4172 | // 765e-2 == 7.65 | ||||
4173 | FormatScientific = false; | ||||
4174 | } else { | ||||
4175 | // 765e-5 == 0.00765 | ||||
4176 | // ^ ^^ | ||||
4177 | FormatScientific = ((unsigned) -MSD) > FormatMaxPadding; | ||||
4178 | } | ||||
4179 | } | ||||
4180 | } | ||||
4181 | |||||
4182 | // Scientific formatting is pretty straightforward. | ||||
4183 | if (FormatScientific) { | ||||
4184 | exp += (NDigits - 1); | ||||
4185 | |||||
4186 | Str.push_back(buffer[NDigits-1]); | ||||
4187 | Str.push_back('.'); | ||||
4188 | if (NDigits == 1 && TruncateZero) | ||||
4189 | Str.push_back('0'); | ||||
4190 | else | ||||
4191 | for (unsigned I = 1; I != NDigits; ++I) | ||||
4192 | Str.push_back(buffer[NDigits-1-I]); | ||||
4193 | // Fill with zeros up to FormatPrecision. | ||||
4194 | if (!TruncateZero && FormatPrecision > NDigits - 1) | ||||
4195 | Str.append(FormatPrecision - NDigits + 1, '0'); | ||||
4196 | // For !TruncateZero we use lower 'e'. | ||||
4197 | Str.push_back(TruncateZero ? 'E' : 'e'); | ||||
4198 | |||||
4199 | Str.push_back(exp >= 0 ? '+' : '-'); | ||||
4200 | if (exp < 0) exp = -exp; | ||||
4201 | SmallVector<char, 6> expbuf; | ||||
4202 | do { | ||||
4203 | expbuf.push_back((char) ('0' + (exp % 10))); | ||||
4204 | exp /= 10; | ||||
4205 | } while (exp); | ||||
4206 | // Exponent always at least two digits if we do not truncate zeros. | ||||
4207 | if (!TruncateZero && expbuf.size() < 2) | ||||
4208 | expbuf.push_back('0'); | ||||
4209 | for (unsigned I = 0, E = expbuf.size(); I != E; ++I) | ||||
4210 | Str.push_back(expbuf[E-1-I]); | ||||
4211 | return; | ||||
4212 | } | ||||
4213 | |||||
4214 | // Non-scientific, positive exponents. | ||||
4215 | if (exp >= 0) { | ||||
4216 | for (unsigned I = 0; I != NDigits; ++I) | ||||
4217 | Str.push_back(buffer[NDigits-1-I]); | ||||
4218 | for (unsigned I = 0; I != (unsigned) exp; ++I) | ||||
4219 | Str.push_back('0'); | ||||
4220 | return; | ||||
4221 | } | ||||
4222 | |||||
4223 | // Non-scientific, negative exponents. | ||||
4224 | |||||
4225 | // The number of digits to the left of the decimal point. | ||||
4226 | int NWholeDigits = exp + (int) NDigits; | ||||
4227 | |||||
4228 | unsigned I = 0; | ||||
4229 | if (NWholeDigits > 0) { | ||||
4230 | for (; I != (unsigned) NWholeDigits; ++I) | ||||
4231 | Str.push_back(buffer[NDigits-I-1]); | ||||
4232 | Str.push_back('.'); | ||||
4233 | } else { | ||||
4234 | unsigned NZeros = 1 + (unsigned) -NWholeDigits; | ||||
4235 | |||||
4236 | Str.push_back('0'); | ||||
4237 | Str.push_back('.'); | ||||
4238 | for (unsigned Z = 1; Z != NZeros; ++Z) | ||||
4239 | Str.push_back('0'); | ||||
4240 | } | ||||
4241 | |||||
4242 | for (; I != NDigits; ++I) | ||||
4243 | Str.push_back(buffer[NDigits-I-1]); | ||||
4244 | } | ||||
4245 | |||||
4246 | bool IEEEFloat::getExactInverse(APFloat *inv) const { | ||||
4247 | // Special floats and denormals have no exact inverse. | ||||
4248 | if (!isFiniteNonZero()) | ||||
4249 | return false; | ||||
4250 | |||||
4251 | // Check that the number is a power of two by making sure that only the | ||||
4252 | // integer bit is set in the significand. | ||||
4253 | if (significandLSB() != semantics->precision - 1) | ||||
4254 | return false; | ||||
4255 | |||||
4256 | // Get the inverse. | ||||
4257 | IEEEFloat reciprocal(*semantics, 1ULL); | ||||
4258 | if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK) | ||||
4259 | return false; | ||||
4260 | |||||
4261 | // Avoid multiplication with a denormal, it is not safe on all platforms and | ||||
4262 | // may be slower than a normal division. | ||||
4263 | if (reciprocal.isDenormal()) | ||||
4264 | return false; | ||||
4265 | |||||
4266 | assert(reciprocal.isFiniteNonZero() &&(static_cast <bool> (reciprocal.isFiniteNonZero() && reciprocal.significandLSB() == reciprocal.semantics->precision - 1) ? void (0) : __assert_fail ("reciprocal.isFiniteNonZero() && reciprocal.significandLSB() == reciprocal.semantics->precision - 1" , "llvm/lib/Support/APFloat.cpp", 4267, __extension__ __PRETTY_FUNCTION__ )) | ||||
4267 | reciprocal.significandLSB() == reciprocal.semantics->precision - 1)(static_cast <bool> (reciprocal.isFiniteNonZero() && reciprocal.significandLSB() == reciprocal.semantics->precision - 1) ? void (0) : __assert_fail ("reciprocal.isFiniteNonZero() && reciprocal.significandLSB() == reciprocal.semantics->precision - 1" , "llvm/lib/Support/APFloat.cpp", 4267, __extension__ __PRETTY_FUNCTION__ )); | ||||
4268 | |||||
4269 | if (inv) | ||||
4270 | *inv = APFloat(reciprocal, *semantics); | ||||
4271 | |||||
4272 | return true; | ||||
4273 | } | ||||
4274 | |||||
4275 | bool IEEEFloat::isSignaling() const { | ||||
4276 | if (!isNaN()) | ||||
4277 | return false; | ||||
4278 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) | ||||
4279 | return false; | ||||
4280 | |||||
4281 | // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the | ||||
4282 | // first bit of the trailing significand being 0. | ||||
4283 | return !APInt::tcExtractBit(significandParts(), semantics->precision - 2); | ||||
4284 | } | ||||
4285 | |||||
4286 | /// IEEE-754R 2008 5.3.1: nextUp/nextDown. | ||||
4287 | /// | ||||
4288 | /// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with | ||||
4289 | /// appropriate sign switching before/after the computation. | ||||
4290 | IEEEFloat::opStatus IEEEFloat::next(bool nextDown) { | ||||
4291 | // If we are performing nextDown, swap sign so we have -x. | ||||
4292 | if (nextDown) | ||||
4293 | changeSign(); | ||||
4294 | |||||
4295 | // Compute nextUp(x) | ||||
4296 | opStatus result = opOK; | ||||
4297 | |||||
4298 | // Handle each float category separately. | ||||
4299 | switch (category) { | ||||
4300 | case fcInfinity: | ||||
4301 | // nextUp(+inf) = +inf | ||||
4302 | if (!isNegative()) | ||||
4303 | break; | ||||
4304 | // nextUp(-inf) = -getLargest() | ||||
4305 | makeLargest(true); | ||||
4306 | break; | ||||
4307 | case fcNaN: | ||||
4308 | // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag. | ||||
4309 | // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not | ||||
4310 | // change the payload. | ||||
4311 | if (isSignaling()) { | ||||
4312 | result = opInvalidOp; | ||||
4313 | // For consistency, propagate the sign of the sNaN to the qNaN. | ||||
4314 | makeNaN(false, isNegative(), nullptr); | ||||
4315 | } | ||||
4316 | break; | ||||
4317 | case fcZero: | ||||
4318 | // nextUp(pm 0) = +getSmallest() | ||||
4319 | makeSmallest(false); | ||||
4320 | break; | ||||
4321 | case fcNormal: | ||||
4322 | // nextUp(-getSmallest()) = -0 | ||||
4323 | if (isSmallest() && isNegative()) { | ||||
4324 | APInt::tcSet(significandParts(), 0, partCount()); | ||||
4325 | category = fcZero; | ||||
4326 | exponent = 0; | ||||
4327 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) | ||||
4328 | sign = false; | ||||
4329 | break; | ||||
4330 | } | ||||
4331 | |||||
4332 | if (isLargest() && !isNegative()) { | ||||
4333 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) { | ||||
4334 | // nextUp(getLargest()) == NAN | ||||
4335 | makeNaN(); | ||||
4336 | break; | ||||
4337 | } else { | ||||
4338 | // nextUp(getLargest()) == INFINITY | ||||
4339 | APInt::tcSet(significandParts(), 0, partCount()); | ||||
4340 | category = fcInfinity; | ||||
4341 | exponent = semantics->maxExponent + 1; | ||||
4342 | break; | ||||
4343 | } | ||||
4344 | } | ||||
4345 | |||||
4346 | // nextUp(normal) == normal + inc. | ||||
4347 | if (isNegative()) { | ||||
4348 | // If we are negative, we need to decrement the significand. | ||||
4349 | |||||
4350 | // We only cross a binade boundary that requires adjusting the exponent | ||||
4351 | // if: | ||||
4352 | // 1. exponent != semantics->minExponent. This implies we are not in the | ||||
4353 | // smallest binade or are dealing with denormals. | ||||
4354 | // 2. Our significand excluding the integral bit is all zeros. | ||||
4355 | bool WillCrossBinadeBoundary = | ||||
4356 | exponent != semantics->minExponent && isSignificandAllZeros(); | ||||
4357 | |||||
4358 | // Decrement the significand. | ||||
4359 | // | ||||
4360 | // We always do this since: | ||||
4361 | // 1. If we are dealing with a non-binade decrement, by definition we | ||||
4362 | // just decrement the significand. | ||||
4363 | // 2. If we are dealing with a normal -> normal binade decrement, since | ||||
4364 | // we have an explicit integral bit the fact that all bits but the | ||||
4365 | // integral bit are zero implies that subtracting one will yield a | ||||
4366 | // significand with 0 integral bit and 1 in all other spots. Thus we | ||||
4367 | // must just adjust the exponent and set the integral bit to 1. | ||||
4368 | // 3. If we are dealing with a normal -> denormal binade decrement, | ||||
4369 | // since we set the integral bit to 0 when we represent denormals, we | ||||
4370 | // just decrement the significand. | ||||
4371 | integerPart *Parts = significandParts(); | ||||
4372 | APInt::tcDecrement(Parts, partCount()); | ||||
4373 | |||||
4374 | if (WillCrossBinadeBoundary) { | ||||
4375 | // Our result is a normal number. Do the following: | ||||
4376 | // 1. Set the integral bit to 1. | ||||
4377 | // 2. Decrement the exponent. | ||||
4378 | APInt::tcSetBit(Parts, semantics->precision - 1); | ||||
4379 | exponent--; | ||||
4380 | } | ||||
4381 | } else { | ||||
4382 | // If we are positive, we need to increment the significand. | ||||
4383 | |||||
4384 | // We only cross a binade boundary that requires adjusting the exponent if | ||||
4385 | // the input is not a denormal and all of said input's significand bits | ||||
4386 | // are set. If all of said conditions are true: clear the significand, set | ||||
4387 | // the integral bit to 1, and increment the exponent. If we have a | ||||
4388 | // denormal always increment since moving denormals and the numbers in the | ||||
4389 | // smallest normal binade have the same exponent in our representation. | ||||
4390 | bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes(); | ||||
4391 | |||||
4392 | if (WillCrossBinadeBoundary) { | ||||
4393 | integerPart *Parts = significandParts(); | ||||
4394 | APInt::tcSet(Parts, 0, partCount()); | ||||
4395 | APInt::tcSetBit(Parts, semantics->precision - 1); | ||||
4396 | assert(exponent != semantics->maxExponent &&(static_cast <bool> (exponent != semantics->maxExponent && "We can not increment an exponent beyond the maxExponent allowed" " by the given floating point semantics.") ? void (0) : __assert_fail ("exponent != semantics->maxExponent && \"We can not increment an exponent beyond the maxExponent allowed\" \" by the given floating point semantics.\"" , "llvm/lib/Support/APFloat.cpp", 4398, __extension__ __PRETTY_FUNCTION__ )) | ||||
4397 | "We can not increment an exponent beyond the maxExponent allowed"(static_cast <bool> (exponent != semantics->maxExponent && "We can not increment an exponent beyond the maxExponent allowed" " by the given floating point semantics.") ? void (0) : __assert_fail ("exponent != semantics->maxExponent && \"We can not increment an exponent beyond the maxExponent allowed\" \" by the given floating point semantics.\"" , "llvm/lib/Support/APFloat.cpp", 4398, __extension__ __PRETTY_FUNCTION__ )) | ||||
4398 | " by the given floating point semantics.")(static_cast <bool> (exponent != semantics->maxExponent && "We can not increment an exponent beyond the maxExponent allowed" " by the given floating point semantics.") ? void (0) : __assert_fail ("exponent != semantics->maxExponent && \"We can not increment an exponent beyond the maxExponent allowed\" \" by the given floating point semantics.\"" , "llvm/lib/Support/APFloat.cpp", 4398, __extension__ __PRETTY_FUNCTION__ )); | ||||
4399 | exponent++; | ||||
4400 | } else { | ||||
4401 | incrementSignificand(); | ||||
4402 | } | ||||
4403 | } | ||||
4404 | break; | ||||
4405 | } | ||||
4406 | |||||
4407 | // If we are performing nextDown, swap sign so we have -nextUp(-x) | ||||
4408 | if (nextDown) | ||||
4409 | changeSign(); | ||||
4410 | |||||
4411 | return result; | ||||
4412 | } | ||||
4413 | |||||
4414 | APFloatBase::ExponentType IEEEFloat::exponentNaN() const { | ||||
4415 | return ::exponentNaN(*semantics); | ||||
4416 | } | ||||
4417 | |||||
4418 | APFloatBase::ExponentType IEEEFloat::exponentInf() const { | ||||
4419 | return ::exponentInf(*semantics); | ||||
4420 | } | ||||
4421 | |||||
4422 | APFloatBase::ExponentType IEEEFloat::exponentZero() const { | ||||
4423 | return ::exponentZero(*semantics); | ||||
4424 | } | ||||
4425 | |||||
4426 | void IEEEFloat::makeInf(bool Negative) { | ||||
4427 | if (semantics->nonFiniteBehavior == fltNonfiniteBehavior::NanOnly) { | ||||
4428 | // There is no Inf, so make NaN instead. | ||||
4429 | makeNaN(false, Negative); | ||||
4430 | return; | ||||
4431 | } | ||||
4432 | category = fcInfinity; | ||||
4433 | sign = Negative; | ||||
4434 | exponent = exponentInf(); | ||||
4435 | APInt::tcSet(significandParts(), 0, partCount()); | ||||
4436 | } | ||||
4437 | |||||
4438 | void IEEEFloat::makeZero(bool Negative) { | ||||
4439 | category = fcZero; | ||||
4440 | sign = Negative; | ||||
4441 | if (semantics->nanEncoding == fltNanEncoding::NegativeZero) { | ||||
4442 | // Merge negative zero to positive because 0b10000...000 is used for NaN | ||||
4443 | sign = false; | ||||
4444 | } | ||||
4445 | exponent = exponentZero(); | ||||
4446 | APInt::tcSet(significandParts(), 0, partCount()); | ||||
4447 | } | ||||
4448 | |||||
4449 | void IEEEFloat::makeQuiet() { | ||||
4450 | assert(isNaN())(static_cast <bool> (isNaN()) ? void (0) : __assert_fail ("isNaN()", "llvm/lib/Support/APFloat.cpp", 4450, __extension__ __PRETTY_FUNCTION__)); | ||||
4451 | if (semantics->nonFiniteBehavior != fltNonfiniteBehavior::NanOnly) | ||||
4452 | APInt::tcSetBit(significandParts(), semantics->precision - 2); | ||||
4453 | } | ||||
4454 | |||||
4455 | int ilogb(const IEEEFloat &Arg) { | ||||
4456 | if (Arg.isNaN()) | ||||
4457 | return IEEEFloat::IEK_NaN; | ||||
4458 | if (Arg.isZero()) | ||||
4459 | return IEEEFloat::IEK_Zero; | ||||
4460 | if (Arg.isInfinity()) | ||||
4461 | return IEEEFloat::IEK_Inf; | ||||
4462 | if (!Arg.isDenormal()) | ||||
4463 | return Arg.exponent; | ||||
4464 | |||||
4465 | IEEEFloat Normalized(Arg); | ||||
4466 | int SignificandBits = Arg.getSemantics().precision - 1; | ||||
4467 | |||||
4468 | Normalized.exponent += SignificandBits; | ||||
4469 | Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero); | ||||
4470 | return Normalized.exponent - SignificandBits; | ||||
4471 | } | ||||
4472 | |||||
4473 | IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) { | ||||
4474 | auto MaxExp = X.getSemantics().maxExponent; | ||||
4475 | auto MinExp = X.getSemantics().minExponent; | ||||
4476 | |||||
4477 | // If Exp is wildly out-of-scale, simply adding it to X.exponent will | ||||
4478 | // overflow; clamp it to a safe range before adding, but ensure that the range | ||||
4479 | // is large enough that the clamp does not change the result. The range we | ||||
4480 | // need to support is the difference between the largest possible exponent and | ||||
4481 | // the normalized exponent of half the smallest denormal. | ||||
4482 | |||||
4483 | int SignificandBits = X.getSemantics().precision - 1; | ||||
4484 | int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1; | ||||
4485 | |||||
4486 | // Clamp to one past the range ends to let normalize handle overlflow. | ||||
4487 | X.exponent += std::clamp(Exp, -MaxIncrement - 1, MaxIncrement); | ||||
4488 | X.normalize(RoundingMode, lfExactlyZero); | ||||
4489 | if (X.isNaN()) | ||||
4490 | X.makeQuiet(); | ||||
4491 | return X; | ||||
4492 | } | ||||
4493 | |||||
4494 | IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) { | ||||
4495 | Exp = ilogb(Val); | ||||
4496 | |||||
4497 | // Quiet signalling nans. | ||||
4498 | if (Exp == IEEEFloat::IEK_NaN) { | ||||
4499 | IEEEFloat Quiet(Val); | ||||
4500 | Quiet.makeQuiet(); | ||||
4501 | return Quiet; | ||||
4502 | } | ||||
4503 | |||||
4504 | if (Exp == IEEEFloat::IEK_Inf) | ||||
4505 | return Val; | ||||
4506 | |||||
4507 | // 1 is added because frexp is defined to return a normalized fraction in | ||||
4508 | // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0). | ||||
4509 | Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1; | ||||
4510 | return scalbn(Val, -Exp, RM); | ||||
4511 | } | ||||
4512 | |||||
4513 | DoubleAPFloat::DoubleAPFloat(const fltSemantics &S) | ||||
4514 | : Semantics(&S), | ||||
4515 | Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) { | ||||
4516 | assert(Semantics == &semPPCDoubleDouble)(static_cast <bool> (Semantics == &semPPCDoubleDouble ) ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble" , "llvm/lib/Support/APFloat.cpp", 4516, __extension__ __PRETTY_FUNCTION__ )); | ||||
4517 | } | ||||
4518 | |||||
4519 | DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag) | ||||
4520 | : Semantics(&S), | ||||
4521 | Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized), | ||||
4522 | APFloat(semIEEEdouble, uninitialized)}) { | ||||
4523 | assert(Semantics == &semPPCDoubleDouble)(static_cast <bool> (Semantics == &semPPCDoubleDouble ) ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble" , "llvm/lib/Support/APFloat.cpp", 4523, __extension__ __PRETTY_FUNCTION__ )); | ||||
4524 | } | ||||
4525 | |||||
4526 | DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I) | ||||
4527 | : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I), | ||||
4528 | APFloat(semIEEEdouble)}) { | ||||
4529 | assert(Semantics == &semPPCDoubleDouble)(static_cast <bool> (Semantics == &semPPCDoubleDouble ) ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble" , "llvm/lib/Support/APFloat.cpp", 4529, __extension__ __PRETTY_FUNCTION__ )); | ||||
4530 | } | ||||
4531 | |||||
4532 | DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I) | ||||
4533 | : Semantics(&S), | ||||
4534 | Floats(new APFloat[2]{ | ||||
4535 | APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])), | ||||
4536 | APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) { | ||||
4537 | assert(Semantics == &semPPCDoubleDouble)(static_cast <bool> (Semantics == &semPPCDoubleDouble ) ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble" , "llvm/lib/Support/APFloat.cpp", 4537, __extension__ __PRETTY_FUNCTION__ )); | ||||
4538 | } | ||||
4539 | |||||
4540 | DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First, | ||||
4541 | APFloat &&Second) | ||||
4542 | : Semantics(&S), | ||||
4543 | Floats(new APFloat[2]{std::move(First), std::move(Second)}) { | ||||
4544 | assert(Semantics == &semPPCDoubleDouble)(static_cast <bool> (Semantics == &semPPCDoubleDouble ) ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble" , "llvm/lib/Support/APFloat.cpp", 4544, __extension__ __PRETTY_FUNCTION__ )); | ||||
4545 | assert(&Floats[0].getSemantics() == &semIEEEdouble)(static_cast <bool> (&Floats[0].getSemantics() == & semIEEEdouble) ? void (0) : __assert_fail ("&Floats[0].getSemantics() == &semIEEEdouble" , "llvm/lib/Support/APFloat.cpp", 4545, __extension__ __PRETTY_FUNCTION__ )); | ||||
4546 | assert(&Floats[1].getSemantics() == &semIEEEdouble)(static_cast <bool> (&Floats[1].getSemantics() == & semIEEEdouble) ? void (0) : __assert_fail ("&Floats[1].getSemantics() == &semIEEEdouble" , "llvm/lib/Support/APFloat.cpp", 4546, __extension__ __PRETTY_FUNCTION__ )); | ||||
4547 | } | ||||
4548 | |||||
4549 | DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS) | ||||
4550 | : Semantics(RHS.Semantics), | ||||
4551 | Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]), | ||||
4552 | APFloat(RHS.Floats[1])} | ||||
4553 | : nullptr) { | ||||
4554 | assert(Semantics == &semPPCDoubleDouble)(static_cast <bool> (Semantics == &semPPCDoubleDouble ) ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble" , "llvm/lib/Support/APFloat.cpp", 4554, __extension__ __PRETTY_FUNCTION__ )); | ||||
4555 | } | ||||
4556 | |||||
4557 | DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS) | ||||
4558 | : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) { | ||||
4559 | RHS.Semantics = &semBogus; | ||||
4560 | assert(Semantics == &semPPCDoubleDouble)(static_cast <bool> (Semantics == &semPPCDoubleDouble ) ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble" , "llvm/lib/Support/APFloat.cpp", 4560, __extension__ __PRETTY_FUNCTION__ )); | ||||
4561 | } | ||||
4562 | |||||
4563 | DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) { | ||||
4564 | if (Semantics == RHS.Semantics && RHS.Floats) { | ||||
4565 | Floats[0] = RHS.Floats[0]; | ||||
4566 | Floats[1] = RHS.Floats[1]; | ||||
4567 | } else if (this != &RHS) { | ||||
4568 | this->~DoubleAPFloat(); | ||||
4569 | new (this) DoubleAPFloat(RHS); | ||||
4570 | } | ||||
4571 | return *this; | ||||
4572 | } | ||||
4573 | |||||
4574 | // Implement addition, subtraction, multiplication and division based on: | ||||
4575 | // "Software for Doubled-Precision Floating-Point Computations", | ||||
4576 | // by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283. | ||||
4577 | APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa, | ||||
4578 | const APFloat &c, const APFloat &cc, | ||||
4579 | roundingMode RM) { | ||||
4580 | int Status = opOK; | ||||
4581 | APFloat z = a; | ||||
4582 | Status |= z.add(c, RM); | ||||
4583 | if (!z.isFinite()) { | ||||
4584 | if (!z.isInfinity()) { | ||||
4585 | Floats[0] = std::move(z); | ||||
4586 | Floats[1].makeZero(/* Neg = */ false); | ||||
4587 | return (opStatus)Status; | ||||
4588 | } | ||||
4589 | Status = opOK; | ||||
4590 | auto AComparedToC = a.compareAbsoluteValue(c); | ||||
4591 | z = cc; | ||||
4592 | Status |= z.add(aa, RM); | ||||
4593 | if (AComparedToC == APFloat::cmpGreaterThan) { | ||||
4594 | // z = cc + aa + c + a; | ||||
4595 | Status |= z.add(c, RM); | ||||
4596 | Status |= z.add(a, RM); | ||||
4597 | } else { | ||||
4598 | // z = cc + aa + a + c; | ||||
4599 | Status |= z.add(a, RM); | ||||
4600 | Status |= z.add(c, RM); | ||||
4601 | } | ||||
4602 | if (!z.isFinite()) { | ||||
4603 | Floats[0] = std::move(z); | ||||
4604 | Floats[1].makeZero(/* Neg = */ false); | ||||
4605 | return (opStatus)Status; | ||||
4606 | } | ||||
4607 | Floats[0] = z; | ||||
4608 | APFloat zz = aa; | ||||
4609 | Status |= zz.add(cc, RM); | ||||
4610 | if (AComparedToC == APFloat::cmpGreaterThan) { | ||||
4611 | // Floats[1] = a - z + c + zz; | ||||
4612 | Floats[1] = a; | ||||
4613 | Status |= Floats[1].subtract(z, RM); | ||||
4614 | Status |= Floats[1].add(c, RM); | ||||
4615 | Status |= Floats[1].add(zz, RM); | ||||
4616 | } else { | ||||
4617 | // Floats[1] = c - z + a + zz; | ||||
4618 | Floats[1] = c; | ||||
4619 | Status |= Floats[1].subtract(z, RM); | ||||
4620 | Status |= Floats[1].add(a, RM); | ||||
4621 | Status |= Floats[1].add(zz, RM); | ||||
4622 | } | ||||
4623 | } else { | ||||
4624 | // q = a - z; | ||||
4625 | APFloat q = a; | ||||
4626 | Status |= q.subtract(z, RM); | ||||
4627 | |||||
4628 | // zz = q + c + (a - (q + z)) + aa + cc; | ||||
4629 | // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies. | ||||
4630 | auto zz = q; | ||||
4631 | Status |= zz.add(c, RM); | ||||
4632 | Status |= q.add(z, RM); | ||||
4633 | Status |= q.subtract(a, RM); | ||||
4634 | q.changeSign(); | ||||
4635 | Status |= zz.add(q, RM); | ||||
4636 | Status |= zz.add(aa, RM); | ||||
4637 | Status |= zz.add(cc, RM); | ||||
4638 | if (zz.isZero() && !zz.isNegative()) { | ||||
4639 | Floats[0] = std::move(z); | ||||
4640 | Floats[1].makeZero(/* Neg = */ false); | ||||
4641 | return opOK; | ||||
4642 | } | ||||
4643 | Floats[0] = z; | ||||
4644 | Status |= Floats[0].add(zz, RM); | ||||
4645 | if (!Floats[0].isFinite()) { | ||||
4646 | Floats[1].makeZero(/* Neg = */ false); | ||||
4647 | return (opStatus)Status; | ||||
4648 | } | ||||
4649 | Floats[1] = std::move(z); | ||||
4650 | Status |= Floats[1].subtract(Floats[0], RM); | ||||
4651 | Status |= Floats[1].add(zz, RM); | ||||
4652 | } | ||||
4653 | return (opStatus)Status; | ||||
4654 | } | ||||
4655 | |||||
4656 | APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS, | ||||
4657 | const DoubleAPFloat &RHS, | ||||
4658 | DoubleAPFloat &Out, | ||||
4659 | roundingMode RM) { | ||||
4660 | if (LHS.getCategory() == fcNaN) { | ||||
4661 | Out = LHS; | ||||
4662 | return opOK; | ||||
4663 | } | ||||
4664 | if (RHS.getCategory() == fcNaN) { | ||||
4665 | Out = RHS; | ||||
4666 | return opOK; | ||||
4667 | } | ||||
4668 | if (LHS.getCategory() == fcZero) { | ||||
4669 | Out = RHS; | ||||
4670 | return opOK; | ||||
4671 | } | ||||
4672 | if (RHS.getCategory() == fcZero) { | ||||
4673 | Out = LHS; | ||||
4674 | return opOK; | ||||
4675 | } | ||||
4676 | if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity && | ||||
4677 | LHS.isNegative() != RHS.isNegative()) { | ||||
4678 | Out.makeNaN(false, Out.isNegative(), nullptr); | ||||
4679 | return opInvalidOp; | ||||
4680 | } | ||||
4681 | if (LHS.getCategory() == fcInfinity) { | ||||
4682 | Out = LHS; | ||||
4683 | return opOK; | ||||
4684 | } | ||||
4685 | if (RHS.getCategory() == fcInfinity) { | ||||
4686 | Out = RHS; | ||||
4687 | return opOK; | ||||
4688 | } | ||||
4689 | assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal)(static_cast <bool> (LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal) ? void (0) : __assert_fail ("LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal" , "llvm/lib/Support/APFloat.cpp", 4689, __extension__ __PRETTY_FUNCTION__ )); | ||||
4690 | |||||
4691 | APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]), | ||||
4692 | CC(RHS.Floats[1]); | ||||
4693 | assert(&A.getSemantics() == &semIEEEdouble)(static_cast <bool> (&A.getSemantics() == &semIEEEdouble ) ? void (0) : __assert_fail ("&A.getSemantics() == &semIEEEdouble" , "llvm/lib/Support/APFloat.cpp", 4693, __extension__ __PRETTY_FUNCTION__ )); | ||||
4694 | assert(&AA.getSemantics() == &semIEEEdouble)(static_cast <bool> (&AA.getSemantics() == &semIEEEdouble ) ? void (0) : __assert_fail ("&AA.getSemantics() == &semIEEEdouble" , "llvm/lib/Support/APFloat.cpp", 4694, __extension__ __PRETTY_FUNCTION__ )); | ||||
4695 | assert(&C.getSemantics() == &semIEEEdouble)(static_cast <bool> (&C.getSemantics() == &semIEEEdouble ) ? void (0) : __assert_fail ("&C.getSemantics() == &semIEEEdouble" , "llvm/lib/Support/APFloat.cpp", 4695, __extension__ __PRETTY_FUNCTION__ )); | ||||
4696 | assert(&CC.getSemantics() == &semIEEEdouble)(static_cast <bool> (&CC.getSemantics() == &semIEEEdouble ) ? void (0) : __assert_fail ("&CC.getSemantics() == &semIEEEdouble" , "llvm/lib/Support/APFloat.cpp", 4696, __extension__ __PRETTY_FUNCTION__ )); | ||||
4697 | assert(&Out.Floats[0].getSemantics() == &semIEEEdouble)(static_cast <bool> (&Out.Floats[0].getSemantics() == &semIEEEdouble) ? void (0) : __assert_fail ("&Out.Floats[0].getSemantics() == &semIEEEdouble" , "llvm/lib/Support/APFloat.cpp", 4697, __extension__ __PRETTY_FUNCTION__ )); | ||||
4698 | assert(&Out.Floats[1].getSemantics() == &semIEEEdouble)(static_cast <bool> (&Out.Floats[1].getSemantics() == &semIEEEdouble) ? void (0) : __assert_fail ("&Out.Floats[1].getSemantics() == &semIEEEdouble" , "llvm/lib/Support/APFloat.cpp", 4698, __extension__ __PRETTY_FUNCTION__ )); | ||||
4699 | return Out.addImpl(A, AA, C, CC, RM); | ||||
4700 | } | ||||
4701 | |||||
4702 | APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS, | ||||
4703 | roundingMode RM) { | ||||
4704 | return addWithSpecial(*this, RHS, *this, RM); | ||||
4705 | } | ||||
4706 | |||||
4707 | APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS, | ||||
4708 | roundingMode RM) { | ||||
4709 | changeSign(); | ||||
4710 | auto Ret = add(RHS, RM); | ||||
4711 | changeSign(); | ||||
4712 | return Ret; | ||||
4713 | } | ||||
4714 | |||||
4715 | APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS, | ||||
4716 | APFloat::roundingMode RM) { | ||||
4717 | const auto &LHS = *this; | ||||
4718 | auto &Out = *this; | ||||
4719 | /* Interesting observation: For special categories, finding the lowest | ||||
4720 | common ancestor of the following layered graph gives the correct | ||||
4721 | return category: | ||||
4722 | |||||
4723 | NaN | ||||
4724 | / \ | ||||
4725 | Zero Inf | ||||
4726 | \ / | ||||
4727 | Normal | ||||
4728 | |||||
4729 | e.g. NaN * NaN = NaN | ||||
4730 | Zero * Inf = NaN | ||||
4731 | Normal * Zero = Zero | ||||
4732 | Normal * Inf = Inf | ||||
4733 | */ | ||||
4734 | if (LHS.getCategory() == fcNaN) { | ||||
4735 | Out = LHS; | ||||
4736 | return opOK; | ||||
4737 | } | ||||
4738 | if (RHS.getCategory() == fcNaN) { | ||||
4739 | Out = RHS; | ||||
4740 | return opOK; | ||||
4741 | } | ||||
4742 | if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) || | ||||
4743 | (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) { | ||||
4744 | Out.makeNaN(false, false, nullptr); | ||||
4745 | return opOK; | ||||
4746 | } | ||||
4747 | if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) { | ||||
4748 | Out = LHS; | ||||
4749 | return opOK; | ||||
4750 | } | ||||
4751 | if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) { | ||||
4752 | Out = RHS; | ||||
4753 | return opOK; | ||||
4754 | } | ||||
4755 | assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&(static_cast <bool> (LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal && "Special cases not handled exhaustively" ) ? void (0) : __assert_fail ("LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal && \"Special cases not handled exhaustively\"" , "llvm/lib/Support/APFloat.cpp", 4756, __extension__ __PRETTY_FUNCTION__ )) | ||||
4756 | "Special cases not handled exhaustively")(static_cast <bool> (LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal && "Special cases not handled exhaustively" ) ? void (0) : __assert_fail ("LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal && \"Special cases not handled exhaustively\"" , "llvm/lib/Support/APFloat.cpp", 4756, __extension__ __PRETTY_FUNCTION__ )); | ||||
4757 | |||||
4758 | int Status = opOK; | ||||
4759 | APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1]; | ||||
4760 | // t = a * c | ||||
4761 | APFloat T = A; | ||||
4762 | Status |= T.multiply(C, RM); | ||||
4763 | if (!T.isFiniteNonZero()) { | ||||
4764 | Floats[0] = T; | ||||
4765 | Floats[1].makeZero(/* Neg = */ false); | ||||
4766 | return (opStatus)Status; | ||||
4767 | } | ||||
4768 | |||||
4769 | // tau = fmsub(a, c, t), that is -fmadd(-a, c, t). | ||||
4770 | APFloat Tau = A; | ||||
4771 | T.changeSign(); | ||||
4772 | Status |= Tau.fusedMultiplyAdd(C, T, RM); | ||||
4773 | T.changeSign(); | ||||
4774 | { | ||||
4775 | // v = a * d | ||||
4776 | APFloat V = A; | ||||
4777 | Status |= V.multiply(D, RM); | ||||
4778 | // w = b * c | ||||
4779 | APFloat W = B; | ||||
4780 | Status |= W.multiply(C, RM); | ||||
4781 | Status |= V.add(W, RM); | ||||
4782 | // tau += v + w | ||||
4783 | Status |= Tau.add(V, RM); | ||||
4784 | } | ||||
4785 | // u = t + tau | ||||
4786 | APFloat U = T; | ||||
4787 | Status |= U.add(Tau, RM); | ||||
4788 | |||||
4789 | Floats[0] = U; | ||||
4790 | if (!U.isFinite()) { | ||||
4791 | Floats[1].makeZero(/* Neg = */ false); | ||||
4792 | } else { | ||||
4793 | // Floats[1] = (t - u) + tau | ||||
4794 | Status |= T.subtract(U, RM); | ||||
4795 | Status |= T.add(Tau, RM); | ||||
4796 | Floats[1] = T; | ||||
4797 | } | ||||
4798 | return (opStatus)Status; | ||||
4799 | } | ||||
4800 | |||||
4801 | APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS, | ||||
4802 | APFloat::roundingMode RM) { | ||||
4803 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4803, __extension__ __PRETTY_FUNCTION__ )); | ||||
4804 | APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); | ||||
4805 | auto Ret = | ||||
4806 | Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM); | ||||
4807 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
4808 | return Ret; | ||||
4809 | } | ||||
4810 | |||||
4811 | APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) { | ||||
4812 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4812, __extension__ __PRETTY_FUNCTION__ )); | ||||
4813 | APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); | ||||
4814 | auto Ret = | ||||
4815 | Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt())); | ||||
4816 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
4817 | return Ret; | ||||
4818 | } | ||||
4819 | |||||
4820 | APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) { | ||||
4821 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4821, __extension__ __PRETTY_FUNCTION__ )); | ||||
4822 | APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); | ||||
4823 | auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt())); | ||||
4824 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
4825 | return Ret; | ||||
4826 | } | ||||
4827 | |||||
4828 | APFloat::opStatus | ||||
4829 | DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, | ||||
4830 | const DoubleAPFloat &Addend, | ||||
4831 | APFloat::roundingMode RM) { | ||||
4832 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4832, __extension__ __PRETTY_FUNCTION__ )); | ||||
4833 | APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); | ||||
4834 | auto Ret = Tmp.fusedMultiplyAdd( | ||||
4835 | APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()), | ||||
4836 | APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM); | ||||
4837 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
4838 | return Ret; | ||||
4839 | } | ||||
4840 | |||||
4841 | APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) { | ||||
4842 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4842, __extension__ __PRETTY_FUNCTION__ )); | ||||
4843 | APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); | ||||
4844 | auto Ret = Tmp.roundToIntegral(RM); | ||||
4845 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
4846 | return Ret; | ||||
4847 | } | ||||
4848 | |||||
4849 | void DoubleAPFloat::changeSign() { | ||||
4850 | Floats[0].changeSign(); | ||||
4851 | Floats[1].changeSign(); | ||||
4852 | } | ||||
4853 | |||||
4854 | APFloat::cmpResult | ||||
4855 | DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const { | ||||
4856 | auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]); | ||||
4857 | if (Result != cmpEqual) | ||||
4858 | return Result; | ||||
4859 | Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]); | ||||
4860 | if (Result == cmpLessThan || Result == cmpGreaterThan) { | ||||
4861 | auto Against = Floats[0].isNegative() ^ Floats[1].isNegative(); | ||||
4862 | auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative(); | ||||
4863 | if (Against && !RHSAgainst) | ||||
4864 | return cmpLessThan; | ||||
4865 | if (!Against && RHSAgainst) | ||||
4866 | return cmpGreaterThan; | ||||
4867 | if (!Against && !RHSAgainst) | ||||
4868 | return Result; | ||||
4869 | if (Against && RHSAgainst) | ||||
4870 | return (cmpResult)(cmpLessThan + cmpGreaterThan - Result); | ||||
4871 | } | ||||
4872 | return Result; | ||||
4873 | } | ||||
4874 | |||||
4875 | APFloat::fltCategory DoubleAPFloat::getCategory() const { | ||||
4876 | return Floats[0].getCategory(); | ||||
4877 | } | ||||
4878 | |||||
4879 | bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); } | ||||
4880 | |||||
4881 | void DoubleAPFloat::makeInf(bool Neg) { | ||||
4882 | Floats[0].makeInf(Neg); | ||||
4883 | Floats[1].makeZero(/* Neg = */ false); | ||||
4884 | } | ||||
4885 | |||||
4886 | void DoubleAPFloat::makeZero(bool Neg) { | ||||
4887 | Floats[0].makeZero(Neg); | ||||
4888 | Floats[1].makeZero(/* Neg = */ false); | ||||
4889 | } | ||||
4890 | |||||
4891 | void DoubleAPFloat::makeLargest(bool Neg) { | ||||
4892 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4892, __extension__ __PRETTY_FUNCTION__ )); | ||||
4893 | Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull)); | ||||
4894 | Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull)); | ||||
4895 | if (Neg) | ||||
4896 | changeSign(); | ||||
4897 | } | ||||
4898 | |||||
4899 | void DoubleAPFloat::makeSmallest(bool Neg) { | ||||
4900 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4900, __extension__ __PRETTY_FUNCTION__ )); | ||||
4901 | Floats[0].makeSmallest(Neg); | ||||
4902 | Floats[1].makeZero(/* Neg = */ false); | ||||
4903 | } | ||||
4904 | |||||
4905 | void DoubleAPFloat::makeSmallestNormalized(bool Neg) { | ||||
4906 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4906, __extension__ __PRETTY_FUNCTION__ )); | ||||
4907 | Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull)); | ||||
4908 | if (Neg) | ||||
4909 | Floats[0].changeSign(); | ||||
4910 | Floats[1].makeZero(/* Neg = */ false); | ||||
4911 | } | ||||
4912 | |||||
4913 | void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) { | ||||
4914 | Floats[0].makeNaN(SNaN, Neg, fill); | ||||
4915 | Floats[1].makeZero(/* Neg = */ false); | ||||
4916 | } | ||||
4917 | |||||
4918 | APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const { | ||||
4919 | auto Result = Floats[0].compare(RHS.Floats[0]); | ||||
4920 | // |Float[0]| > |Float[1]| | ||||
4921 | if (Result == APFloat::cmpEqual) | ||||
4922 | return Floats[1].compare(RHS.Floats[1]); | ||||
4923 | return Result; | ||||
4924 | } | ||||
4925 | |||||
4926 | bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const { | ||||
4927 | return Floats[0].bitwiseIsEqual(RHS.Floats[0]) && | ||||
4928 | Floats[1].bitwiseIsEqual(RHS.Floats[1]); | ||||
4929 | } | ||||
4930 | |||||
4931 | hash_code hash_value(const DoubleAPFloat &Arg) { | ||||
4932 | if (Arg.Floats) | ||||
4933 | return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1])); | ||||
4934 | return hash_combine(Arg.Semantics); | ||||
4935 | } | ||||
4936 | |||||
4937 | APInt DoubleAPFloat::bitcastToAPInt() const { | ||||
4938 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4938, __extension__ __PRETTY_FUNCTION__ )); | ||||
4939 | uint64_t Data[] = { | ||||
4940 | Floats[0].bitcastToAPInt().getRawData()[0], | ||||
4941 | Floats[1].bitcastToAPInt().getRawData()[0], | ||||
4942 | }; | ||||
4943 | return APInt(128, 2, Data); | ||||
4944 | } | ||||
4945 | |||||
4946 | Expected<APFloat::opStatus> DoubleAPFloat::convertFromString(StringRef S, | ||||
4947 | roundingMode RM) { | ||||
4948 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4948, __extension__ __PRETTY_FUNCTION__ )); | ||||
4949 | APFloat Tmp(semPPCDoubleDoubleLegacy); | ||||
4950 | auto Ret = Tmp.convertFromString(S, RM); | ||||
4951 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
4952 | return Ret; | ||||
4953 | } | ||||
4954 | |||||
4955 | APFloat::opStatus DoubleAPFloat::next(bool nextDown) { | ||||
4956 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4956, __extension__ __PRETTY_FUNCTION__ )); | ||||
4957 | APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); | ||||
4958 | auto Ret = Tmp.next(nextDown); | ||||
4959 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
4960 | return Ret; | ||||
4961 | } | ||||
4962 | |||||
4963 | APFloat::opStatus | ||||
4964 | DoubleAPFloat::convertToInteger(MutableArrayRef<integerPart> Input, | ||||
4965 | unsigned int Width, bool IsSigned, | ||||
4966 | roundingMode RM, bool *IsExact) const { | ||||
4967 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4967, __extension__ __PRETTY_FUNCTION__ )); | ||||
4968 | return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt()) | ||||
4969 | .convertToInteger(Input, Width, IsSigned, RM, IsExact); | ||||
4970 | } | ||||
4971 | |||||
4972 | APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input, | ||||
4973 | bool IsSigned, | ||||
4974 | roundingMode RM) { | ||||
4975 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4975, __extension__ __PRETTY_FUNCTION__ )); | ||||
4976 | APFloat Tmp(semPPCDoubleDoubleLegacy); | ||||
4977 | auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM); | ||||
4978 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
4979 | return Ret; | ||||
4980 | } | ||||
4981 | |||||
4982 | APFloat::opStatus | ||||
4983 | DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input, | ||||
4984 | unsigned int InputSize, | ||||
4985 | bool IsSigned, roundingMode RM) { | ||||
4986 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4986, __extension__ __PRETTY_FUNCTION__ )); | ||||
4987 | APFloat Tmp(semPPCDoubleDoubleLegacy); | ||||
4988 | auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM); | ||||
4989 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
4990 | return Ret; | ||||
4991 | } | ||||
4992 | |||||
4993 | APFloat::opStatus | ||||
4994 | DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input, | ||||
4995 | unsigned int InputSize, | ||||
4996 | bool IsSigned, roundingMode RM) { | ||||
4997 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 4997, __extension__ __PRETTY_FUNCTION__ )); | ||||
4998 | APFloat Tmp(semPPCDoubleDoubleLegacy); | ||||
4999 | auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM); | ||||
5000 | *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); | ||||
5001 | return Ret; | ||||
5002 | } | ||||
5003 | |||||
5004 | unsigned int DoubleAPFloat::convertToHexString(char *DST, | ||||
5005 | unsigned int HexDigits, | ||||
5006 | bool UpperCase, | ||||
5007 | roundingMode RM) const { | ||||
5008 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 5008, __extension__ __PRETTY_FUNCTION__ )); | ||||
5009 | return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt()) | ||||
5010 | .convertToHexString(DST, HexDigits, UpperCase, RM); | ||||
5011 | } | ||||
5012 | |||||
5013 | bool DoubleAPFloat::isDenormal() const { | ||||
5014 | return getCategory() == fcNormal && | ||||
5015 | (Floats[0].isDenormal() || Floats[1].isDenormal() || | ||||
5016 | // (double)(Hi + Lo) == Hi defines a normal number. | ||||
5017 | Floats[0] != Floats[0] + Floats[1]); | ||||
5018 | } | ||||
5019 | |||||
5020 | bool DoubleAPFloat::isSmallest() const { | ||||
5021 | if (getCategory() != fcNormal) | ||||
5022 | return false; | ||||
5023 | DoubleAPFloat Tmp(*this); | ||||
5024 | Tmp.makeSmallest(this->isNegative()); | ||||
5025 | return Tmp.compare(*this) == cmpEqual; | ||||
5026 | } | ||||
5027 | |||||
5028 | bool DoubleAPFloat::isSmallestNormalized() const { | ||||
5029 | if (getCategory() != fcNormal) | ||||
5030 | return false; | ||||
5031 | |||||
5032 | DoubleAPFloat Tmp(*this); | ||||
5033 | Tmp.makeSmallestNormalized(this->isNegative()); | ||||
5034 | return Tmp.compare(*this) == cmpEqual; | ||||
5035 | } | ||||
5036 | |||||
5037 | bool DoubleAPFloat::isLargest() const { | ||||
5038 | if (getCategory() != fcNormal) | ||||
5039 | return false; | ||||
5040 | DoubleAPFloat Tmp(*this); | ||||
5041 | Tmp.makeLargest(this->isNegative()); | ||||
5042 | return Tmp.compare(*this) == cmpEqual; | ||||
5043 | } | ||||
5044 | |||||
5045 | bool DoubleAPFloat::isInteger() const { | ||||
5046 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 5046, __extension__ __PRETTY_FUNCTION__ )); | ||||
5047 | return Floats[0].isInteger() && Floats[1].isInteger(); | ||||
5048 | } | ||||
5049 | |||||
5050 | void DoubleAPFloat::toString(SmallVectorImpl<char> &Str, | ||||
5051 | unsigned FormatPrecision, | ||||
5052 | unsigned FormatMaxPadding, | ||||
5053 | bool TruncateZero) const { | ||||
5054 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 5054, __extension__ __PRETTY_FUNCTION__ )); | ||||
5055 | APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt()) | ||||
5056 | .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero); | ||||
5057 | } | ||||
5058 | |||||
5059 | bool DoubleAPFloat::getExactInverse(APFloat *inv) const { | ||||
5060 | assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 5060, __extension__ __PRETTY_FUNCTION__ )); | ||||
5061 | APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); | ||||
5062 | if (!inv) | ||||
5063 | return Tmp.getExactInverse(nullptr); | ||||
5064 | APFloat Inv(semPPCDoubleDoubleLegacy); | ||||
5065 | auto Ret = Tmp.getExactInverse(&Inv); | ||||
5066 | *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt()); | ||||
5067 | return Ret; | ||||
5068 | } | ||||
5069 | |||||
5070 | DoubleAPFloat scalbn(const DoubleAPFloat &Arg, int Exp, | ||||
5071 | APFloat::roundingMode RM) { | ||||
5072 | assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Arg.Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 5072, __extension__ __PRETTY_FUNCTION__ )); | ||||
5073 | return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM), | ||||
5074 | scalbn(Arg.Floats[1], Exp, RM)); | ||||
5075 | } | ||||
5076 | |||||
5077 | DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp, | ||||
5078 | APFloat::roundingMode RM) { | ||||
5079 | assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics")(static_cast <bool> (Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics") ? void (0) : __assert_fail ("Arg.Semantics == &semPPCDoubleDouble && \"Unexpected Semantics\"" , "llvm/lib/Support/APFloat.cpp", 5079, __extension__ __PRETTY_FUNCTION__ )); | ||||
5080 | APFloat First = frexp(Arg.Floats[0], Exp, RM); | ||||
5081 | APFloat Second = Arg.Floats[1]; | ||||
5082 | if (Arg.getCategory() == APFloat::fcNormal) | ||||
5083 | Second = scalbn(Second, -Exp, RM); | ||||
5084 | return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second)); | ||||
5085 | } | ||||
5086 | |||||
5087 | } // namespace detail | ||||
5088 | |||||
5089 | APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) { | ||||
5090 | if (usesLayout<IEEEFloat>(Semantics)) { | ||||
5091 | new (&IEEE) IEEEFloat(std::move(F)); | ||||
5092 | return; | ||||
5093 | } | ||||
5094 | if (usesLayout<DoubleAPFloat>(Semantics)) { | ||||
5095 | const fltSemantics& S = F.getSemantics(); | ||||
5096 | new (&Double) | ||||
5097 | DoubleAPFloat(Semantics, APFloat(std::move(F), S), | ||||
5098 | APFloat(semIEEEdouble)); | ||||
5099 | return; | ||||
5100 | } | ||||
5101 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/lib/Support/APFloat.cpp" , 5101); | ||||
5102 | } | ||||
5103 | |||||
5104 | Expected<APFloat::opStatus> APFloat::convertFromString(StringRef Str, | ||||
5105 | roundingMode RM) { | ||||
5106 | APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM)); | ||||
5107 | } | ||||
5108 | |||||
5109 | hash_code hash_value(const APFloat &Arg) { | ||||
5110 | if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics())) | ||||
5111 | return hash_value(Arg.U.IEEE); | ||||
5112 | if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics())) | ||||
5113 | return hash_value(Arg.U.Double); | ||||
5114 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/lib/Support/APFloat.cpp" , 5114); | ||||
5115 | } | ||||
5116 | |||||
5117 | APFloat::APFloat(const fltSemantics &Semantics, StringRef S) | ||||
5118 | : APFloat(Semantics) { | ||||
5119 | auto StatusOrErr = convertFromString(S, rmNearestTiesToEven); | ||||
5120 | assert(StatusOrErr && "Invalid floating point representation")(static_cast <bool> (StatusOrErr && "Invalid floating point representation" ) ? void (0) : __assert_fail ("StatusOrErr && \"Invalid floating point representation\"" , "llvm/lib/Support/APFloat.cpp", 5120, __extension__ __PRETTY_FUNCTION__ )); | ||||
5121 | consumeError(StatusOrErr.takeError()); | ||||
5122 | } | ||||
5123 | |||||
5124 | FPClassTest APFloat::classify() const { | ||||
5125 | if (isZero()) | ||||
5126 | return isNegative() ? fcNegZero : fcPosZero; | ||||
5127 | if (isNormal()) | ||||
5128 | return isNegative() ? fcNegNormal : fcPosNormal; | ||||
5129 | if (isDenormal()) | ||||
5130 | return isNegative() ? fcNegSubnormal : fcPosSubnormal; | ||||
5131 | if (isInfinity()) | ||||
5132 | return isNegative() ? fcNegInf : fcPosInf; | ||||
5133 | assert(isNaN() && "Other class of FP constant")(static_cast <bool> (isNaN() && "Other class of FP constant" ) ? void (0) : __assert_fail ("isNaN() && \"Other class of FP constant\"" , "llvm/lib/Support/APFloat.cpp", 5133, __extension__ __PRETTY_FUNCTION__ )); | ||||
5134 | return isSignaling() ? fcSNan : fcQNan; | ||||
5135 | } | ||||
5136 | |||||
5137 | APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics, | ||||
5138 | roundingMode RM, bool *losesInfo) { | ||||
5139 | if (&getSemantics() == &ToSemantics) { | ||||
5140 | *losesInfo = false; | ||||
5141 | return opOK; | ||||
5142 | } | ||||
5143 | if (usesLayout<IEEEFloat>(getSemantics()) && | ||||
5144 | usesLayout<IEEEFloat>(ToSemantics)) | ||||
5145 | return U.IEEE.convert(ToSemantics, RM, losesInfo); | ||||
5146 | if (usesLayout<IEEEFloat>(getSemantics()) && | ||||
5147 | usesLayout<DoubleAPFloat>(ToSemantics)) { | ||||
5148 | assert(&ToSemantics == &semPPCDoubleDouble)(static_cast <bool> (&ToSemantics == &semPPCDoubleDouble ) ? void (0) : __assert_fail ("&ToSemantics == &semPPCDoubleDouble" , "llvm/lib/Support/APFloat.cpp", 5148, __extension__ __PRETTY_FUNCTION__ )); | ||||
5149 | auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo); | ||||
5150 | *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt()); | ||||
5151 | return Ret; | ||||
5152 | } | ||||
5153 | if (usesLayout<DoubleAPFloat>(getSemantics()) && | ||||
5154 | usesLayout<IEEEFloat>(ToSemantics)) { | ||||
5155 | auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo); | ||||
5156 | *this = APFloat(std::move(getIEEE()), ToSemantics); | ||||
5157 | return Ret; | ||||
5158 | } | ||||
5159 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/lib/Support/APFloat.cpp" , 5159); | ||||
5160 | } | ||||
5161 | |||||
5162 | APFloat APFloat::getAllOnesValue(const fltSemantics &Semantics) { | ||||
5163 | return APFloat(Semantics, APInt::getAllOnes(Semantics.sizeInBits)); | ||||
5164 | } | ||||
5165 | |||||
5166 | void APFloat::print(raw_ostream &OS) const { | ||||
5167 | SmallVector<char, 16> Buffer; | ||||
5168 | toString(Buffer); | ||||
5169 | OS << Buffer << "\n"; | ||||
5170 | } | ||||
5171 | |||||
5172 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | ||||
5173 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void APFloat::dump() const { print(dbgs()); } | ||||
5174 | #endif | ||||
5175 | |||||
5176 | void APFloat::Profile(FoldingSetNodeID &NID) const { | ||||
5177 | NID.Add(bitcastToAPInt()); | ||||
5178 | } | ||||
5179 | |||||
5180 | /* Same as convertToInteger(integerPart*, ...), except the result is returned in | ||||
5181 | an APSInt, whose initial bit-width and signed-ness are used to determine the | ||||
5182 | precision of the conversion. | ||||
5183 | */ | ||||
5184 | APFloat::opStatus APFloat::convertToInteger(APSInt &result, | ||||
5185 | roundingMode rounding_mode, | ||||
5186 | bool *isExact) const { | ||||
5187 | unsigned bitWidth = result.getBitWidth(); | ||||
5188 | SmallVector<uint64_t, 4> parts(result.getNumWords()); | ||||
5189 | opStatus status = convertToInteger(parts, bitWidth, result.isSigned(), | ||||
5190 | rounding_mode, isExact); | ||||
5191 | // Keeps the original signed-ness. | ||||
5192 | result = APInt(bitWidth, parts); | ||||
5193 | return status; | ||||
5194 | } | ||||
5195 | |||||
5196 | double APFloat::convertToDouble() const { | ||||
5197 | if (&getSemantics() == (const llvm::fltSemantics *)&semIEEEdouble) | ||||
5198 | return getIEEE().convertToDouble(); | ||||
5199 | assert(getSemantics().isRepresentableBy(semIEEEdouble) &&(static_cast <bool> (getSemantics().isRepresentableBy(semIEEEdouble ) && "Float semantics is not representable by IEEEdouble" ) ? void (0) : __assert_fail ("getSemantics().isRepresentableBy(semIEEEdouble) && \"Float semantics is not representable by IEEEdouble\"" , "llvm/lib/Support/APFloat.cpp", 5200, __extension__ __PRETTY_FUNCTION__ )) | ||||
5200 | "Float semantics is not representable by IEEEdouble")(static_cast <bool> (getSemantics().isRepresentableBy(semIEEEdouble ) && "Float semantics is not representable by IEEEdouble" ) ? void (0) : __assert_fail ("getSemantics().isRepresentableBy(semIEEEdouble) && \"Float semantics is not representable by IEEEdouble\"" , "llvm/lib/Support/APFloat.cpp", 5200, __extension__ __PRETTY_FUNCTION__ )); | ||||
5201 | APFloat Temp = *this; | ||||
5202 | bool LosesInfo; | ||||
5203 | opStatus St = Temp.convert(semIEEEdouble, rmNearestTiesToEven, &LosesInfo); | ||||
5204 | assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision")(static_cast <bool> (!(St & opInexact) && ! LosesInfo && "Unexpected imprecision") ? void (0) : __assert_fail ("!(St & opInexact) && !LosesInfo && \"Unexpected imprecision\"" , "llvm/lib/Support/APFloat.cpp", 5204, __extension__ __PRETTY_FUNCTION__ )); | ||||
5205 | (void)St; | ||||
5206 | return Temp.getIEEE().convertToDouble(); | ||||
5207 | } | ||||
5208 | |||||
5209 | float APFloat::convertToFloat() const { | ||||
5210 | if (&getSemantics() == (const llvm::fltSemantics *)&semIEEEsingle) | ||||
| |||||
5211 | return getIEEE().convertToFloat(); | ||||
5212 | assert(getSemantics().isRepresentableBy(semIEEEsingle) &&(static_cast <bool> (getSemantics().isRepresentableBy(semIEEEsingle ) && "Float semantics is not representable by IEEEsingle" ) ? void (0) : __assert_fail ("getSemantics().isRepresentableBy(semIEEEsingle) && \"Float semantics is not representable by IEEEsingle\"" , "llvm/lib/Support/APFloat.cpp", 5213, __extension__ __PRETTY_FUNCTION__ )) | ||||
5213 | "Float semantics is not representable by IEEEsingle")(static_cast <bool> (getSemantics().isRepresentableBy(semIEEEsingle ) && "Float semantics is not representable by IEEEsingle" ) ? void (0) : __assert_fail ("getSemantics().isRepresentableBy(semIEEEsingle) && \"Float semantics is not representable by IEEEsingle\"" , "llvm/lib/Support/APFloat.cpp", 5213, __extension__ __PRETTY_FUNCTION__ )); | ||||
5214 | APFloat Temp = *this; | ||||
5215 | bool LosesInfo; | ||||
5216 | opStatus St = Temp.convert(semIEEEsingle, rmNearestTiesToEven, &LosesInfo); | ||||
5217 | assert(!(St & opInexact) && !LosesInfo && "Unexpected imprecision")(static_cast <bool> (!(St & opInexact) && ! LosesInfo && "Unexpected imprecision") ? void (0) : __assert_fail ("!(St & opInexact) && !LosesInfo && \"Unexpected imprecision\"" , "llvm/lib/Support/APFloat.cpp", 5217, __extension__ __PRETTY_FUNCTION__ )); | ||||
5218 | (void)St; | ||||
5219 | return Temp.getIEEE().convertToFloat(); | ||||
5220 | } | ||||
5221 | |||||
5222 | } // namespace llvm | ||||
5223 | |||||
5224 | #undef APFLOAT_DISPATCH_ON_SEMANTICS |
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/ErrorHandling.h" |
22 | #include <memory> |
23 | |
24 | #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \ |
25 | do { \ |
26 | if (usesLayout<IEEEFloat>(getSemantics())) \ |
27 | return U.IEEE.METHOD_CALL; \ |
28 | if (usesLayout<DoubleAPFloat>(getSemantics())) \ |
29 | return U.Double.METHOD_CALL; \ |
30 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 30); \ |
31 | } while (false) |
32 | |
33 | namespace llvm { |
34 | |
35 | struct fltSemantics; |
36 | class APSInt; |
37 | class StringRef; |
38 | class APFloat; |
39 | class raw_ostream; |
40 | |
41 | template <typename T> class Expected; |
42 | template <typename T> class SmallVectorImpl; |
43 | |
44 | /// Enum that represents what fraction of the LSB truncated bits of an fp number |
45 | /// represent. |
46 | /// |
47 | /// This essentially combines the roles of guard and sticky bits. |
48 | enum lostFraction { // Example of truncated bits: |
49 | lfExactlyZero, // 000000 |
50 | lfLessThanHalf, // 0xxxxx x's not all zero |
51 | lfExactlyHalf, // 100000 |
52 | lfMoreThanHalf // 1xxxxx x's not all zero |
53 | }; |
54 | |
55 | /// A self-contained host- and target-independent arbitrary-precision |
56 | /// floating-point software implementation. |
57 | /// |
58 | /// APFloat uses bignum integer arithmetic as provided by static functions in |
59 | /// the APInt class. The library will work with bignum integers whose parts are |
60 | /// any unsigned type at least 16 bits wide, but 64 bits is recommended. |
61 | /// |
62 | /// Written for clarity rather than speed, in particular with a view to use in |
63 | /// the front-end of a cross compiler so that target arithmetic can be correctly |
64 | /// performed on the host. Performance should nonetheless be reasonable, |
65 | /// particularly for its intended use. It may be useful as a base |
66 | /// implementation for a run-time library during development of a faster |
67 | /// target-specific one. |
68 | /// |
69 | /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all |
70 | /// implemented operations. Currently implemented operations are add, subtract, |
71 | /// multiply, divide, fused-multiply-add, conversion-to-float, |
72 | /// conversion-to-integer and conversion-from-integer. New rounding modes |
73 | /// (e.g. away from zero) can be added with three or four lines of code. |
74 | /// |
75 | /// Four formats are built-in: IEEE single precision, double precision, |
76 | /// quadruple precision, and x87 80-bit extended double (when operating with |
77 | /// full extended precision). Adding a new format that obeys IEEE semantics |
78 | /// only requires adding two lines of code: a declaration and definition of the |
79 | /// format. |
80 | /// |
81 | /// All operations return the status of that operation as an exception bit-mask, |
82 | /// so multiple operations can be done consecutively with their results or-ed |
83 | /// together. The returned status can be useful for compiler diagnostics; e.g., |
84 | /// inexact, underflow and overflow can be easily diagnosed on constant folding, |
85 | /// and compiler optimizers can determine what exceptions would be raised by |
86 | /// folding operations and optimize, or perhaps not optimize, accordingly. |
87 | /// |
88 | /// At present, underflow tininess is detected after rounding; it should be |
89 | /// straight forward to add support for the before-rounding case too. |
90 | /// |
91 | /// The library reads hexadecimal floating point numbers as per C99, and |
92 | /// correctly rounds if necessary according to the specified rounding mode. |
93 | /// Syntax is required to have been validated by the caller. It also converts |
94 | /// floating point numbers to hexadecimal text as per the C99 %a and %A |
95 | /// conversions. The output precision (or alternatively the natural minimal |
96 | /// precision) can be specified; if the requested precision is less than the |
97 | /// natural precision the output is correctly rounded for the specified rounding |
98 | /// mode. |
99 | /// |
100 | /// It also reads decimal floating point numbers and correctly rounds according |
101 | /// to the specified rounding mode. |
102 | /// |
103 | /// Conversion to decimal text is not currently implemented. |
104 | /// |
105 | /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit |
106 | /// signed exponent, and the significand as an array of integer parts. After |
107 | /// normalization of a number of precision P the exponent is within the range of |
108 | /// the format, and if the number is not denormal the P-th bit of the |
109 | /// significand is set as an explicit integer bit. For denormals the most |
110 | /// significant bit is shifted right so that the exponent is maintained at the |
111 | /// format's minimum, so that the smallest denormal has just the least |
112 | /// significant bit of the significand set. The sign of zeroes and infinities |
113 | /// is significant; the exponent and significand of such numbers is not stored, |
114 | /// but has a known implicit (deterministic) value: 0 for the significands, 0 |
115 | /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and |
116 | /// significand are deterministic, although not really meaningful, and preserved |
117 | /// in non-conversion operations. The exponent is implicitly all 1 bits. |
118 | /// |
119 | /// APFloat does not provide any exception handling beyond default exception |
120 | /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause |
121 | /// by encoding Signaling NaNs with the first bit of its trailing significand as |
122 | /// 0. |
123 | /// |
124 | /// TODO |
125 | /// ==== |
126 | /// |
127 | /// Some features that may or may not be worth adding: |
128 | /// |
129 | /// Binary to decimal conversion (hard). |
130 | /// |
131 | /// Optional ability to detect underflow tininess before rounding. |
132 | /// |
133 | /// New formats: x87 in single and double precision mode (IEEE apart from |
134 | /// extended exponent range) (hard). |
135 | /// |
136 | /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward. |
137 | /// |
138 | |
139 | // This is the common type definitions shared by APFloat and its internal |
140 | // implementation classes. This struct should not define any non-static data |
141 | // members. |
142 | struct APFloatBase { |
143 | typedef APInt::WordType integerPart; |
144 | static constexpr unsigned integerPartWidth = APInt::APINT_BITS_PER_WORD; |
145 | |
146 | /// A signed type to represent a floating point numbers unbiased exponent. |
147 | typedef int32_t ExponentType; |
148 | |
149 | /// \name Floating Point Semantics. |
150 | /// @{ |
151 | enum Semantics { |
152 | S_IEEEhalf, |
153 | S_BFloat, |
154 | S_IEEEsingle, |
155 | S_IEEEdouble, |
156 | S_IEEEquad, |
157 | S_PPCDoubleDouble, |
158 | // 8-bit floating point number following IEEE-754 conventions with bit |
159 | // layout S1E5M2 as described in https://arxiv.org/abs/2209.05433. |
160 | S_Float8E5M2, |
161 | // 8-bit floating point number mostly following IEEE-754 conventions |
162 | // and bit layout S1E5M2 described in https://arxiv.org/abs/2206.02915, |
163 | // with expanded range and with no infinity or signed zero. |
164 | // NaN is represented as negative zero. (FN -> Finite, UZ -> unsigned zero). |
165 | // This format's exponent bias is 16, instead of the 15 (2 ** (5 - 1) - 1) |
166 | // that IEEE precedent would imply. |
167 | S_Float8E5M2FNUZ, |
168 | // 8-bit floating point number mostly following IEEE-754 conventions with |
169 | // bit layout S1E4M3 as described in https://arxiv.org/abs/2209.05433. |
170 | // Unlike IEEE-754 types, there are no infinity values, and NaN is |
171 | // represented with the exponent and mantissa bits set to all 1s. |
172 | S_Float8E4M3FN, |
173 | // 8-bit floating point number mostly following IEEE-754 conventions |
174 | // and bit layout S1E4M3 described in https://arxiv.org/abs/2206.02915, |
175 | // with expanded range and with no infinity or signed zero. |
176 | // NaN is represented as negative zero. (FN -> Finite, UZ -> unsigned zero). |
177 | // This format's exponent bias is 8, instead of the 7 (2 ** (4 - 1) - 1) |
178 | // that IEEE precedent would imply. |
179 | S_Float8E4M3FNUZ, |
180 | // 8-bit floating point number mostly following IEEE-754 conventions |
181 | // and bit layout S1E4M3 with expanded range and with no infinity or signed |
182 | // zero. |
183 | // NaN is represented as negative zero. (FN -> Finite, UZ -> unsigned zero). |
184 | // This format's exponent bias is 11, instead of the 7 (2 ** (4 - 1) - 1) |
185 | // that IEEE precedent would imply. |
186 | S_Float8E4M3B11FNUZ, |
187 | |
188 | S_x87DoubleExtended, |
189 | S_MaxSemantics = S_x87DoubleExtended, |
190 | }; |
191 | |
192 | static const llvm::fltSemantics &EnumToSemantics(Semantics S); |
193 | static Semantics SemanticsToEnum(const llvm::fltSemantics &Sem); |
194 | |
195 | static const fltSemantics &IEEEhalf() LLVM_READNONE__attribute__((__const__)); |
196 | static const fltSemantics &BFloat() LLVM_READNONE__attribute__((__const__)); |
197 | static const fltSemantics &IEEEsingle() LLVM_READNONE__attribute__((__const__)); |
198 | static const fltSemantics &IEEEdouble() LLVM_READNONE__attribute__((__const__)); |
199 | static const fltSemantics &IEEEquad() LLVM_READNONE__attribute__((__const__)); |
200 | static const fltSemantics &PPCDoubleDouble() LLVM_READNONE__attribute__((__const__)); |
201 | static const fltSemantics &Float8E5M2() LLVM_READNONE__attribute__((__const__)); |
202 | static const fltSemantics &Float8E5M2FNUZ() LLVM_READNONE__attribute__((__const__)); |
203 | static const fltSemantics &Float8E4M3FN() LLVM_READNONE__attribute__((__const__)); |
204 | static const fltSemantics &Float8E4M3FNUZ() LLVM_READNONE__attribute__((__const__)); |
205 | static const fltSemantics &Float8E4M3B11FNUZ() LLVM_READNONE__attribute__((__const__)); |
206 | static const fltSemantics &x87DoubleExtended() LLVM_READNONE__attribute__((__const__)); |
207 | |
208 | /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with |
209 | /// anything real. |
210 | static const fltSemantics &Bogus() LLVM_READNONE__attribute__((__const__)); |
211 | |
212 | /// @} |
213 | |
214 | /// IEEE-754R 5.11: Floating Point Comparison Relations. |
215 | enum cmpResult { |
216 | cmpLessThan, |
217 | cmpEqual, |
218 | cmpGreaterThan, |
219 | cmpUnordered |
220 | }; |
221 | |
222 | /// IEEE-754R 4.3: Rounding-direction attributes. |
223 | using roundingMode = llvm::RoundingMode; |
224 | |
225 | static constexpr roundingMode rmNearestTiesToEven = |
226 | RoundingMode::NearestTiesToEven; |
227 | static constexpr roundingMode rmTowardPositive = RoundingMode::TowardPositive; |
228 | static constexpr roundingMode rmTowardNegative = RoundingMode::TowardNegative; |
229 | static constexpr roundingMode rmTowardZero = RoundingMode::TowardZero; |
230 | static constexpr roundingMode rmNearestTiesToAway = |
231 | RoundingMode::NearestTiesToAway; |
232 | |
233 | /// IEEE-754R 7: Default exception handling. |
234 | /// |
235 | /// opUnderflow or opOverflow are always returned or-ed with opInexact. |
236 | /// |
237 | /// APFloat models this behavior specified by IEEE-754: |
238 | /// "For operations producing results in floating-point format, the default |
239 | /// result of an operation that signals the invalid operation exception |
240 | /// shall be a quiet NaN." |
241 | enum opStatus { |
242 | opOK = 0x00, |
243 | opInvalidOp = 0x01, |
244 | opDivByZero = 0x02, |
245 | opOverflow = 0x04, |
246 | opUnderflow = 0x08, |
247 | opInexact = 0x10 |
248 | }; |
249 | |
250 | /// Category of internally-represented number. |
251 | enum fltCategory { |
252 | fcInfinity, |
253 | fcNaN, |
254 | fcNormal, |
255 | fcZero |
256 | }; |
257 | |
258 | /// Convenience enum used to construct an uninitialized APFloat. |
259 | enum uninitializedTag { |
260 | uninitialized |
261 | }; |
262 | |
263 | /// Enumeration of \c ilogb error results. |
264 | enum IlogbErrorKinds { |
265 | IEK_Zero = INT_MIN(-2147483647 -1) + 1, |
266 | IEK_NaN = INT_MIN(-2147483647 -1), |
267 | IEK_Inf = INT_MAX2147483647 |
268 | }; |
269 | |
270 | static unsigned int semanticsPrecision(const fltSemantics &); |
271 | static ExponentType semanticsMinExponent(const fltSemantics &); |
272 | static ExponentType semanticsMaxExponent(const fltSemantics &); |
273 | static unsigned int semanticsSizeInBits(const fltSemantics &); |
274 | static unsigned int semanticsIntSizeInBits(const fltSemantics&, bool); |
275 | |
276 | // Returns true if any number described by \p Src can be precisely represented |
277 | // by a normal (not subnormal) value in \p Dst. |
278 | static bool isRepresentableAsNormalIn(const fltSemantics &Src, |
279 | const fltSemantics &Dst); |
280 | |
281 | /// Returns the size of the floating point number (in bits) in the given |
282 | /// semantics. |
283 | static unsigned getSizeInBits(const fltSemantics &Sem); |
284 | }; |
285 | |
286 | namespace detail { |
287 | |
288 | class IEEEFloat final : public APFloatBase { |
289 | public: |
290 | /// \name Constructors |
291 | /// @{ |
292 | |
293 | IEEEFloat(const fltSemantics &); // Default construct to +0.0 |
294 | IEEEFloat(const fltSemantics &, integerPart); |
295 | IEEEFloat(const fltSemantics &, uninitializedTag); |
296 | IEEEFloat(const fltSemantics &, const APInt &); |
297 | explicit IEEEFloat(double d); |
298 | explicit IEEEFloat(float f); |
299 | IEEEFloat(const IEEEFloat &); |
300 | IEEEFloat(IEEEFloat &&); |
301 | ~IEEEFloat(); |
302 | |
303 | /// @} |
304 | |
305 | /// Returns whether this instance allocated memory. |
306 | bool needsCleanup() const { return partCount() > 1; } |
307 | |
308 | /// \name Convenience "constructors" |
309 | /// @{ |
310 | |
311 | /// @} |
312 | |
313 | /// \name Arithmetic |
314 | /// @{ |
315 | |
316 | opStatus add(const IEEEFloat &, roundingMode); |
317 | opStatus subtract(const IEEEFloat &, roundingMode); |
318 | opStatus multiply(const IEEEFloat &, roundingMode); |
319 | opStatus divide(const IEEEFloat &, roundingMode); |
320 | /// IEEE remainder. |
321 | opStatus remainder(const IEEEFloat &); |
322 | /// C fmod, or llvm frem. |
323 | opStatus mod(const IEEEFloat &); |
324 | opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode); |
325 | opStatus roundToIntegral(roundingMode); |
326 | /// IEEE-754R 5.3.1: nextUp/nextDown. |
327 | opStatus next(bool nextDown); |
328 | |
329 | /// @} |
330 | |
331 | /// \name Sign operations. |
332 | /// @{ |
333 | |
334 | void changeSign(); |
335 | |
336 | /// @} |
337 | |
338 | /// \name Conversions |
339 | /// @{ |
340 | |
341 | opStatus convert(const fltSemantics &, roundingMode, bool *); |
342 | opStatus convertToInteger(MutableArrayRef<integerPart>, unsigned int, bool, |
343 | roundingMode, bool *) const; |
344 | opStatus convertFromAPInt(const APInt &, bool, roundingMode); |
345 | opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int, |
346 | bool, roundingMode); |
347 | opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int, |
348 | bool, roundingMode); |
349 | Expected<opStatus> convertFromString(StringRef, roundingMode); |
350 | APInt bitcastToAPInt() const; |
351 | double convertToDouble() const; |
352 | float convertToFloat() const; |
353 | |
354 | /// @} |
355 | |
356 | /// The definition of equality is not straightforward for floating point, so |
357 | /// we won't use operator==. Use one of the following, or write whatever it |
358 | /// is you really mean. |
359 | bool operator==(const IEEEFloat &) const = delete; |
360 | |
361 | /// IEEE comparison with another floating point number (NaNs compare |
362 | /// unordered, 0==-0). |
363 | cmpResult compare(const IEEEFloat &) const; |
364 | |
365 | /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0). |
366 | bool bitwiseIsEqual(const IEEEFloat &) const; |
367 | |
368 | /// Write out a hexadecimal representation of the floating point value to DST, |
369 | /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d. |
370 | /// Return the number of characters written, excluding the terminating NUL. |
371 | unsigned int convertToHexString(char *dst, unsigned int hexDigits, |
372 | bool upperCase, roundingMode) const; |
373 | |
374 | /// \name IEEE-754R 5.7.2 General operations. |
375 | /// @{ |
376 | |
377 | /// IEEE-754R isSignMinus: Returns true if and only if the current value is |
378 | /// negative. |
379 | /// |
380 | /// This applies to zeros and NaNs as well. |
381 | bool isNegative() const { return sign; } |
382 | |
383 | /// IEEE-754R isNormal: Returns true if and only if the current value is normal. |
384 | /// |
385 | /// This implies that the current value of the float is not zero, subnormal, |
386 | /// infinite, or NaN following the definition of normality from IEEE-754R. |
387 | bool isNormal() const { return !isDenormal() && isFiniteNonZero(); } |
388 | |
389 | /// Returns true if and only if the current value is zero, subnormal, or |
390 | /// normal. |
391 | /// |
392 | /// This means that the value is not infinite or NaN. |
393 | bool isFinite() const { return !isNaN() && !isInfinity(); } |
394 | |
395 | /// Returns true if and only if the float is plus or minus zero. |
396 | bool isZero() const { return category == fcZero; } |
397 | |
398 | /// IEEE-754R isSubnormal(): Returns true if and only if the float is a |
399 | /// denormal. |
400 | bool isDenormal() const; |
401 | |
402 | /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity. |
403 | bool isInfinity() const { return category == fcInfinity; } |
404 | |
405 | /// Returns true if and only if the float is a quiet or signaling NaN. |
406 | bool isNaN() const { return category == fcNaN; } |
407 | |
408 | /// Returns true if and only if the float is a signaling NaN. |
409 | bool isSignaling() const; |
410 | |
411 | /// @} |
412 | |
413 | /// \name Simple Queries |
414 | /// @{ |
415 | |
416 | fltCategory getCategory() const { return category; } |
417 | const fltSemantics &getSemantics() const { return *semantics; } |
418 | bool isNonZero() const { return category != fcZero; } |
419 | bool isFiniteNonZero() const { return isFinite() && !isZero(); } |
420 | bool isPosZero() const { return isZero() && !isNegative(); } |
421 | bool isNegZero() const { return isZero() && isNegative(); } |
422 | |
423 | /// Returns true if and only if the number has the smallest possible non-zero |
424 | /// magnitude in the current semantics. |
425 | bool isSmallest() const; |
426 | |
427 | /// Returns true if this is the smallest (by magnitude) normalized finite |
428 | /// number in the given semantics. |
429 | bool isSmallestNormalized() const; |
430 | |
431 | /// Returns true if and only if the number has the largest possible finite |
432 | /// magnitude in the current semantics. |
433 | bool isLargest() const; |
434 | |
435 | /// Returns true if and only if the number is an exact integer. |
436 | bool isInteger() const; |
437 | |
438 | /// @} |
439 | |
440 | IEEEFloat &operator=(const IEEEFloat &); |
441 | IEEEFloat &operator=(IEEEFloat &&); |
442 | |
443 | /// Overload to compute a hash code for an APFloat value. |
444 | /// |
445 | /// Note that the use of hash codes for floating point values is in general |
446 | /// frought with peril. Equality is hard to define for these values. For |
447 | /// example, should negative and positive zero hash to different codes? Are |
448 | /// they equal or not? This hash value implementation specifically |
449 | /// emphasizes producing different codes for different inputs in order to |
450 | /// be used in canonicalization and memoization. As such, equality is |
451 | /// bitwiseIsEqual, and 0 != -0. |
452 | friend hash_code hash_value(const IEEEFloat &Arg); |
453 | |
454 | /// Converts this value into a decimal string. |
455 | /// |
456 | /// \param FormatPrecision The maximum number of digits of |
457 | /// precision to output. If there are fewer digits available, |
458 | /// zero padding will not be used unless the value is |
459 | /// integral and small enough to be expressed in |
460 | /// FormatPrecision digits. 0 means to use the natural |
461 | /// precision of the number. |
462 | /// \param FormatMaxPadding The maximum number of zeros to |
463 | /// consider inserting before falling back to scientific |
464 | /// notation. 0 means to always use scientific notation. |
465 | /// |
466 | /// \param TruncateZero Indicate whether to remove the trailing zero in |
467 | /// fraction part or not. Also setting this parameter to false forcing |
468 | /// producing of output more similar to default printf behavior. |
469 | /// Specifically the lower e is used as exponent delimiter and exponent |
470 | /// always contains no less than two digits. |
471 | /// |
472 | /// Number Precision MaxPadding Result |
473 | /// ------ --------- ---------- ------ |
474 | /// 1.01E+4 5 2 10100 |
475 | /// 1.01E+4 4 2 1.01E+4 |
476 | /// 1.01E+4 5 1 1.01E+4 |
477 | /// 1.01E-2 5 2 0.0101 |
478 | /// 1.01E-2 4 2 0.0101 |
479 | /// 1.01E-2 4 1 1.01E-2 |
480 | void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0, |
481 | unsigned FormatMaxPadding = 3, bool TruncateZero = true) const; |
482 | |
483 | /// If this value has an exact multiplicative inverse, store it in inv and |
484 | /// return true. |
485 | bool getExactInverse(APFloat *inv) const; |
486 | |
487 | /// Returns the exponent of the internal representation of the APFloat. |
488 | /// |
489 | /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)). |
490 | /// For special APFloat values, this returns special error codes: |
491 | /// |
492 | /// NaN -> \c IEK_NaN |
493 | /// 0 -> \c IEK_Zero |
494 | /// Inf -> \c IEK_Inf |
495 | /// |
496 | friend int ilogb(const IEEEFloat &Arg); |
497 | |
498 | /// Returns: X * 2^Exp for integral exponents. |
499 | friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode); |
500 | |
501 | friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode); |
502 | |
503 | /// \name Special value setters. |
504 | /// @{ |
505 | |
506 | void makeLargest(bool Neg = false); |
507 | void makeSmallest(bool Neg = false); |
508 | void makeNaN(bool SNaN = false, bool Neg = false, |
509 | const APInt *fill = nullptr); |
510 | void makeInf(bool Neg = false); |
511 | void makeZero(bool Neg = false); |
512 | void makeQuiet(); |
513 | |
514 | /// Returns the smallest (by magnitude) normalized finite number in the given |
515 | /// semantics. |
516 | /// |
517 | /// \param Negative - True iff the number should be negative |
518 | void makeSmallestNormalized(bool Negative = false); |
519 | |
520 | /// @} |
521 | |
522 | cmpResult compareAbsoluteValue(const IEEEFloat &) const; |
523 | |
524 | private: |
525 | /// \name Simple Queries |
526 | /// @{ |
527 | |
528 | integerPart *significandParts(); |
529 | const integerPart *significandParts() const; |
530 | unsigned int partCount() const; |
531 | |
532 | /// @} |
533 | |
534 | /// \name Significand operations. |
535 | /// @{ |
536 | |
537 | integerPart addSignificand(const IEEEFloat &); |
538 | integerPart subtractSignificand(const IEEEFloat &, integerPart); |
539 | lostFraction addOrSubtractSignificand(const IEEEFloat &, bool subtract); |
540 | lostFraction multiplySignificand(const IEEEFloat &, IEEEFloat); |
541 | lostFraction multiplySignificand(const IEEEFloat&); |
542 | lostFraction divideSignificand(const IEEEFloat &); |
543 | void incrementSignificand(); |
544 | void initialize(const fltSemantics *); |
545 | void shiftSignificandLeft(unsigned int); |
546 | lostFraction shiftSignificandRight(unsigned int); |
547 | unsigned int significandLSB() const; |
548 | unsigned int significandMSB() const; |
549 | void zeroSignificand(); |
550 | /// Return true if the significand excluding the integral bit is all ones. |
551 | bool isSignificandAllOnes() const; |
552 | bool isSignificandAllOnesExceptLSB() const; |
553 | /// Return true if the significand excluding the integral bit is all zeros. |
554 | bool isSignificandAllZeros() const; |
555 | bool isSignificandAllZerosExceptMSB() const; |
556 | |
557 | /// @} |
558 | |
559 | /// \name Arithmetic on special values. |
560 | /// @{ |
561 | |
562 | opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract); |
563 | opStatus divideSpecials(const IEEEFloat &); |
564 | opStatus multiplySpecials(const IEEEFloat &); |
565 | opStatus modSpecials(const IEEEFloat &); |
566 | opStatus remainderSpecials(const IEEEFloat&); |
567 | |
568 | /// @} |
569 | |
570 | /// \name Miscellany |
571 | /// @{ |
572 | |
573 | bool convertFromStringSpecials(StringRef str); |
574 | opStatus normalize(roundingMode, lostFraction); |
575 | opStatus addOrSubtract(const IEEEFloat &, roundingMode, bool subtract); |
576 | opStatus handleOverflow(roundingMode); |
577 | bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const; |
578 | opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart>, |
579 | unsigned int, bool, roundingMode, |
580 | bool *) const; |
581 | opStatus convertFromUnsignedParts(const integerPart *, unsigned int, |
582 | roundingMode); |
583 | Expected<opStatus> convertFromHexadecimalString(StringRef, roundingMode); |
584 | Expected<opStatus> convertFromDecimalString(StringRef, roundingMode); |
585 | char *convertNormalToHexString(char *, unsigned int, bool, |
586 | roundingMode) const; |
587 | opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int, |
588 | roundingMode); |
589 | ExponentType exponentNaN() const; |
590 | ExponentType exponentInf() const; |
591 | ExponentType exponentZero() const; |
592 | |
593 | /// @} |
594 | |
595 | template <const fltSemantics &S> APInt convertIEEEFloatToAPInt() const; |
596 | APInt convertHalfAPFloatToAPInt() const; |
597 | APInt convertBFloatAPFloatToAPInt() const; |
598 | APInt convertFloatAPFloatToAPInt() const; |
599 | APInt convertDoubleAPFloatToAPInt() const; |
600 | APInt convertQuadrupleAPFloatToAPInt() const; |
601 | APInt convertF80LongDoubleAPFloatToAPInt() const; |
602 | APInt convertPPCDoubleDoubleAPFloatToAPInt() const; |
603 | APInt convertFloat8E5M2APFloatToAPInt() const; |
604 | APInt convertFloat8E5M2FNUZAPFloatToAPInt() const; |
605 | APInt convertFloat8E4M3FNAPFloatToAPInt() const; |
606 | APInt convertFloat8E4M3FNUZAPFloatToAPInt() const; |
607 | APInt convertFloat8E4M3B11FNUZAPFloatToAPInt() const; |
608 | void initFromAPInt(const fltSemantics *Sem, const APInt &api); |
609 | template <const fltSemantics &S> void initFromIEEEAPInt(const APInt &api); |
610 | void initFromHalfAPInt(const APInt &api); |
611 | void initFromBFloatAPInt(const APInt &api); |
612 | void initFromFloatAPInt(const APInt &api); |
613 | void initFromDoubleAPInt(const APInt &api); |
614 | void initFromQuadrupleAPInt(const APInt &api); |
615 | void initFromF80LongDoubleAPInt(const APInt &api); |
616 | void initFromPPCDoubleDoubleAPInt(const APInt &api); |
617 | void initFromFloat8E5M2APInt(const APInt &api); |
618 | void initFromFloat8E5M2FNUZAPInt(const APInt &api); |
619 | void initFromFloat8E4M3FNAPInt(const APInt &api); |
620 | void initFromFloat8E4M3FNUZAPInt(const APInt &api); |
621 | void initFromFloat8E4M3B11FNUZAPInt(const APInt &api); |
622 | |
623 | void assign(const IEEEFloat &); |
624 | void copySignificand(const IEEEFloat &); |
625 | void freeSignificand(); |
626 | |
627 | /// Note: this must be the first data member. |
628 | /// The semantics that this value obeys. |
629 | const fltSemantics *semantics; |
630 | |
631 | /// A binary fraction with an explicit integer bit. |
632 | /// |
633 | /// The significand must be at least one bit wider than the target precision. |
634 | union Significand { |
635 | integerPart part; |
636 | integerPart *parts; |
637 | } significand; |
638 | |
639 | /// The signed unbiased exponent of the value. |
640 | ExponentType exponent; |
641 | |
642 | /// What kind of floating point number this is. |
643 | /// |
644 | /// Only 2 bits are required, but VisualStudio incorrectly sign extends it. |
645 | /// Using the extra bit keeps it from failing under VisualStudio. |
646 | fltCategory category : 3; |
647 | |
648 | /// Sign bit of the number. |
649 | unsigned int sign : 1; |
650 | }; |
651 | |
652 | hash_code hash_value(const IEEEFloat &Arg); |
653 | int ilogb(const IEEEFloat &Arg); |
654 | IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode); |
655 | IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM); |
656 | |
657 | // This mode implements more precise float in terms of two APFloats. |
658 | // The interface and layout is designed for arbitrary underlying semantics, |
659 | // though currently only PPCDoubleDouble semantics are supported, whose |
660 | // corresponding underlying semantics are IEEEdouble. |
661 | class DoubleAPFloat final : public APFloatBase { |
662 | // Note: this must be the first data member. |
663 | const fltSemantics *Semantics; |
664 | std::unique_ptr<APFloat[]> Floats; |
665 | |
666 | opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c, |
667 | const APFloat &cc, roundingMode RM); |
668 | |
669 | opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS, |
670 | DoubleAPFloat &Out, roundingMode RM); |
671 | |
672 | public: |
673 | DoubleAPFloat(const fltSemantics &S); |
674 | DoubleAPFloat(const fltSemantics &S, uninitializedTag); |
675 | DoubleAPFloat(const fltSemantics &S, integerPart); |
676 | DoubleAPFloat(const fltSemantics &S, const APInt &I); |
677 | DoubleAPFloat(const fltSemantics &S, APFloat &&First, APFloat &&Second); |
678 | DoubleAPFloat(const DoubleAPFloat &RHS); |
679 | DoubleAPFloat(DoubleAPFloat &&RHS); |
680 | |
681 | DoubleAPFloat &operator=(const DoubleAPFloat &RHS); |
682 | |
683 | DoubleAPFloat &operator=(DoubleAPFloat &&RHS) { |
684 | if (this != &RHS) { |
685 | this->~DoubleAPFloat(); |
686 | new (this) DoubleAPFloat(std::move(RHS)); |
687 | } |
688 | return *this; |
689 | } |
690 | |
691 | bool needsCleanup() const { return Floats != nullptr; } |
692 | |
693 | APFloat &getFirst() { return Floats[0]; } |
694 | const APFloat &getFirst() const { return Floats[0]; } |
695 | APFloat &getSecond() { return Floats[1]; } |
696 | const APFloat &getSecond() const { return Floats[1]; } |
697 | |
698 | opStatus add(const DoubleAPFloat &RHS, roundingMode RM); |
699 | opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM); |
700 | opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM); |
701 | opStatus divide(const DoubleAPFloat &RHS, roundingMode RM); |
702 | opStatus remainder(const DoubleAPFloat &RHS); |
703 | opStatus mod(const DoubleAPFloat &RHS); |
704 | opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, |
705 | const DoubleAPFloat &Addend, roundingMode RM); |
706 | opStatus roundToIntegral(roundingMode RM); |
707 | void changeSign(); |
708 | cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const; |
709 | |
710 | fltCategory getCategory() const; |
711 | bool isNegative() const; |
712 | |
713 | void makeInf(bool Neg); |
714 | void makeZero(bool Neg); |
715 | void makeLargest(bool Neg); |
716 | void makeSmallest(bool Neg); |
717 | void makeSmallestNormalized(bool Neg); |
718 | void makeNaN(bool SNaN, bool Neg, const APInt *fill); |
719 | |
720 | cmpResult compare(const DoubleAPFloat &RHS) const; |
721 | bool bitwiseIsEqual(const DoubleAPFloat &RHS) const; |
722 | APInt bitcastToAPInt() const; |
723 | Expected<opStatus> convertFromString(StringRef, roundingMode); |
724 | opStatus next(bool nextDown); |
725 | |
726 | opStatus convertToInteger(MutableArrayRef<integerPart> Input, |
727 | unsigned int Width, bool IsSigned, roundingMode RM, |
728 | bool *IsExact) const; |
729 | opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM); |
730 | opStatus convertFromSignExtendedInteger(const integerPart *Input, |
731 | unsigned int InputSize, bool IsSigned, |
732 | roundingMode RM); |
733 | opStatus convertFromZeroExtendedInteger(const integerPart *Input, |
734 | unsigned int InputSize, bool IsSigned, |
735 | roundingMode RM); |
736 | unsigned int convertToHexString(char *DST, unsigned int HexDigits, |
737 | bool UpperCase, roundingMode RM) const; |
738 | |
739 | bool isDenormal() const; |
740 | bool isSmallest() const; |
741 | bool isSmallestNormalized() const; |
742 | bool isLargest() const; |
743 | bool isInteger() const; |
744 | |
745 | void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision, |
746 | unsigned FormatMaxPadding, bool TruncateZero = true) const; |
747 | |
748 | bool getExactInverse(APFloat *inv) const; |
749 | |
750 | friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp, roundingMode); |
751 | friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp, roundingMode); |
752 | friend hash_code hash_value(const DoubleAPFloat &Arg); |
753 | }; |
754 | |
755 | hash_code hash_value(const DoubleAPFloat &Arg); |
756 | |
757 | } // End detail namespace |
758 | |
759 | // This is a interface class that is currently forwarding functionalities from |
760 | // detail::IEEEFloat. |
761 | class APFloat : public APFloatBase { |
762 | typedef detail::IEEEFloat IEEEFloat; |
763 | typedef detail::DoubleAPFloat DoubleAPFloat; |
764 | |
765 | static_assert(std::is_standard_layout<IEEEFloat>::value); |
766 | |
767 | union Storage { |
768 | const fltSemantics *semantics; |
769 | IEEEFloat IEEE; |
770 | DoubleAPFloat Double; |
771 | |
772 | explicit Storage(IEEEFloat F, const fltSemantics &S); |
773 | explicit Storage(DoubleAPFloat F, const fltSemantics &S) |
774 | : Double(std::move(F)) { |
775 | assert(&S == &PPCDoubleDouble())(static_cast <bool> (&S == &PPCDoubleDouble()) ? void (0) : __assert_fail ("&S == &PPCDoubleDouble()" , "llvm/include/llvm/ADT/APFloat.h", 775, __extension__ __PRETTY_FUNCTION__ )); |
776 | } |
777 | |
778 | template <typename... ArgTypes> |
779 | Storage(const fltSemantics &Semantics, ArgTypes &&... Args) { |
780 | if (usesLayout<IEEEFloat>(Semantics)) { |
781 | new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...); |
782 | return; |
783 | } |
784 | if (usesLayout<DoubleAPFloat>(Semantics)) { |
785 | new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...); |
786 | return; |
787 | } |
788 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 788); |
789 | } |
790 | |
791 | ~Storage() { |
792 | if (usesLayout<IEEEFloat>(*semantics)) { |
793 | IEEE.~IEEEFloat(); |
794 | return; |
795 | } |
796 | if (usesLayout<DoubleAPFloat>(*semantics)) { |
797 | Double.~DoubleAPFloat(); |
798 | return; |
799 | } |
800 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 800); |
801 | } |
802 | |
803 | Storage(const Storage &RHS) { |
804 | if (usesLayout<IEEEFloat>(*RHS.semantics)) { |
805 | new (this) IEEEFloat(RHS.IEEE); |
806 | return; |
807 | } |
808 | if (usesLayout<DoubleAPFloat>(*RHS.semantics)) { |
809 | new (this) DoubleAPFloat(RHS.Double); |
810 | return; |
811 | } |
812 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 812); |
813 | } |
814 | |
815 | Storage(Storage &&RHS) { |
816 | if (usesLayout<IEEEFloat>(*RHS.semantics)) { |
817 | new (this) IEEEFloat(std::move(RHS.IEEE)); |
818 | return; |
819 | } |
820 | if (usesLayout<DoubleAPFloat>(*RHS.semantics)) { |
821 | new (this) DoubleAPFloat(std::move(RHS.Double)); |
822 | return; |
823 | } |
824 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 824); |
825 | } |
826 | |
827 | Storage &operator=(const Storage &RHS) { |
828 | if (usesLayout<IEEEFloat>(*semantics) && |
829 | usesLayout<IEEEFloat>(*RHS.semantics)) { |
830 | IEEE = RHS.IEEE; |
831 | } else if (usesLayout<DoubleAPFloat>(*semantics) && |
832 | usesLayout<DoubleAPFloat>(*RHS.semantics)) { |
833 | Double = RHS.Double; |
834 | } else if (this != &RHS) { |
835 | this->~Storage(); |
836 | new (this) Storage(RHS); |
837 | } |
838 | return *this; |
839 | } |
840 | |
841 | Storage &operator=(Storage &&RHS) { |
842 | if (usesLayout<IEEEFloat>(*semantics) && |
843 | usesLayout<IEEEFloat>(*RHS.semantics)) { |
844 | IEEE = std::move(RHS.IEEE); |
845 | } else if (usesLayout<DoubleAPFloat>(*semantics) && |
846 | usesLayout<DoubleAPFloat>(*RHS.semantics)) { |
847 | Double = std::move(RHS.Double); |
848 | } else if (this != &RHS) { |
849 | this->~Storage(); |
850 | new (this) Storage(std::move(RHS)); |
851 | } |
852 | return *this; |
853 | } |
854 | } U; |
855 | |
856 | template <typename T> static bool usesLayout(const fltSemantics &Semantics) { |
857 | static_assert(std::is_same<T, IEEEFloat>::value || |
858 | std::is_same<T, DoubleAPFloat>::value); |
859 | if (std::is_same<T, DoubleAPFloat>::value) { |
860 | return &Semantics == &PPCDoubleDouble(); |
861 | } |
862 | return &Semantics != &PPCDoubleDouble(); |
863 | } |
864 | |
865 | IEEEFloat &getIEEE() { |
866 | if (usesLayout<IEEEFloat>(*U.semantics)) |
867 | return U.IEEE; |
868 | if (usesLayout<DoubleAPFloat>(*U.semantics)) |
869 | return U.Double.getFirst().U.IEEE; |
870 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 870); |
871 | } |
872 | |
873 | const IEEEFloat &getIEEE() const { |
874 | if (usesLayout<IEEEFloat>(*U.semantics)) |
875 | return U.IEEE; |
876 | if (usesLayout<DoubleAPFloat>(*U.semantics)) |
877 | return U.Double.getFirst().U.IEEE; |
878 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 878); |
879 | } |
880 | |
881 | void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); } |
882 | |
883 | void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); } |
884 | |
885 | void makeNaN(bool SNaN, bool Neg, const APInt *fill) { |
886 | APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill)); |
887 | } |
888 | |
889 | void makeLargest(bool Neg) { |
890 | APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg)); |
891 | } |
892 | |
893 | void makeSmallest(bool Neg) { |
894 | APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg)); |
895 | } |
896 | |
897 | void makeSmallestNormalized(bool Neg) { |
898 | APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg)); |
899 | } |
900 | |
901 | explicit APFloat(IEEEFloat F, const fltSemantics &S) : U(std::move(F), S) {} |
902 | explicit APFloat(DoubleAPFloat F, const fltSemantics &S) |
903 | : U(std::move(F), S) {} |
904 | |
905 | cmpResult compareAbsoluteValue(const APFloat &RHS) const { |
906 | assert(&getSemantics() == &RHS.getSemantics() &&(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only compare APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only compare APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 907, __extension__ __PRETTY_FUNCTION__ )) |
907 | "Should only compare APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only compare APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only compare APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 907, __extension__ __PRETTY_FUNCTION__ )); |
908 | if (usesLayout<IEEEFloat>(getSemantics())) |
909 | return U.IEEE.compareAbsoluteValue(RHS.U.IEEE); |
910 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
911 | return U.Double.compareAbsoluteValue(RHS.U.Double); |
912 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 912); |
913 | } |
914 | |
915 | public: |
916 | APFloat(const fltSemantics &Semantics) : U(Semantics) {} |
917 | APFloat(const fltSemantics &Semantics, StringRef S); |
918 | APFloat(const fltSemantics &Semantics, integerPart I) : U(Semantics, I) {} |
919 | template <typename T, |
920 | typename = std::enable_if_t<std::is_floating_point<T>::value>> |
921 | APFloat(const fltSemantics &Semantics, T V) = delete; |
922 | // TODO: Remove this constructor. This isn't faster than the first one. |
923 | APFloat(const fltSemantics &Semantics, uninitializedTag) |
924 | : U(Semantics, uninitialized) {} |
925 | APFloat(const fltSemantics &Semantics, const APInt &I) : U(Semantics, I) {} |
926 | explicit APFloat(double d) : U(IEEEFloat(d), IEEEdouble()) {} |
927 | explicit APFloat(float f) : U(IEEEFloat(f), IEEEsingle()) {} |
928 | APFloat(const APFloat &RHS) = default; |
929 | APFloat(APFloat &&RHS) = default; |
930 | |
931 | ~APFloat() = default; |
932 | |
933 | bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); } |
934 | |
935 | /// Factory for Positive and Negative Zero. |
936 | /// |
937 | /// \param Negative True iff the number should be negative. |
938 | static APFloat getZero(const fltSemantics &Sem, bool Negative = false) { |
939 | APFloat Val(Sem, uninitialized); |
940 | Val.makeZero(Negative); |
941 | return Val; |
942 | } |
943 | |
944 | /// Factory for Positive and Negative Infinity. |
945 | /// |
946 | /// \param Negative True iff the number should be negative. |
947 | static APFloat getInf(const fltSemantics &Sem, bool Negative = false) { |
948 | APFloat Val(Sem, uninitialized); |
949 | Val.makeInf(Negative); |
950 | return Val; |
951 | } |
952 | |
953 | /// Factory for NaN values. |
954 | /// |
955 | /// \param Negative - True iff the NaN generated should be negative. |
956 | /// \param payload - The unspecified fill bits for creating the NaN, 0 by |
957 | /// default. The value is truncated as necessary. |
958 | static APFloat getNaN(const fltSemantics &Sem, bool Negative = false, |
959 | uint64_t payload = 0) { |
960 | if (payload) { |
961 | APInt intPayload(64, payload); |
962 | return getQNaN(Sem, Negative, &intPayload); |
963 | } else { |
964 | return getQNaN(Sem, Negative, nullptr); |
965 | } |
966 | } |
967 | |
968 | /// Factory for QNaN values. |
969 | static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false, |
970 | const APInt *payload = nullptr) { |
971 | APFloat Val(Sem, uninitialized); |
972 | Val.makeNaN(false, Negative, payload); |
973 | return Val; |
974 | } |
975 | |
976 | /// Factory for SNaN values. |
977 | static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false, |
978 | const APInt *payload = nullptr) { |
979 | APFloat Val(Sem, uninitialized); |
980 | Val.makeNaN(true, Negative, payload); |
981 | return Val; |
982 | } |
983 | |
984 | /// Returns the largest finite number in the given semantics. |
985 | /// |
986 | /// \param Negative - True iff the number should be negative |
987 | static APFloat getLargest(const fltSemantics &Sem, bool Negative = false) { |
988 | APFloat Val(Sem, uninitialized); |
989 | Val.makeLargest(Negative); |
990 | return Val; |
991 | } |
992 | |
993 | /// Returns the smallest (by magnitude) finite number in the given semantics. |
994 | /// Might be denormalized, which implies a relative loss of precision. |
995 | /// |
996 | /// \param Negative - True iff the number should be negative |
997 | static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false) { |
998 | APFloat Val(Sem, uninitialized); |
999 | Val.makeSmallest(Negative); |
1000 | return Val; |
1001 | } |
1002 | |
1003 | /// Returns the smallest (by magnitude) normalized finite number in the given |
1004 | /// semantics. |
1005 | /// |
1006 | /// \param Negative - True iff the number should be negative |
1007 | static APFloat getSmallestNormalized(const fltSemantics &Sem, |
1008 | bool Negative = false) { |
1009 | APFloat Val(Sem, uninitialized); |
1010 | Val.makeSmallestNormalized(Negative); |
1011 | return Val; |
1012 | } |
1013 | |
1014 | /// Returns a float which is bitcasted from an all one value int. |
1015 | /// |
1016 | /// \param Semantics - type float semantics |
1017 | static APFloat getAllOnesValue(const fltSemantics &Semantics); |
1018 | |
1019 | /// Used to insert APFloat objects, or objects that contain APFloat objects, |
1020 | /// into FoldingSets. |
1021 | void Profile(FoldingSetNodeID &NID) const; |
1022 | |
1023 | opStatus add(const APFloat &RHS, roundingMode RM) { |
1024 | assert(&getSemantics() == &RHS.getSemantics() &&(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1025, __extension__ __PRETTY_FUNCTION__ )) |
1025 | "Should only call on two APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1025, __extension__ __PRETTY_FUNCTION__ )); |
1026 | if (usesLayout<IEEEFloat>(getSemantics())) |
1027 | return U.IEEE.add(RHS.U.IEEE, RM); |
1028 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
1029 | return U.Double.add(RHS.U.Double, RM); |
1030 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1030); |
1031 | } |
1032 | opStatus subtract(const APFloat &RHS, roundingMode RM) { |
1033 | assert(&getSemantics() == &RHS.getSemantics() &&(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1034, __extension__ __PRETTY_FUNCTION__ )) |
1034 | "Should only call on two APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1034, __extension__ __PRETTY_FUNCTION__ )); |
1035 | if (usesLayout<IEEEFloat>(getSemantics())) |
1036 | return U.IEEE.subtract(RHS.U.IEEE, RM); |
1037 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
1038 | return U.Double.subtract(RHS.U.Double, RM); |
1039 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1039); |
1040 | } |
1041 | opStatus multiply(const APFloat &RHS, roundingMode RM) { |
1042 | assert(&getSemantics() == &RHS.getSemantics() &&(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1043, __extension__ __PRETTY_FUNCTION__ )) |
1043 | "Should only call on two APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1043, __extension__ __PRETTY_FUNCTION__ )); |
1044 | if (usesLayout<IEEEFloat>(getSemantics())) |
1045 | return U.IEEE.multiply(RHS.U.IEEE, RM); |
1046 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
1047 | return U.Double.multiply(RHS.U.Double, RM); |
1048 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1048); |
1049 | } |
1050 | opStatus divide(const APFloat &RHS, roundingMode RM) { |
1051 | assert(&getSemantics() == &RHS.getSemantics() &&(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1052, __extension__ __PRETTY_FUNCTION__ )) |
1052 | "Should only call on two APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1052, __extension__ __PRETTY_FUNCTION__ )); |
1053 | if (usesLayout<IEEEFloat>(getSemantics())) |
1054 | return U.IEEE.divide(RHS.U.IEEE, RM); |
1055 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
1056 | return U.Double.divide(RHS.U.Double, RM); |
1057 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1057); |
1058 | } |
1059 | opStatus remainder(const APFloat &RHS) { |
1060 | assert(&getSemantics() == &RHS.getSemantics() &&(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1061, __extension__ __PRETTY_FUNCTION__ )) |
1061 | "Should only call on two APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1061, __extension__ __PRETTY_FUNCTION__ )); |
1062 | if (usesLayout<IEEEFloat>(getSemantics())) |
1063 | return U.IEEE.remainder(RHS.U.IEEE); |
1064 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
1065 | return U.Double.remainder(RHS.U.Double); |
1066 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1066); |
1067 | } |
1068 | opStatus mod(const APFloat &RHS) { |
1069 | assert(&getSemantics() == &RHS.getSemantics() &&(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1070, __extension__ __PRETTY_FUNCTION__ )) |
1070 | "Should only call on two APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only call on two APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only call on two APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1070, __extension__ __PRETTY_FUNCTION__ )); |
1071 | if (usesLayout<IEEEFloat>(getSemantics())) |
1072 | return U.IEEE.mod(RHS.U.IEEE); |
1073 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
1074 | return U.Double.mod(RHS.U.Double); |
1075 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1075); |
1076 | } |
1077 | opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, |
1078 | roundingMode RM) { |
1079 | assert(&getSemantics() == &Multiplicand.getSemantics() &&(static_cast <bool> (&getSemantics() == &Multiplicand .getSemantics() && "Should only call on APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &Multiplicand.getSemantics() && \"Should only call on APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1080, __extension__ __PRETTY_FUNCTION__ )) |
1080 | "Should only call on APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &Multiplicand .getSemantics() && "Should only call on APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &Multiplicand.getSemantics() && \"Should only call on APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1080, __extension__ __PRETTY_FUNCTION__ )); |
1081 | assert(&getSemantics() == &Addend.getSemantics() &&(static_cast <bool> (&getSemantics() == &Addend .getSemantics() && "Should only call on APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &Addend.getSemantics() && \"Should only call on APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1082, __extension__ __PRETTY_FUNCTION__ )) |
1082 | "Should only call on APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &Addend .getSemantics() && "Should only call on APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &Addend.getSemantics() && \"Should only call on APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1082, __extension__ __PRETTY_FUNCTION__ )); |
1083 | if (usesLayout<IEEEFloat>(getSemantics())) |
1084 | return U.IEEE.fusedMultiplyAdd(Multiplicand.U.IEEE, Addend.U.IEEE, RM); |
1085 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
1086 | return U.Double.fusedMultiplyAdd(Multiplicand.U.Double, Addend.U.Double, |
1087 | RM); |
1088 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1088); |
1089 | } |
1090 | opStatus roundToIntegral(roundingMode RM) { |
1091 | APFLOAT_DISPATCH_ON_SEMANTICS(roundToIntegral(RM)); |
1092 | } |
1093 | |
1094 | // TODO: bool parameters are not readable and a source of bugs. |
1095 | // Do something. |
1096 | opStatus next(bool nextDown) { |
1097 | APFLOAT_DISPATCH_ON_SEMANTICS(next(nextDown)); |
1098 | } |
1099 | |
1100 | /// Negate an APFloat. |
1101 | APFloat operator-() const { |
1102 | APFloat Result(*this); |
1103 | Result.changeSign(); |
1104 | return Result; |
1105 | } |
1106 | |
1107 | /// Add two APFloats, rounding ties to the nearest even. |
1108 | /// No error checking. |
1109 | APFloat operator+(const APFloat &RHS) const { |
1110 | APFloat Result(*this); |
1111 | (void)Result.add(RHS, rmNearestTiesToEven); |
1112 | return Result; |
1113 | } |
1114 | |
1115 | /// Subtract two APFloats, rounding ties to the nearest even. |
1116 | /// No error checking. |
1117 | APFloat operator-(const APFloat &RHS) const { |
1118 | APFloat Result(*this); |
1119 | (void)Result.subtract(RHS, rmNearestTiesToEven); |
1120 | return Result; |
1121 | } |
1122 | |
1123 | /// Multiply two APFloats, rounding ties to the nearest even. |
1124 | /// No error checking. |
1125 | APFloat operator*(const APFloat &RHS) const { |
1126 | APFloat Result(*this); |
1127 | (void)Result.multiply(RHS, rmNearestTiesToEven); |
1128 | return Result; |
1129 | } |
1130 | |
1131 | /// Divide the first APFloat by the second, rounding ties to the nearest even. |
1132 | /// No error checking. |
1133 | APFloat operator/(const APFloat &RHS) const { |
1134 | APFloat Result(*this); |
1135 | (void)Result.divide(RHS, rmNearestTiesToEven); |
1136 | return Result; |
1137 | } |
1138 | |
1139 | void changeSign() { APFLOAT_DISPATCH_ON_SEMANTICS(changeSign()); } |
1140 | void clearSign() { |
1141 | if (isNegative()) |
1142 | changeSign(); |
1143 | } |
1144 | void copySign(const APFloat &RHS) { |
1145 | if (isNegative() != RHS.isNegative()) |
1146 | changeSign(); |
1147 | } |
1148 | |
1149 | /// A static helper to produce a copy of an APFloat value with its sign |
1150 | /// copied from some other APFloat. |
1151 | static APFloat copySign(APFloat Value, const APFloat &Sign) { |
1152 | Value.copySign(Sign); |
1153 | return Value; |
1154 | } |
1155 | |
1156 | /// Assuming this is an IEEE-754 NaN value, quiet its signaling bit. |
1157 | /// This preserves the sign and payload bits. |
1158 | APFloat makeQuiet() const { |
1159 | APFloat Result(*this); |
1160 | Result.getIEEE().makeQuiet(); |
1161 | return Result; |
1162 | } |
1163 | |
1164 | opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, |
1165 | bool *losesInfo); |
1166 | opStatus convertToInteger(MutableArrayRef<integerPart> Input, |
1167 | unsigned int Width, bool IsSigned, roundingMode RM, |
1168 | bool *IsExact) const { |
1169 | APFLOAT_DISPATCH_ON_SEMANTICS( |
1170 | convertToInteger(Input, Width, IsSigned, RM, IsExact)); |
1171 | } |
1172 | opStatus convertToInteger(APSInt &Result, roundingMode RM, |
1173 | bool *IsExact) const; |
1174 | opStatus convertFromAPInt(const APInt &Input, bool IsSigned, |
1175 | roundingMode RM) { |
1176 | APFLOAT_DISPATCH_ON_SEMANTICS(convertFromAPInt(Input, IsSigned, RM)); |
1177 | } |
1178 | opStatus convertFromSignExtendedInteger(const integerPart *Input, |
1179 | unsigned int InputSize, bool IsSigned, |
1180 | roundingMode RM) { |
1181 | APFLOAT_DISPATCH_ON_SEMANTICS( |
1182 | convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM)); |
1183 | } |
1184 | opStatus convertFromZeroExtendedInteger(const integerPart *Input, |
1185 | unsigned int InputSize, bool IsSigned, |
1186 | roundingMode RM) { |
1187 | APFLOAT_DISPATCH_ON_SEMANTICS( |
1188 | convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM)); |
1189 | } |
1190 | Expected<opStatus> convertFromString(StringRef, roundingMode); |
1191 | APInt bitcastToAPInt() const { |
1192 | APFLOAT_DISPATCH_ON_SEMANTICS(bitcastToAPInt()); |
1193 | } |
1194 | |
1195 | /// Converts this APFloat to host double value. |
1196 | /// |
1197 | /// \pre The APFloat must be built using semantics, that can be represented by |
1198 | /// the host double type without loss of precision. It can be IEEEdouble and |
1199 | /// shorter semantics, like IEEEsingle and others. |
1200 | double convertToDouble() const; |
1201 | |
1202 | /// Converts this APFloat to host float value. |
1203 | /// |
1204 | /// \pre The APFloat must be built using semantics, that can be represented by |
1205 | /// the host float type without loss of precision. It can be IEEEsingle and |
1206 | /// shorter semantics, like IEEEhalf. |
1207 | float convertToFloat() const; |
1208 | |
1209 | bool operator==(const APFloat &RHS) const { return compare(RHS) == cmpEqual; } |
1210 | |
1211 | bool operator!=(const APFloat &RHS) const { return compare(RHS) != cmpEqual; } |
1212 | |
1213 | bool operator<(const APFloat &RHS) const { |
1214 | return compare(RHS) == cmpLessThan; |
1215 | } |
1216 | |
1217 | bool operator>(const APFloat &RHS) const { |
1218 | return compare(RHS) == cmpGreaterThan; |
1219 | } |
1220 | |
1221 | bool operator<=(const APFloat &RHS) const { |
1222 | cmpResult Res = compare(RHS); |
1223 | return Res == cmpLessThan || Res == cmpEqual; |
1224 | } |
1225 | |
1226 | bool operator>=(const APFloat &RHS) const { |
1227 | cmpResult Res = compare(RHS); |
1228 | return Res == cmpGreaterThan || Res == cmpEqual; |
1229 | } |
1230 | |
1231 | cmpResult compare(const APFloat &RHS) const { |
1232 | assert(&getSemantics() == &RHS.getSemantics() &&(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only compare APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only compare APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1233, __extension__ __PRETTY_FUNCTION__ )) |
1233 | "Should only compare APFloats with the same semantics")(static_cast <bool> (&getSemantics() == &RHS.getSemantics () && "Should only compare APFloats with the same semantics" ) ? void (0) : __assert_fail ("&getSemantics() == &RHS.getSemantics() && \"Should only compare APFloats with the same semantics\"" , "llvm/include/llvm/ADT/APFloat.h", 1233, __extension__ __PRETTY_FUNCTION__ )); |
1234 | if (usesLayout<IEEEFloat>(getSemantics())) |
1235 | return U.IEEE.compare(RHS.U.IEEE); |
1236 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
1237 | return U.Double.compare(RHS.U.Double); |
1238 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1238); |
1239 | } |
1240 | |
1241 | bool bitwiseIsEqual(const APFloat &RHS) const { |
1242 | if (&getSemantics() != &RHS.getSemantics()) |
1243 | return false; |
1244 | if (usesLayout<IEEEFloat>(getSemantics())) |
1245 | return U.IEEE.bitwiseIsEqual(RHS.U.IEEE); |
1246 | if (usesLayout<DoubleAPFloat>(getSemantics())) |
1247 | return U.Double.bitwiseIsEqual(RHS.U.Double); |
1248 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1248); |
1249 | } |
1250 | |
1251 | /// We don't rely on operator== working on double values, as |
1252 | /// it returns true for things that are clearly not equal, like -0.0 and 0.0. |
1253 | /// As such, this method can be used to do an exact bit-for-bit comparison of |
1254 | /// two floating point values. |
1255 | /// |
1256 | /// We leave the version with the double argument here because it's just so |
1257 | /// convenient to write "2.0" and the like. Without this function we'd |
1258 | /// have to duplicate its logic everywhere it's called. |
1259 | bool isExactlyValue(double V) const { |
1260 | bool ignored; |
1261 | APFloat Tmp(V); |
1262 | Tmp.convert(getSemantics(), APFloat::rmNearestTiesToEven, &ignored); |
1263 | return bitwiseIsEqual(Tmp); |
1264 | } |
1265 | |
1266 | unsigned int convertToHexString(char *DST, unsigned int HexDigits, |
1267 | bool UpperCase, roundingMode RM) const { |
1268 | APFLOAT_DISPATCH_ON_SEMANTICS( |
1269 | convertToHexString(DST, HexDigits, UpperCase, RM)); |
1270 | } |
1271 | |
1272 | bool isZero() const { return getCategory() == fcZero; } |
1273 | bool isInfinity() const { return getCategory() == fcInfinity; } |
1274 | bool isNaN() const { return getCategory() == fcNaN; } |
1275 | |
1276 | bool isNegative() const { return getIEEE().isNegative(); } |
1277 | bool isDenormal() const { APFLOAT_DISPATCH_ON_SEMANTICS(isDenormal()); } |
1278 | bool isSignaling() const { return getIEEE().isSignaling(); } |
1279 | |
1280 | bool isNormal() const { return !isDenormal() && isFiniteNonZero(); } |
1281 | bool isFinite() const { return !isNaN() && !isInfinity(); } |
1282 | |
1283 | fltCategory getCategory() const { return getIEEE().getCategory(); } |
1284 | const fltSemantics &getSemantics() const { return *U.semantics; } |
1285 | bool isNonZero() const { return !isZero(); } |
1286 | bool isFiniteNonZero() const { return isFinite() && !isZero(); } |
1287 | bool isPosZero() const { return isZero() && !isNegative(); } |
1288 | bool isNegZero() const { return isZero() && isNegative(); } |
1289 | bool isPosInfinity() const { return isInfinity() && !isNegative(); } |
1290 | bool isNegInfinity() const { return isInfinity() && isNegative(); } |
1291 | bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); } |
1292 | bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); } |
1293 | bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); } |
1294 | bool isIEEE() const { return usesLayout<IEEEFloat>(getSemantics()); } |
1295 | |
1296 | bool isSmallestNormalized() const { |
1297 | APFLOAT_DISPATCH_ON_SEMANTICS(isSmallestNormalized()); |
1298 | } |
1299 | |
1300 | /// Return the FPClassTest which will return true for the value. |
1301 | FPClassTest classify() const; |
1302 | |
1303 | APFloat &operator=(const APFloat &RHS) = default; |
1304 | APFloat &operator=(APFloat &&RHS) = default; |
1305 | |
1306 | void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0, |
1307 | unsigned FormatMaxPadding = 3, bool TruncateZero = true) const { |
1308 | APFLOAT_DISPATCH_ON_SEMANTICS( |
1309 | toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero)); |
1310 | } |
1311 | |
1312 | void print(raw_ostream &) const; |
1313 | void dump() const; |
1314 | |
1315 | bool getExactInverse(APFloat *inv) const { |
1316 | APFLOAT_DISPATCH_ON_SEMANTICS(getExactInverse(inv)); |
1317 | } |
1318 | |
1319 | friend hash_code hash_value(const APFloat &Arg); |
1320 | friend int ilogb(const APFloat &Arg) { return ilogb(Arg.getIEEE()); } |
1321 | friend APFloat scalbn(APFloat X, int Exp, roundingMode RM); |
1322 | friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM); |
1323 | friend IEEEFloat; |
1324 | friend DoubleAPFloat; |
1325 | }; |
1326 | |
1327 | /// See friend declarations above. |
1328 | /// |
1329 | /// These additional declarations are required in order to compile LLVM with IBM |
1330 | /// xlC compiler. |
1331 | hash_code hash_value(const APFloat &Arg); |
1332 | inline APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM) { |
1333 | if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics())) |
1334 | return APFloat(scalbn(X.U.IEEE, Exp, RM), X.getSemantics()); |
1335 | if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics())) |
1336 | return APFloat(scalbn(X.U.Double, Exp, RM), X.getSemantics()); |
1337 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1337); |
1338 | } |
1339 | |
1340 | /// Equivalent of C standard library function. |
1341 | /// |
1342 | /// While the C standard says Exp is an unspecified value for infinity and nan, |
1343 | /// this returns INT_MAX for infinities, and INT_MIN for NaNs. |
1344 | inline APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM) { |
1345 | if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics())) |
1346 | return APFloat(frexp(X.U.IEEE, Exp, RM), X.getSemantics()); |
1347 | if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics())) |
1348 | return APFloat(frexp(X.U.Double, Exp, RM), X.getSemantics()); |
1349 | llvm_unreachable("Unexpected semantics")::llvm::llvm_unreachable_internal("Unexpected semantics", "llvm/include/llvm/ADT/APFloat.h" , 1349); |
1350 | } |
1351 | /// Returns the absolute value of the argument. |
1352 | inline APFloat abs(APFloat X) { |
1353 | X.clearSign(); |
1354 | return X; |
1355 | } |
1356 | |
1357 | /// Returns the negated value of the argument. |
1358 | inline APFloat neg(APFloat X) { |
1359 | X.changeSign(); |
1360 | return X; |
1361 | } |
1362 | |
1363 | /// Implements IEEE minNum semantics. Returns the smaller of the 2 arguments if |
1364 | /// both are not NaN. If either argument is a NaN, returns the other argument. |
1365 | LLVM_READONLY__attribute__((__pure__)) |
1366 | inline APFloat minnum(const APFloat &A, const APFloat &B) { |
1367 | if (A.isNaN()) |
1368 | return B; |
1369 | if (B.isNaN()) |
1370 | return A; |
1371 | return B < A ? B : A; |
1372 | } |
1373 | |
1374 | /// Implements IEEE maxNum semantics. Returns the larger of the 2 arguments if |
1375 | /// both are not NaN. If either argument is a NaN, returns the other argument. |
1376 | LLVM_READONLY__attribute__((__pure__)) |
1377 | inline APFloat maxnum(const APFloat &A, const APFloat &B) { |
1378 | if (A.isNaN()) |
1379 | return B; |
1380 | if (B.isNaN()) |
1381 | return A; |
1382 | return A < B ? B : A; |
1383 | } |
1384 | |
1385 | /// Implements IEEE 754-2018 minimum semantics. Returns the smaller of 2 |
1386 | /// arguments, propagating NaNs and treating -0 as less than +0. |
1387 | LLVM_READONLY__attribute__((__pure__)) |
1388 | inline APFloat minimum(const APFloat &A, const APFloat &B) { |
1389 | if (A.isNaN()) |
1390 | return A; |
1391 | if (B.isNaN()) |
1392 | return B; |
1393 | if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative())) |
1394 | return A.isNegative() ? A : B; |
1395 | return B < A ? B : A; |
1396 | } |
1397 | |
1398 | /// Implements IEEE 754-2018 maximum semantics. Returns the larger of 2 |
1399 | /// arguments, propagating NaNs and treating -0 as less than +0. |
1400 | LLVM_READONLY__attribute__((__pure__)) |
1401 | inline APFloat maximum(const APFloat &A, const APFloat &B) { |
1402 | if (A.isNaN()) |
1403 | return A; |
1404 | if (B.isNaN()) |
1405 | return B; |
1406 | if (A.isZero() && B.isZero() && (A.isNegative() != B.isNegative())) |
1407 | return A.isNegative() ? B : A; |
1408 | return A < B ? B : A; |
1409 | } |
1410 | |
1411 | } // namespace llvm |
1412 | |
1413 | #undef APFLOAT_DISPATCH_ON_SEMANTICS |
1414 | #endif // LLVM_ADT_APFLOAT_H |