Bug 1686820 [wpt PR 27193] - Origin-keyed agent clusters: make COI imply origin-keyin...
[gecko.git] / mfbt / FloatingPoint.h
bloba2625a4e2232d79c730178e188a7f57c6417f94a
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Various predicates and operations on IEEE-754 floating point types. */
9 #ifndef mozilla_FloatingPoint_h
10 #define mozilla_FloatingPoint_h
12 #include "mozilla/Assertions.h"
13 #include "mozilla/Attributes.h"
14 #include "mozilla/Casting.h"
15 #include "mozilla/MathAlgorithms.h"
16 #include "mozilla/MemoryChecking.h"
17 #include "mozilla/Types.h"
19 #include <algorithm>
20 #include <climits>
21 #include <limits>
22 #include <stdint.h>
24 namespace mozilla {
27 * It's reasonable to ask why we have this header at all. Don't isnan,
28 * copysign, the built-in comparison operators, and the like solve these
29 * problems? Unfortunately, they don't. We've found that various compilers
30 * (MSVC, MSVC when compiling with PGO, and GCC on OS X, at least) miscompile
31 * the standard methods in various situations, so we can't use them. Some of
32 * these compilers even have problems compiling seemingly reasonable bitwise
33 * algorithms! But with some care we've found algorithms that seem to not
34 * trigger those compiler bugs.
36 * For the aforementioned reasons, be very wary of making changes to any of
37 * these algorithms. If you must make changes, keep a careful eye out for
38 * compiler bustage, particularly PGO-specific bustage.
41 namespace detail {
44 * These implementations assume float/double are 32/64-bit single/double
45 * format number types compatible with the IEEE-754 standard. C++ doesn't
46 * require this, but we required it in implementations of these algorithms that
47 * preceded this header, so we shouldn't break anything to continue doing so.
49 template <typename T>
50 struct FloatingPointTrait;
52 template <>
53 struct FloatingPointTrait<float> {
54 protected:
55 using Bits = uint32_t;
57 static constexpr unsigned kExponentWidth = 8;
58 static constexpr unsigned kSignificandWidth = 23;
61 template <>
62 struct FloatingPointTrait<double> {
63 protected:
64 using Bits = uint64_t;
66 static constexpr unsigned kExponentWidth = 11;
67 static constexpr unsigned kSignificandWidth = 52;
70 } // namespace detail
73 * This struct contains details regarding the encoding of floating-point
74 * numbers that can be useful for direct bit manipulation. As of now, the
75 * template parameter has to be float or double.
77 * The nested typedef |Bits| is the unsigned integral type with the same size
78 * as T: uint32_t for float and uint64_t for double (static assertions
79 * double-check these assumptions).
81 * kExponentBias is the offset that is subtracted from the exponent when
82 * computing the value, i.e. one plus the opposite of the mininum possible
83 * exponent.
84 * kExponentShift is the shift that one needs to apply to retrieve the
85 * exponent component of the value.
87 * kSignBit contains a bits mask. Bit-and-ing with this mask will result in
88 * obtaining the sign bit.
89 * kExponentBits contains the mask needed for obtaining the exponent bits and
90 * kSignificandBits contains the mask needed for obtaining the significand
91 * bits.
93 * Full details of how floating point number formats are encoded are beyond
94 * the scope of this comment. For more information, see
95 * http://en.wikipedia.org/wiki/IEEE_floating_point
96 * http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers
98 template <typename T>
99 struct FloatingPoint final : private detail::FloatingPointTrait<T> {
100 private:
101 using Base = detail::FloatingPointTrait<T>;
103 public:
105 * An unsigned integral type suitable for accessing the bitwise representation
106 * of T.
108 using Bits = typename Base::Bits;
110 static_assert(sizeof(T) == sizeof(Bits), "Bits must be same size as T");
112 /** The bit-width of the exponent component of T. */
113 using Base::kExponentWidth;
115 /** The bit-width of the significand component of T. */
116 using Base::kSignificandWidth;
118 static_assert(1 + kExponentWidth + kSignificandWidth == CHAR_BIT * sizeof(T),
119 "sign bit plus bit widths should sum to overall bit width");
122 * The exponent field in an IEEE-754 floating point number consists of bits
123 * encoding an unsigned number. The *actual* represented exponent (for all
124 * values finite and not denormal) is that value, minus a bias |kExponentBias|
125 * so that a useful range of numbers is represented.
127 static constexpr unsigned kExponentBias = (1U << (kExponentWidth - 1)) - 1;
130 * The amount by which the bits of the exponent-field in an IEEE-754 floating
131 * point number are shifted from the LSB of the floating point type.
133 static constexpr unsigned kExponentShift = kSignificandWidth;
135 /** The sign bit in the floating point representation. */
136 static constexpr Bits kSignBit = static_cast<Bits>(1)
137 << (CHAR_BIT * sizeof(Bits) - 1);
139 /** The exponent bits in the floating point representation. */
140 static constexpr Bits kExponentBits =
141 ((static_cast<Bits>(1) << kExponentWidth) - 1) << kSignificandWidth;
143 /** The significand bits in the floating point representation. */
144 static constexpr Bits kSignificandBits =
145 (static_cast<Bits>(1) << kSignificandWidth) - 1;
147 static_assert((kSignBit & kExponentBits) == 0,
148 "sign bit shouldn't overlap exponent bits");
149 static_assert((kSignBit & kSignificandBits) == 0,
150 "sign bit shouldn't overlap significand bits");
151 static_assert((kExponentBits & kSignificandBits) == 0,
152 "exponent bits shouldn't overlap significand bits");
154 static_assert((kSignBit | kExponentBits | kSignificandBits) == ~Bits(0),
155 "all bits accounted for");
158 /** Determines whether a float/double is NaN. */
159 template <typename T>
160 static MOZ_ALWAYS_INLINE bool IsNaN(T aValue) {
162 * A float/double is NaN if all exponent bits are 1 and the significand
163 * contains at least one non-zero bit.
165 typedef FloatingPoint<T> Traits;
166 typedef typename Traits::Bits Bits;
167 return (BitwiseCast<Bits>(aValue) & Traits::kExponentBits) ==
168 Traits::kExponentBits &&
169 (BitwiseCast<Bits>(aValue) & Traits::kSignificandBits) != 0;
172 /** Determines whether a float/double is +Infinity or -Infinity. */
173 template <typename T>
174 static MOZ_ALWAYS_INLINE bool IsInfinite(T aValue) {
175 /* Infinities have all exponent bits set to 1 and an all-0 significand. */
176 typedef FloatingPoint<T> Traits;
177 typedef typename Traits::Bits Bits;
178 Bits bits = BitwiseCast<Bits>(aValue);
179 return (bits & ~Traits::kSignBit) == Traits::kExponentBits;
182 /** Determines whether a float/double is not NaN or infinite. */
183 template <typename T>
184 static MOZ_ALWAYS_INLINE bool IsFinite(T aValue) {
186 * NaN and Infinities are the only non-finite floats/doubles, and both have
187 * all exponent bits set to 1.
189 typedef FloatingPoint<T> Traits;
190 typedef typename Traits::Bits Bits;
191 Bits bits = BitwiseCast<Bits>(aValue);
192 return (bits & Traits::kExponentBits) != Traits::kExponentBits;
196 * Determines whether a float/double is negative or -0. It is an error
197 * to call this method on a float/double which is NaN.
199 template <typename T>
200 static MOZ_ALWAYS_INLINE bool IsNegative(T aValue) {
201 MOZ_ASSERT(!IsNaN(aValue), "NaN does not have a sign");
203 /* The sign bit is set if the double is negative. */
204 typedef FloatingPoint<T> Traits;
205 typedef typename Traits::Bits Bits;
206 Bits bits = BitwiseCast<Bits>(aValue);
207 return (bits & Traits::kSignBit) != 0;
210 /** Determines whether a float/double represents -0. */
211 template <typename T>
212 static MOZ_ALWAYS_INLINE bool IsNegativeZero(T aValue) {
213 /* Only the sign bit is set if the value is -0. */
214 typedef FloatingPoint<T> Traits;
215 typedef typename Traits::Bits Bits;
216 Bits bits = BitwiseCast<Bits>(aValue);
217 return bits == Traits::kSignBit;
220 /** Determines wether a float/double represents +0. */
221 template <typename T>
222 static MOZ_ALWAYS_INLINE bool IsPositiveZero(T aValue) {
223 /* All bits are zero if the value is +0. */
224 typedef FloatingPoint<T> Traits;
225 typedef typename Traits::Bits Bits;
226 Bits bits = BitwiseCast<Bits>(aValue);
227 return bits == 0;
231 * Returns 0 if a float/double is NaN or infinite;
232 * otherwise, the float/double is returned.
234 template <typename T>
235 static MOZ_ALWAYS_INLINE T ToZeroIfNonfinite(T aValue) {
236 return IsFinite(aValue) ? aValue : 0;
240 * Returns the exponent portion of the float/double.
242 * Zero is not special-cased, so ExponentComponent(0.0) is
243 * -int_fast16_t(Traits::kExponentBias).
245 template <typename T>
246 static MOZ_ALWAYS_INLINE int_fast16_t ExponentComponent(T aValue) {
248 * The exponent component of a float/double is an unsigned number, biased
249 * from its actual value. Subtract the bias to retrieve the actual exponent.
251 typedef FloatingPoint<T> Traits;
252 typedef typename Traits::Bits Bits;
253 Bits bits = BitwiseCast<Bits>(aValue);
254 return int_fast16_t((bits & Traits::kExponentBits) >>
255 Traits::kExponentShift) -
256 int_fast16_t(Traits::kExponentBias);
259 /** Returns +Infinity. */
260 template <typename T>
261 static MOZ_ALWAYS_INLINE T PositiveInfinity() {
263 * Positive infinity has all exponent bits set, sign bit set to 0, and no
264 * significand.
266 typedef FloatingPoint<T> Traits;
267 return BitwiseCast<T>(Traits::kExponentBits);
270 /** Returns -Infinity. */
271 template <typename T>
272 static MOZ_ALWAYS_INLINE T NegativeInfinity() {
274 * Negative infinity has all exponent bits set, sign bit set to 1, and no
275 * significand.
277 typedef FloatingPoint<T> Traits;
278 return BitwiseCast<T>(Traits::kSignBit | Traits::kExponentBits);
282 * Computes the bit pattern for an infinity with the specified sign bit.
284 template <typename T, int SignBit>
285 struct InfinityBits {
286 using Traits = FloatingPoint<T>;
288 static_assert(SignBit == 0 || SignBit == 1, "bad sign bit");
289 static constexpr typename Traits::Bits value =
290 (SignBit * Traits::kSignBit) | Traits::kExponentBits;
294 * Computes the bit pattern for a NaN with the specified sign bit and
295 * significand bits.
297 template <typename T, int SignBit, typename FloatingPoint<T>::Bits Significand>
298 struct SpecificNaNBits {
299 using Traits = FloatingPoint<T>;
301 static_assert(SignBit == 0 || SignBit == 1, "bad sign bit");
302 static_assert((Significand & ~Traits::kSignificandBits) == 0,
303 "significand must only have significand bits set");
304 static_assert(Significand & Traits::kSignificandBits,
305 "significand must be nonzero");
307 static constexpr typename Traits::Bits value =
308 (SignBit * Traits::kSignBit) | Traits::kExponentBits | Significand;
312 * Constructs a NaN value with the specified sign bit and significand bits.
314 * There is also a variant that returns the value directly. In most cases, the
315 * two variants should be identical. However, in the specific case of x86
316 * chips, the behavior differs: returning floating-point values directly is done
317 * through the x87 stack, and x87 loads and stores turn signaling NaNs into
318 * quiet NaNs... silently. Returning floating-point values via outparam,
319 * however, is done entirely within the SSE registers when SSE2 floating-point
320 * is enabled in the compiler, which has semantics-preserving behavior you would
321 * expect.
323 * If preserving the distinction between signaling NaNs and quiet NaNs is
324 * important to you, you should use the outparam version. In all other cases,
325 * you should use the direct return version.
327 template <typename T>
328 static MOZ_ALWAYS_INLINE void SpecificNaN(
329 int signbit, typename FloatingPoint<T>::Bits significand, T* result) {
330 typedef FloatingPoint<T> Traits;
331 MOZ_ASSERT(signbit == 0 || signbit == 1);
332 MOZ_ASSERT((significand & ~Traits::kSignificandBits) == 0);
333 MOZ_ASSERT(significand & Traits::kSignificandBits);
335 BitwiseCast<T>(
336 (signbit ? Traits::kSignBit : 0) | Traits::kExponentBits | significand,
337 result);
338 MOZ_ASSERT(IsNaN(*result));
341 template <typename T>
342 static MOZ_ALWAYS_INLINE T
343 SpecificNaN(int signbit, typename FloatingPoint<T>::Bits significand) {
344 T t;
345 SpecificNaN(signbit, significand, &t);
346 return t;
349 /** Computes the smallest non-zero positive float/double value. */
350 template <typename T>
351 static MOZ_ALWAYS_INLINE T MinNumberValue() {
352 typedef FloatingPoint<T> Traits;
353 typedef typename Traits::Bits Bits;
354 return BitwiseCast<T>(Bits(1));
357 namespace detail {
359 template <typename Float, typename SignedInteger>
360 inline bool NumberEqualsSignedInteger(Float aValue, SignedInteger* aInteger) {
361 static_assert(std::is_same_v<Float, float> || std::is_same_v<Float, double>,
362 "Float must be an IEEE-754 floating point type");
363 static_assert(std::is_signed_v<SignedInteger>,
364 "this algorithm only works for signed types: a different one "
365 "will be required for unsigned types");
366 static_assert(sizeof(SignedInteger) >= sizeof(int),
367 "this function *might* require some finessing for signed types "
368 "subject to integral promotion before it can be used on them");
370 MOZ_MAKE_MEM_UNDEFINED(aInteger, sizeof(*aInteger));
372 // NaNs and infinities are not integers.
373 if (!IsFinite(aValue)) {
374 return false;
377 // Otherwise do direct comparisons against the minimum/maximum |SignedInteger|
378 // values that can be encoded in |Float|.
380 constexpr SignedInteger MaxIntValue =
381 std::numeric_limits<SignedInteger>::max(); // e.g. INT32_MAX
382 constexpr SignedInteger MinValue =
383 std::numeric_limits<SignedInteger>::min(); // e.g. INT32_MIN
385 static_assert(IsPowerOfTwo(Abs(MinValue)),
386 "MinValue should be is a small power of two, thus exactly "
387 "representable in float/double both");
389 constexpr unsigned SignedIntegerWidth = CHAR_BIT * sizeof(SignedInteger);
390 constexpr unsigned ExponentShift = FloatingPoint<Float>::kExponentShift;
392 // Careful! |MaxIntValue| may not be the maximum |SignedInteger| value that
393 // can be encoded in |Float|. Its |SignedIntegerWidth - 1| bits of precision
394 // may exceed |Float|'s |ExponentShift + 1| bits of precision. If necessary,
395 // compute the maximum |SignedInteger| that fits in |Float| from IEEE-754
396 // first principles. (|MinValue| doesn't have this problem because as a
397 // [relatively] small power of two it's always representable in |Float|.)
399 // Per C++11 [expr.const]p2, unevaluated subexpressions of logical AND/OR and
400 // conditional expressions *may* contain non-constant expressions, without
401 // making the enclosing expression not constexpr. MSVC implements this -- but
402 // it sometimes warns about undefined behavior in unevaluated subexpressions.
403 // This bites us if we initialize |MaxValue| the obvious way including an
404 // |uint64_t(1) << (SignedIntegerWidth - 2 - ExponentShift)| subexpression.
405 // Pull that shift-amount out and give it a not-too-huge value when it's in an
406 // unevaluated subexpression. 🙄
407 constexpr unsigned PrecisionExceededShiftAmount =
408 ExponentShift > SignedIntegerWidth - 1
410 : SignedIntegerWidth - 2 - ExponentShift;
412 constexpr SignedInteger MaxValue =
413 ExponentShift > SignedIntegerWidth - 1
414 ? MaxIntValue
415 : SignedInteger((uint64_t(1) << (SignedIntegerWidth - 1)) -
416 (uint64_t(1) << PrecisionExceededShiftAmount));
418 if (static_cast<Float>(MinValue) <= aValue &&
419 aValue <= static_cast<Float>(MaxValue)) {
420 auto possible = static_cast<SignedInteger>(aValue);
421 if (static_cast<Float>(possible) == aValue) {
422 *aInteger = possible;
423 return true;
427 return false;
430 template <typename Float, typename SignedInteger>
431 inline bool NumberIsSignedInteger(Float aValue, SignedInteger* aInteger) {
432 static_assert(std::is_same_v<Float, float> || std::is_same_v<Float, double>,
433 "Float must be an IEEE-754 floating point type");
434 static_assert(std::is_signed_v<SignedInteger>,
435 "this algorithm only works for signed types: a different one "
436 "will be required for unsigned types");
437 static_assert(sizeof(SignedInteger) >= sizeof(int),
438 "this function *might* require some finessing for signed types "
439 "subject to integral promotion before it can be used on them");
441 MOZ_MAKE_MEM_UNDEFINED(aInteger, sizeof(*aInteger));
443 if (IsNegativeZero(aValue)) {
444 return false;
447 return NumberEqualsSignedInteger(aValue, aInteger);
450 } // namespace detail
453 * If |aValue| is identical to some |int32_t| value, set |*aInt32| to that value
454 * and return true. Otherwise return false, leaving |*aInt32| in an
455 * indeterminate state.
457 * This method returns false for negative zero. If you want to consider -0 to
458 * be 0, use NumberEqualsInt32 below.
460 template <typename T>
461 static MOZ_ALWAYS_INLINE bool NumberIsInt32(T aValue, int32_t* aInt32) {
462 return detail::NumberIsSignedInteger(aValue, aInt32);
466 * If |aValue| is equal to some int32_t value (where -0 and +0 are considered
467 * equal), set |*aInt32| to that value and return true. Otherwise return false,
468 * leaving |*aInt32| in an indeterminate state.
470 * |NumberEqualsInt32(-0.0, ...)| will return true. To test whether a value can
471 * be losslessly converted to |int32_t| and back, use NumberIsInt32 above.
473 template <typename T>
474 static MOZ_ALWAYS_INLINE bool NumberEqualsInt32(T aValue, int32_t* aInt32) {
475 return detail::NumberEqualsSignedInteger(aValue, aInt32);
479 * Computes a NaN value. Do not use this method if you depend upon a particular
480 * NaN value being returned.
482 template <typename T>
483 static MOZ_ALWAYS_INLINE T UnspecifiedNaN() {
485 * If we can use any quiet NaN, we might as well use the all-ones NaN,
486 * since it's cheap to materialize on common platforms (such as x64, where
487 * this value can be represented in a 32-bit signed immediate field, allowing
488 * it to be stored to memory in a single instruction).
490 typedef FloatingPoint<T> Traits;
491 return SpecificNaN<T>(1, Traits::kSignificandBits);
495 * Compare two doubles for equality, *without* equating -0 to +0, and equating
496 * any NaN value to any other NaN value. (The normal equality operators equate
497 * -0 with +0, and they equate NaN to no other value.)
499 template <typename T>
500 static inline bool NumbersAreIdentical(T aValue1, T aValue2) {
501 typedef FloatingPoint<T> Traits;
502 typedef typename Traits::Bits Bits;
503 if (IsNaN(aValue1)) {
504 return IsNaN(aValue2);
506 return BitwiseCast<Bits>(aValue1) == BitwiseCast<Bits>(aValue2);
510 * Return true iff |aValue| and |aValue2| are equal (ignoring sign if both are
511 * zero) or both NaN.
513 template <typename T>
514 static inline bool EqualOrBothNaN(T aValue1, T aValue2) {
515 if (IsNaN(aValue1)) {
516 return IsNaN(aValue2);
518 return aValue1 == aValue2;
522 * Return NaN if either |aValue1| or |aValue2| is NaN, or the minimum of
523 * |aValue1| and |aValue2| otherwise.
525 template <typename T>
526 static inline T NaNSafeMin(T aValue1, T aValue2) {
527 if (IsNaN(aValue1) || IsNaN(aValue2)) {
528 return UnspecifiedNaN<T>();
530 return std::min(aValue1, aValue2);
534 * Return NaN if either |aValue1| or |aValue2| is NaN, or the maximum of
535 * |aValue1| and |aValue2| otherwise.
537 template <typename T>
538 static inline T NaNSafeMax(T aValue1, T aValue2) {
539 if (IsNaN(aValue1) || IsNaN(aValue2)) {
540 return UnspecifiedNaN<T>();
542 return std::max(aValue1, aValue2);
545 namespace detail {
547 template <typename T>
548 struct FuzzyEqualsEpsilon;
550 template <>
551 struct FuzzyEqualsEpsilon<float> {
552 // A number near 1e-5 that is exactly representable in a float.
553 static float value() { return 1.0f / (1 << 17); }
556 template <>
557 struct FuzzyEqualsEpsilon<double> {
558 // A number near 1e-12 that is exactly representable in a double.
559 static double value() { return 1.0 / (1LL << 40); }
562 } // namespace detail
565 * Compare two floating point values for equality, modulo rounding error. That
566 * is, the two values are considered equal if they are both not NaN and if they
567 * are less than or equal to aEpsilon apart. The default value of aEpsilon is
568 * near 1e-5.
570 * For most scenarios you will want to use FuzzyEqualsMultiplicative instead,
571 * as it is more reasonable over the entire range of floating point numbers.
572 * This additive version should only be used if you know the range of the
573 * numbers you are dealing with is bounded and stays around the same order of
574 * magnitude.
576 template <typename T>
577 static MOZ_ALWAYS_INLINE bool FuzzyEqualsAdditive(
578 T aValue1, T aValue2, T aEpsilon = detail::FuzzyEqualsEpsilon<T>::value()) {
579 static_assert(std::is_floating_point_v<T>, "floating point type required");
580 return Abs(aValue1 - aValue2) <= aEpsilon;
584 * Compare two floating point values for equality, allowing for rounding error
585 * relative to the magnitude of the values. That is, the two values are
586 * considered equal if they are both not NaN and they are less than or equal to
587 * some aEpsilon apart, where the aEpsilon is scaled by the smaller of the two
588 * argument values.
590 * In most cases you will want to use this rather than FuzzyEqualsAdditive, as
591 * this function effectively masks out differences in the bottom few bits of
592 * the floating point numbers being compared, regardless of what order of
593 * magnitude those numbers are at.
595 template <typename T>
596 static MOZ_ALWAYS_INLINE bool FuzzyEqualsMultiplicative(
597 T aValue1, T aValue2, T aEpsilon = detail::FuzzyEqualsEpsilon<T>::value()) {
598 static_assert(std::is_floating_point_v<T>, "floating point type required");
599 // can't use std::min because of bug 965340
600 T smaller = Abs(aValue1) < Abs(aValue2) ? Abs(aValue1) : Abs(aValue2);
601 return Abs(aValue1 - aValue2) <= aEpsilon * smaller;
605 * Returns true if |aValue| can be losslessly represented as an IEEE-754 single
606 * precision number, false otherwise. All NaN values are considered
607 * representable (even though the bit patterns of double precision NaNs can't
608 * all be exactly represented in single precision).
610 MOZ_MUST_USE
611 extern MFBT_API bool IsFloat32Representable(double aValue);
613 } /* namespace mozilla */
615 #endif /* mozilla_FloatingPoint_h */