FLANG
big-radix-floating-point.h
1//===-- lib/Decimal/big-radix-floating-point.h ------------------*- 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#ifndef FORTRAN_DECIMAL_BIG_RADIX_FLOATING_POINT_H_
10#define FORTRAN_DECIMAL_BIG_RADIX_FLOATING_POINT_H_
11
12// This is a helper class for use in floating-point conversions between
13// binary and decimal representations. It holds a multiple-precision
14// integer value using digits of a radix that is a large even power of ten
15// (10,000,000,000,000,000 by default, 10**16). These digits are accompanied
16// by a signed exponent that denotes multiplication by a power of ten.
17// The effective radix point is to the right of the digits (i.e., they do
18// not represent a fraction).
19//
20// The operations supported by this class are limited to those required
21// for conversions between binary and decimal representations; it is not
22// a general-purpose facility.
23
24#include "flang/Common/leading-zero-bit-count.h"
25#include "flang/Common/uint128.h"
26#include "flang/Decimal/binary-floating-point.h"
27#include "flang/Decimal/decimal.h"
28#include <cinttypes>
29#include <limits>
30#include <type_traits>
31
32// Some environments, viz. glibc 2.17, allow the macro HUGE
33// to leak out of <math.h>.
34#undef HUGE
35
36namespace Fortran::decimal {
37
38static constexpr std::uint64_t TenToThe(int power) {
39 return power <= 0 ? 1 : 10 * TenToThe(power - 1);
40}
41
42// 10**(LOG10RADIX + 3) must be < 2**wordbits, and LOG10RADIX must be
43// even, so that pairs of decimal digits do not straddle Digits.
44// So LOG10RADIX must be 16 or 6.
45template <int PREC, int LOG10RADIX = 16> class BigRadixFloatingPointNumber {
46public:
48 static constexpr int log10Radix{LOG10RADIX};
49
50private:
51 static constexpr std::uint64_t uint64Radix{TenToThe(log10Radix)};
52 static constexpr int minDigitBits{
53 64 - common::LeadingZeroBitCount(uint64Radix)};
54 using Digit = common::HostUnsignedIntType<minDigitBits>;
55 static constexpr Digit radix{uint64Radix};
56 static_assert(radix < std::numeric_limits<Digit>::max() / 1000,
57 "radix is somehow too big");
58 static_assert(radix > std::numeric_limits<Digit>::max() / 10000,
59 "radix is somehow too small");
60
61 // The base-2 logarithm of the least significant bit that can arise
62 // in a subnormal IEEE floating-point number.
63 static constexpr int minLog2AnyBit{
64 -Real::exponentBias - Real::binaryPrecision};
65
66 // The number of Digits needed to represent the smallest subnormal.
67 static constexpr int maxDigits{3 - minLog2AnyBit / log10Radix};
68
69public:
70 explicit RT_API_ATTRS BigRadixFloatingPointNumber(
71 enum FortranRounding rounding = RoundNearest)
72 : rounding_{rounding} {}
73
74 // Converts a binary floating point value.
75 explicit RT_API_ATTRS BigRadixFloatingPointNumber(
76 Real, enum FortranRounding = RoundNearest);
77
78 RT_API_ATTRS BigRadixFloatingPointNumber &SetToZero() {
79 isNegative_ = false;
80 digits_ = 0;
81 exponent_ = 0;
82 return *this;
83 }
84
85 RT_API_ATTRS bool IsInteger() const { return exponent_ >= 0; }
86
87 // Converts decimal floating-point to binary.
88 RT_API_ATTRS ConversionToBinaryResult<PREC> ConvertToBinary();
89
90 // Parses and converts to binary. Handles leading spaces,
91 // "NaN", & optionally-signed "Inf". Does not skip internal
92 // spaces.
93 // The argument is a reference to a pointer that is left
94 // pointing to the first character that wasn't parsed.
95 RT_API_ATTRS ConversionToBinaryResult<PREC> ConvertToBinary(
96 const char *&, const char *end = nullptr);
97
98 // Formats a decimal floating-point number to a user buffer.
99 // May emit "NaN" or "Inf", or an possibly-signed integer.
100 // No decimal point is written, but if it were, it would be
101 // after the last digit; the effective decimal exponent is
102 // returned as part of the result structure so that it can be
103 // formatted by the client.
104 RT_API_ATTRS ConversionToDecimalResult ConvertToDecimal(
105 char *, std::size_t, enum DecimalConversionFlags, int digits) const;
106
107 // Discard decimal digits not needed to distinguish this value
108 // from the decimal encodings of two others (viz., the nearest binary
109 // floating-point numbers immediately below and above this one).
110 // The last decimal digit may not be uniquely determined in all
111 // cases, and will be the mean value when that is so (e.g., if
112 // last decimal digit values 6-8 would all work, it'll be a 7).
113 // This minimization necessarily assumes that the value will be
114 // emitted and read back into the same (or less precise) format
115 // with default rounding to the nearest value.
116 RT_API_ATTRS void Minimize(
117 BigRadixFloatingPointNumber &&less, BigRadixFloatingPointNumber &&more);
118
119 template <typename STREAM> STREAM &Dump(STREAM &) const;
120
121private:
122 RT_API_ATTRS BigRadixFloatingPointNumber(
123 const BigRadixFloatingPointNumber &that)
124 : digits_{that.digits_}, exponent_{that.exponent_},
125 isNegative_{that.isNegative_}, rounding_{that.rounding_} {
126 for (int j{0}; j < digits_; ++j) {
127 digit_[j] = that.digit_[j];
128 }
129 }
130
131 RT_API_ATTRS bool IsZero() const {
132 // Don't assume normalization.
133 for (int j{0}; j < digits_; ++j) {
134 if (digit_[j] != 0) {
135 return false;
136 }
137 }
138 return true;
139 }
140
141 // Predicate: true when 10*value would cause a carry.
142 // (When this happens during decimal-to-binary conversion,
143 // there are more digits in the input string than can be
144 // represented precisely.)
145 RT_API_ATTRS bool IsFull() const {
146 return digits_ == digitLimit_ && digit_[digits_ - 1] >= radix / 10;
147 }
148
149 // Sets *this to an unsigned integer value.
150 // Returns any remainder.
151 template <typename UINT> RT_API_ATTRS UINT SetTo(UINT n) {
152 static_assert(
153 std::is_same_v<UINT, common::uint128_t> || std::is_unsigned_v<UINT>);
154 SetToZero();
155 while (n != 0) {
156 auto q{n / 10u};
157 if (n != q * 10) {
158 break;
159 }
160 ++exponent_;
161 n = q;
162 }
163 if constexpr (sizeof n < sizeof(Digit)) {
164 if (n != 0) {
165 digit_[digits_++] = n;
166 }
167 return 0;
168 } else {
169 while (n != 0 && digits_ < digitLimit_) {
170 auto q{n / radix};
171 digit_[digits_++] = static_cast<Digit>(n - q * radix);
172 n = q;
173 }
174 return n;
175 }
176 }
177
178 RT_API_ATTRS int RemoveLeastOrderZeroDigits() {
179 int remove{0};
180 if (digits_ > 0 && digit_[0] == 0) {
181 while (remove < digits_ && digit_[remove] == 0) {
182 ++remove;
183 }
184 if (remove >= digits_) {
185 digits_ = 0;
186 } else if (remove > 0) {
187#if defined __GNUC__ && __GNUC__ < 8
188 // (&& j + remove < maxDigits) was added to avoid GCC < 8 build failure
189 // on -Werror=array-bounds. This can be removed if -Werror is disable.
190 for (int j{0}; j + remove < digits_ && (j + remove < maxDigits); ++j) {
191#else
192 for (int j{0}; j + remove < digits_; ++j) {
193#endif
194 digit_[j] = digit_[j + remove];
195 }
196 digits_ -= remove;
197 }
198 }
199 return remove;
200 }
201
202 RT_API_ATTRS void RemoveLeadingZeroDigits() {
203 while (digits_ > 0 && digit_[digits_ - 1] == 0) {
204 --digits_;
205 }
206 }
207
208 RT_API_ATTRS void Normalize() {
209 RemoveLeadingZeroDigits();
210 exponent_ += RemoveLeastOrderZeroDigits() * log10Radix;
211 }
212
213 // This limited divisibility test only works for even divisors of the radix,
214 // which is fine since it's only ever used with 2 and 5.
215 template <int N> RT_API_ATTRS bool IsDivisibleBy() const {
216 static_assert(N > 1 && radix % N == 0, "bad modulus");
217 return digits_ == 0 || (digit_[0] % N) == 0;
218 }
219
220 template <unsigned DIVISOR> RT_API_ATTRS int DivideBy() {
221 Digit remainder{0};
222 for (int j{digits_ - 1}; j >= 0; --j) {
223 Digit q{digit_[j] / DIVISOR};
224 Digit nrem{digit_[j] - DIVISOR * q};
225 digit_[j] = q + (radix / DIVISOR) * remainder;
226 remainder = nrem;
227 }
228 return remainder;
229 }
230
231 RT_API_ATTRS void DivideByPowerOfTwo(int twoPow) { // twoPow <= log10Radix
232 Digit remainder{0};
233 auto mask{(Digit{1} << twoPow) - 1};
234 auto coeff{radix >> twoPow};
235 for (int j{digits_ - 1}; j >= 0; --j) {
236 auto nrem{digit_[j] & mask};
237 digit_[j] = (digit_[j] >> twoPow) + coeff * remainder;
238 remainder = nrem;
239 }
240 }
241
242 // Returns true on overflow
243 RT_API_ATTRS bool DivideByPowerOfTwoInPlace(int twoPow) {
244 if (digits_ > 0) {
245 while (twoPow > 0) {
246 int chunk{twoPow > log10Radix ? log10Radix : twoPow};
247 if ((digit_[0] & ((Digit{1} << chunk) - 1)) == 0) {
248 DivideByPowerOfTwo(chunk);
249 twoPow -= chunk;
250 continue;
251 }
252 twoPow -= chunk;
253 if (digit_[digits_ - 1] >> chunk != 0) {
254 if (digits_ == digitLimit_) {
255 return true; // overflow
256 }
257 digit_[digits_++] = 0;
258 }
259 auto remainder{digit_[digits_ - 1]};
260 exponent_ -= log10Radix;
261 auto coeff{radix >> chunk}; // precise; radix is (5*2)**log10Radix
262 auto mask{(Digit{1} << chunk) - 1};
263 for (int j{digits_ - 1}; j >= 1; --j) {
264 digit_[j] = (digit_[j - 1] >> chunk) + coeff * remainder;
265 remainder = digit_[j - 1] & mask;
266 }
267 digit_[0] = coeff * remainder;
268 }
269 }
270 return false; // no overflow
271 }
272
273 RT_API_ATTRS int AddCarry(int position = 0, int carry = 1) {
274 for (; position < digits_; ++position) {
275 Digit v{digit_[position] + carry};
276 if (v < radix) {
277 digit_[position] = v;
278 return 0;
279 }
280 digit_[position] = v - radix;
281 carry = 1;
282 }
283 if (digits_ < digitLimit_) {
284 digit_[digits_++] = carry;
285 return 0;
286 }
287 Normalize();
288 if (digits_ < digitLimit_) {
289 digit_[digits_++] = carry;
290 return 0;
291 }
292 return carry;
293 }
294
295 RT_API_ATTRS void Decrement() {
296 for (int j{0}; digit_[j]-- == 0; ++j) {
297 digit_[j] = radix - 1;
298 }
299 }
300
301 template <int N> RT_API_ATTRS int MultiplyByHelper(int carry = 0) {
302 for (int j{0}; j < digits_; ++j) {
303 auto v{N * digit_[j] + carry};
304 carry = v / radix;
305 digit_[j] = v - carry * radix; // i.e., v % radix
306 }
307 return carry;
308 }
309
310 template <int N> RT_API_ATTRS int MultiplyBy(int carry = 0) {
311 if (int newCarry{MultiplyByHelper<N>(carry)}) {
312 return AddCarry(digits_, newCarry);
313 } else {
314 return 0;
315 }
316 }
317
318 template <int N> RT_API_ATTRS int MultiplyWithoutNormalization() {
319 if (int carry{MultiplyByHelper<N>(0)}) {
320 if (digits_ < digitLimit_) {
321 digit_[digits_++] = carry;
322 return 0;
323 } else {
324 return carry;
325 }
326 } else {
327 return 0;
328 }
329 }
330
331 RT_API_ATTRS void LoseLeastSignificantDigit(); // with rounding
332
333 RT_API_ATTRS void PushCarry(int carry) {
334 if (digits_ == maxDigits && RemoveLeastOrderZeroDigits() == 0) {
335 LoseLeastSignificantDigit();
336 digit_[digits_ - 1] += carry;
337 } else {
338 digit_[digits_++] = carry;
339 }
340 }
341
342 // Adds another number and then divides by two.
343 // Assumes same exponent and sign.
344 // Returns true when the result has effectively been rounded down.
345 RT_API_ATTRS bool Mean(const BigRadixFloatingPointNumber &);
346
347 // Parses a floating-point number; leaves the pointer reference
348 // argument pointing at the next character after what was recognized.
349 // The "end" argument can be left null if the caller is sure that the
350 // string is properly terminated with an addressable character that
351 // can't be in a valid floating-point character.
352 RT_API_ATTRS bool ParseNumber(const char *&, bool &inexact, const char *end);
353
354 using Raw = typename Real::RawType;
355 constexpr RT_API_ATTRS Raw SignBit() const {
356 return Raw{isNegative_} << (Real::bits - 1);
357 }
358 constexpr RT_API_ATTRS Raw Infinity() const {
359 Raw result{static_cast<Raw>(Real::maxExponent)};
360 result <<= Real::significandBits;
361 result |= SignBit();
362 if constexpr (Real::bits == 80) { // x87
363 result |= Raw{1} << 63;
364 }
365 return result;
366 }
367 constexpr RT_API_ATTRS Raw NaN(bool isQuiet = true) {
368 Raw result{Real::maxExponent};
369 result <<= Real::significandBits;
370 result |= SignBit();
371 if constexpr (Real::bits == 80) { // x87
372 result |= Raw{isQuiet ? 3u : 2u} << 62;
373 } else {
374 Raw quiet{isQuiet ? Raw{2} : Raw{1}};
375 quiet <<= Real::significandBits - 2;
376 result |= quiet;
377 }
378 return result;
379 }
380 constexpr RT_API_ATTRS Raw HUGE() const {
381 Raw result{static_cast<Raw>(Real::maxExponent)};
382 result <<= Real::significandBits;
383 result |= SignBit();
384 return result - 1; // decrement exponent, set all significand bits
385 }
386
387 Digit digit_[maxDigits]; // in little-endian order: digit_[0] is LSD
388 int digits_{0}; // # of elements in digit_[] array; zero when zero
389 int digitLimit_{maxDigits}; // precision clamp
390 int exponent_{0}; // signed power of ten
391 bool isNegative_{false};
392 enum FortranRounding rounding_ { RoundNearest };
393};
394} // namespace Fortran::decimal
395#endif
Definition binary-floating-point.h:32
Definition decimal.h:41