|
fixed_point128 1.0.1.0
128 bit integer, fixed point and floating point arithmetic for C++20
|
Shared definitions, intrinsics, and helper functions for 128-bit fixed-point arithmetic. More...
#include <array>#include <bit>#include <cstdint>#include <cassert>#include <cctype>#include <cstdio>#include <cstring>#include <stdexcept>#include <memory>#include <string>#include <type_traits>Go to the source code of this file.
Classes | |
| struct | fp128::Double |
| Bit level view of an IEEE 754 double-precision value. More... | |
| struct | fp128::Float |
| Bit level view of an IEEE 754 single-precision value. More... | |
Namespaces | |
| namespace | fp128 |
| Everything the library provides. | |
Macros | |
| #define | FP128_DISABLE_INLINE 0 |
| #define | FP128_INLINE inline |
| #define | FP128_FORCE_INLINE inline __attribute__((always_inline)) |
| Marks a function the compiler must inline rather than merely may. | |
| #define | FP128_SUPPRESS_DEPRECATED_BEGIN _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") |
| Opens a region in which the use of a deprecated declaration is not reported. | |
| #define | FP128_SUPPRESS_DEPRECATED_END _Pragma("GCC diagnostic pop") |
| Closes the region opened by FP128_SUPPRESS_DEPRECATED_BEGIN. | |
| #define | FP128_USE_RECIPROCAL_FOR_DIVISION 0 |
| Selects how fixed_point128 divides by a value that is neither a power of two nor an integer. | |
| #define | FP128_ADD_ROUND_BIT(l, h, round_up) |
| Adds a rounding bit into a 128 bit value held as two QWORDs, as l and h are named there. | |
Library Version | |
Version of the fixed_point128 library, as macros usable by the preprocessor. The version is a four component number, major.minor.patch.build, starting at 0.9.0.0. Every component is kept below 100 so FP128_MAKE_VERSION() can pack the four of them into a single comparable integer. Bump the components on the usual terms: These are macros rather than constants so a consumer can branch on the version at preprocessing time, before any of this library's declarations exist: #if FP128_VERSION >= FP128_MAKE_VERSION(1, 0, 0, 0)
// use something introduced in 1.0
#endif
fp128::version_string holds the same value as a string for code that only needs to report it. | |
| #define | FP128_VERSION_MAJOR 1 |
| Breaking changes to the public interface. | |
| #define | FP128_VERSION_MINOR 0 |
| Backwards compatible additions. | |
| #define | FP128_VERSION_PATCH 1 |
| Fixes that change neither. | |
| #define | FP128_VERSION_BUILD 0 |
| Rebuild of an unchanged source tree. | |
| #define | FP128_MAKE_VERSION(major, minor, patch, build) |
| Packs a four component version into one integer, so two versions compare with < and >=. | |
| #define | FP128_VERSION FP128_MAKE_VERSION(FP128_VERSION_MAJOR, FP128_VERSION_MINOR, FP128_VERSION_PATCH, FP128_VERSION_BUILD) |
| This library's version as a single comparable integer, e.g. 90000 for 0.9.0.0. | |
| #define | FP128_STRINGIFY_IMPL(x) |
| #define | FP128_STRINGIFY(x) |
| #define | FP128_VERSION_STRING |
| This library's version as a dotted string literal, e.g. "0.9.0.0". | |
Utility Macros | |
Bit manipulation and exception macros for fixed-point arithmetic. | |
| #define | FP128_ONE_SHIFT(x) |
| #define | FP128_MAX_VALUE_64(x) |
| #define | FP128_GET_BIT(x, n) |
| #define | FP128_GET_BITS(x, b, count) |
| #define | FP128_INT_DIVIDE_BY_ZERO_EXCEPTION throw std::logic_error("Integer divide by zero!") |
| #define | FP128_FLOAT_DIVIDE_BY_ZERO_EXCEPTION throw std::logic_error("Floating point divide by zero!") |
| #define | FP128_NOT_IMPLEMENTED_EXCEPTION throw std::runtime_error("Not implemented!") |
| #define | FP128_ASSERT(x) |
| #define | FP128_THROW_ONLY_IN_DEBUG noexcept |
Platform-Specific Intrinsics | |
Compiler-specific intrinsic wrappers for bit manipulation and extended arithmetic. | |
| #define | FP128_ALIGN16 FP128_ALIGN(16) |
Functions | |
| static errno_t | fp128::strnlwr (char *dest, const char *src, size_t n) noexcept |
| Copy a string to lowercase, up to n characters. | |
| template<typename T> | |
| constexpr uint32_t | fp128::array_length (const T &a) |
| Calculates the element count of a C style array at build time Example: int a[5]; constexpr int len = array_length(a); // returns 5 at build time. | |
| constexpr uint64_t | fp128::shift_right64_round (uint64_t x, int shift) noexcept |
| Right-shift a 64-bit value with rounding. | |
| constexpr void | fp128::shift_right128_inplace (uint64_t &l, uint64_t &h, int shift) noexcept |
| Right shift a 128 bit unsigned integer (inplace). Limited range, inplace and no parameter checks (checked via assert in debug builds) | |
| constexpr void | fp128::shift_left128_inplace (uint64_t &l, uint64_t &h, int shift) noexcept |
| Left shift a 128 bit integer (inplace). Limited range, inplace and no parameter checks (checked via assert in debug builds) | |
| constexpr void | fp128::shift_right128_inplace_safe (uint64_t &l, uint64_t &h, int shift) noexcept |
| Right shift of an unsigned 128 bit integer (inplace), rounded to nearest with a tie going up. | |
| constexpr uint64_t | fp128::shift_right128_wide_signed_low (uint64_t l, uint64_t h, int shift) noexcept |
| The shifts by 64 bits or more of shift_right128_inplace_safe_signed(). | |
| constexpr void | fp128::shift_right128_inplace_safe_signed (uint64_t &l, uint64_t &h, int shift) noexcept |
| Arithmetic right shift of a 128 bit two's complement value (inplace), rounded to nearest with a tie going away from zero. | |
| constexpr void | fp128::shift_left128_inplace_safe (uint64_t &l, uint64_t &h, int shift) noexcept |
| Left shift a 128 bit integer (inplace). Handles any positive shift value. | |
| template<int shift> | |
| constexpr uint64_t | fp128::shift_right128 (uint64_t l, uint64_t h) noexcept |
| Right shift a 128 bit integer. When shift is a compile time constant, this function generates optimal code for all shift values. | |
| template<int shift> | |
| constexpr uint64_t | fp128::shift_left128 (uint64_t l, uint64_t h) noexcept |
| Left shift a 128 bit integer. When shift is a compile time constant, this function generates optimal code for all shift values. | |
| constexpr uint64_t | fp128::shift_right128 (uint64_t l, uint64_t h, int shift) noexcept |
| Right shift a 128 bit integer. | |
| constexpr uint64_t | fp128::shift_right128_round (uint64_t l, uint64_t h, int shift) noexcept |
| Right shift a 128 bit integer with rounding. | |
| constexpr uint64_t | fp128::shift_left128 (uint64_t l, uint64_t h, int shift) noexcept |
| Left shift a 128 bit integer. | |
| constexpr void | fp128::twos_complement128 (uint64_t &l, uint64_t &h) noexcept |
| converts a 128 integer to negative via 2's complement. | |
| static bool | fp128::div_64bit (uint64_t *q, uint64_t *r, const uint64_t *u, uint64_t v, int64_t m) noexcept |
| 64 bit words unsigned divide function. Variation of the code from the book Hacker's Delight. | |
| template<int64_t m> | |
| static bool | fp128::div_128bit (uint64_t *q, uint64_t *r, const uint64_t *u, const uint64_t *v) noexcept |
| Divides an unsigned integer of up to 256 bits by a 128 bit one. Knuth algorithm D, 64 bit limbs. | |
| static bool | fp128::div_128bit (uint64_t *q, uint64_t *r, const uint64_t *u, const uint64_t *v, int64_t m) noexcept |
| div_128bit() with the word count of the numerator chosen at run time. | |
| constexpr uint64_t | fp128::popcnt128 (uint64_t l, uint64_t h) noexcept |
| Counts the number of 1 bits (population count) in a 128-bit unsigned integer. | |
| constexpr uint64_t | fp128::lzcnt128 (uint64_t l, uint64_t h) noexcept |
| Left zero count 128 bit. | |
| constexpr uint64_t | fp128::log2 (uint64_t l, uint64_t h) noexcept |
| Calculates the Log base 2 of x: log2(x) Rounding is always towards zero so the maximum error is close to 1. | |
| constexpr uint64_t | fp128::log2 (uint64_t x) noexcept |
| Calculates the Log base 2 of x: log2(x) Rounding is always towards zero so the maximum error is close to 1. | |
| constexpr uint32_t | fp128::log2 (uint32_t x) noexcept |
| Calculates the Log base 2 of x: log2(x) Rounding is always towards zero so the maximum error is close to 1. | |
| constexpr void | fp128::mul128_high (uint64_t a_low, uint64_t a_high, uint64_t b_low, uint64_t b_high, uint64_t &res_low, uint64_t &res_high) noexcept |
| Upper 128 bits of the product of two 128 bit unsigned values. | |
Variables | |
| static constexpr bool | FP128_CPP_STYLE_MODULO = true |
| Use C++ modulo semantics (false = Python-style). | |
| constexpr uint64_t | fp128::log2_recip_table [][2] |
| 1/(1 + j/64) as a 128 bit fraction, the reciprocals fixed_point128::log2() reduces with. | |
| constexpr uint64_t | fp128::log2_value_table [][2] |
| -log2 of the matching log2_recip_table entry, as a 128 bit fraction. | |
| constexpr uint64_t | fp128::log2_inv_n_table [][2] |
| 1/(n*ln2) for n = 1 upwards, as a raw 128 bit value with 127 fraction bits; entry [i] holds 1/((i+1)*ln2). | |
| constexpr int32_t | fp128::log2_reduction_bits = 6 |
| Bits of argument reduction fixed_point128::log2() applies; log2_recip_table has 2^this entries. | |
Library Version | |
The FP128_VERSION_* macros as constants, for code that reports the version rather than branching on it at preprocessing time. | |
| static constexpr int32_t | fp128::version_major = FP128_VERSION_MAJOR |
| Breaking changes to the public interface. | |
| static constexpr int32_t | fp128::version_minor = FP128_VERSION_MINOR |
| Backwards compatible additions. | |
| static constexpr int32_t | fp128::version_patch = FP128_VERSION_PATCH |
| Fixes that change neither. | |
| static constexpr int32_t | fp128::version_build = FP128_VERSION_BUILD |
| Rebuild of an unchanged source tree. | |
| static constexpr int32_t | fp128::version = FP128_VERSION |
| All four packed into one comparable integer. | |
| static constexpr const char * | fp128::version_string = FP128_VERSION_STRING |
| Dotted form, e.g. "0.9.0.0". | |
IEEE 754 Layout Constants | |
| static constexpr int32_t | fp128::flt_frac_bits = 23 |
| Mantissa bit count of an IEEE 754 float. | |
| static constexpr int32_t | fp128::flt_exp_bits = 8 |
| Exponent bit count of an IEEE 754 float. | |
| static constexpr int32_t | fp128::dbl_frac_bits = 52 |
| Mantissa bit count of an IEEE 754 double. | |
| static constexpr int32_t | fp128::dbl_exp_bits = 11 |
| Exponent bit count of an IEEE 754 double. | |
Shared definitions, intrinsics, and helper functions for 128-bit fixed-point arithmetic.
Provides compiler-specific intrinsic wrappers (MSVC and GCC/Clang), bit manipulation utilities (128-bit shifts, leading zero counts, population counts), multi-word division algorithms (32-bit and 64-bit word-based, derived from Hacker's Delight), IEEE 754 bit-layout views, and build configuration macros.
This header is consumed by fixed_point128.h and should not be included directly.
Definition in file fp128_shared.h.
| #define FP128_VERSION_MAJOR 1 |
Breaking changes to the public interface.
Definition at line 73 of file fp128_shared.h.
| #define FP128_VERSION_MINOR 0 |
Backwards compatible additions.
Definition at line 74 of file fp128_shared.h.
| #define FP128_VERSION_PATCH 1 |
Fixes that change neither.
Definition at line 75 of file fp128_shared.h.
| #define FP128_VERSION_BUILD 0 |
Rebuild of an unchanged source tree.
Definition at line 76 of file fp128_shared.h.
| #define FP128_MAKE_VERSION | ( | major, | |
| minor, | |||
| patch, | |||
| build ) |
Packs a four component version into one integer, so two versions compare with < and >=.
Definition at line 79 of file fp128_shared.h.
| #define FP128_VERSION FP128_MAKE_VERSION(FP128_VERSION_MAJOR, FP128_VERSION_MINOR, FP128_VERSION_PATCH, FP128_VERSION_BUILD) |
This library's version as a single comparable integer, e.g. 90000 for 0.9.0.0.
Definition at line 82 of file fp128_shared.h.
| #define FP128_STRINGIFY_IMPL | ( | x | ) |
Definition at line 86 of file fp128_shared.h.
| #define FP128_STRINGIFY | ( | x | ) |
Definition at line 87 of file fp128_shared.h.
| #define FP128_VERSION_STRING |
This library's version as a dotted string literal, e.g. "0.9.0.0".
Definition at line 90 of file fp128_shared.h.
| #define FP128_DISABLE_INLINE 0 |
Definition at line 121 of file fp128_shared.h.
| #define FP128_INLINE inline |
Definition at line 171 of file fp128_shared.h.
| #define FP128_FORCE_INLINE inline __attribute__((always_inline)) |
Marks a function the compiler must inline rather than merely may.
Which of the two markers a member of the 128 bit types carries follows a single rule:
The distinction matters because all four types are 16 bytes, which the x64 ABI passes and returns in memory. Left to its own judgement MSVC declines to inline these forwarders under /GL (whole program optimization), and the round trip through memory then costs more than the operation being forwarded to. Forcing the wrapper open does not force the callee open with it, so the code that does the actual work still gets outlined when the optimizer thinks that is better.
Two places depart from that rule, and both say why at their definitions. The by value shift operators of float128 and fixed_point128 are forwarders that are nonetheless not forced: what they forward to is large enough that expanding the wrapper crowds out the arithmetic around it. float128::get_components() and float128::norm_fraction_sticky() go the other way - they have bodies of their own and are forced anyway, because the callers' exponent arithmetic only folds once they are open, and Clang would not open them on its own.
Treat any addition to the forced set the same way - measure it, and record the number if the answer is surprising.
Definition at line 172 of file fp128_shared.h.
| #define FP128_SUPPRESS_DEPRECATED_BEGIN _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") |
Opens a region in which the use of a deprecated declaration is not reported.
C++23 deprecated numeric_limits::has_denorm, numeric_limits::has_denorm_loss and the float_denorm_style enum they are typed with, and C++26 keeps all three in Annex D. The numeric_limits specializations of this library still declare the two members, because generic code may read them, and naming the enum is enough for the standard library to warn: Clang over the MSVC STL reports -Wdeprecated-declarations twice per specialization from C++23 on.
The warning is silenced around those declarations only. The library's own switch, _SILENCE_CXX23_DENORM_DEPRECATION_WARNING, would have to be defined before <limits> is included and would hide the warning in the including program as well.
Definition at line 197 of file fp128_shared.h.
| #define FP128_SUPPRESS_DEPRECATED_END _Pragma("GCC diagnostic pop") |
Closes the region opened by FP128_SUPPRESS_DEPRECATED_BEGIN.
Definition at line 198 of file fp128_shared.h.
| #define FP128_USE_RECIPROCAL_FOR_DIVISION 0 |
Selects how fixed_point128 divides by a value that is neither a power of two nor an integer.
Non zero computes a / b as a * reciprocal(b), where reciprocal() refines a double precision estimate with Newton iterations. Zero (the default) selects the hand written long division instead. Only the general case is affected either way: a power of two divisor is still turned into a shift, and an integral divisor that fits in 64 bit still goes through div_64bit().
Override it on the command line (/DFP128_USE_RECIPROCAL_FOR_DIVISION=1 or -DFP128_USE_RECIPROCAL_FOR_DIVISION=1) or by defining it before including any header of this library, exactly as with FP128_DISABLE_INLINE.
The default used to be non zero, and the reason was speed: against the old 32 bit limb long division the reciprocal ran 1.4x to 1.7x faster, which was worth its cost in accuracy. div_128bit() removed that trade. Measured over a table of 256 random divisors on fixed_point128<10>, the long division now runs at 2.0x (MSVC) and 2.7x (clang-cl) the rate of the reciprocal, so the default is zero and the accuracy comes for free: the two algorithms disagree on roughly 40% of those divisors, by up to 1.7 ulp, and comparing the residual |a - q * b| of each puts the long division closer to the exact quotient every single time it differs. Set this to non zero only to reproduce the older behaviour.
The flag is deliberately specific to fixed_point128. The other three types are not built the same way, and measuring them says to leave them alone:
Definition at line 252 of file fp128_shared.h.
| #define FP128_ONE_SHIFT | ( | x | ) |
Definition at line 263 of file fp128_shared.h.
| #define FP128_MAX_VALUE_64 | ( | x | ) |
Definition at line 264 of file fp128_shared.h.
| #define FP128_GET_BIT | ( | x, | |
| n ) |
Definition at line 265 of file fp128_shared.h.
| #define FP128_GET_BITS | ( | x, | |
| b, | |||
| count ) |
Definition at line 266 of file fp128_shared.h.
| #define FP128_INT_DIVIDE_BY_ZERO_EXCEPTION throw std::logic_error("Integer divide by zero!") |
Definition at line 267 of file fp128_shared.h.
| #define FP128_FLOAT_DIVIDE_BY_ZERO_EXCEPTION throw std::logic_error("Floating point divide by zero!") |
Definition at line 268 of file fp128_shared.h.
| #define FP128_NOT_IMPLEMENTED_EXCEPTION throw std::runtime_error("Not implemented!") |
Definition at line 269 of file fp128_shared.h.
| #define FP128_ASSERT | ( | x | ) |
Definition at line 274 of file fp128_shared.h.
| #define FP128_THROW_ONLY_IN_DEBUG noexcept |
Definition at line 275 of file fp128_shared.h.
| #define FP128_ALIGN16 FP128_ALIGN(16) |
Definition at line 806 of file fp128_shared.h.
| #define FP128_ADD_ROUND_BIT | ( | l, | |
| h, | |||
| round_up ) |
Adds a rounding bit into a 128 bit value held as two QWORDs, as l and h are named there.
A macro rather than a function because the two QWORDs are always members of the caller, and taking references to them is what a function would have to do. MSVC then keeps them in memory for the whole of the surrounding routine even with __forceinline, which costs more than this whole operation is worth: written as a function it made fixed_point128<10>::log2() 40% slower.
The rounding bit is bit F-1 of a product, which is as good as random for every caller that multiplies data rather than constants. A branch on it therefore mispredicts about half the time, and this macro sits in operator*=() and square(), the two hottest routines in the library. The carry propagating form has no branch to mispredict: BT sets the carry flag and two ADCs consume it, four instructions of fixed latency.
Both compilers want that form, and MSVC wants it far more than Clang does. MSVC used to be given the branch instead, on the strength of a log2() measurement in which it if converted the branch into a conditional move; that if conversion is not something it does reliably, and in the Mandelbrot escape-time loop of a real renderer it emits a real branch, three per iteration on three unpredictable bits. There the change is worth 1.9x - a 640x360 frame at 2048 iterations goes from 625ms to 324ms, taking MSVC from roughly half of clang-cl's speed to level with it.
Measured on an i9-12900K, one core, fastest of three runs, over the 32 fixed_point128<10> benchmarks in bench/Bench.cpp. Ratios are the carry propagating form against the branch:
| MSVC P-core | MSVC E-core | Clang P-core | |
|---|---|---|---|
| median over all 32 | +52% | +43% | +6.7% |
| exp2 / exp / pow / expm1 | 1.87-1.81x | 1.77-1.74x | 1.17-1.11x |
| atan / asin / acos | 1.78-1.67x | 1.61-1.40x | 1.09-1.00x |
| tan / sin / cos | 1.63-1.56x | 1.50-1.43x | 1.03-1.01x |
| log2 / log | 1.54-1.55x | 1.62-1.63x | 1.15-1.14x |
| sqrt, reciprocal | -2%, -3% | 0%, +20% | +1%, +3% |
| isolated operator*=() loop | -7% | 2.01x | -4% |
The transcendentals gain most because they reach this code once per bit of their result, so the rounding was a large part of their inner loop. The isolated multiplication loop is the one case that regresses on a P-core: accumulating a single product per iteration leaves the core enough slack to hide the branch, which no caller that chains multiplications gives it. The same loop is twice as fast on an E-core, whose narrower recovery pays more for a misprediction than it saves.
A warning for anyone re-measuring this. Until 2026-08-21 bench/Bench.cpp built its operands as an arithmetic progression and multiplied them by an operand that silently saturated to the type maximum, which made the rounding bit 1 for every argument in the set - a branch that never changes direction is free, and the benchmark reported this change as a 6% regression. Randomising the operands costs the branch build 45-48% on the transcendentals and the carry build 1-3%; that asymmetry is the check that the benchmark can see a misprediction at all. bench_mandelbrot() still shows a small loss because it iterates one bounded orbit with no escape test, the shape MSVC does if convert - it is not a substitute for measuring a real render.
Definition at line 1086 of file fp128_shared.h.
|
staticconstexpr |
Use C++ modulo semantics (false = Python-style).
Definition at line 201 of file fp128_shared.h.