fixed_point128 1.0.1.0
128 bit integer, fixed point and floating point arithmetic for C++20
Loading...
Searching...
No Matches
fp128_shared.h
Go to the documentation of this file.
1/***********************************************************************************
2 MIT License
3
4 Copyright (c) 2025 Eric Gur (ericgur@iname.com)
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 SOFTWARE.
23************************************************************************************/
24#ifndef FP128_SHARED_H
25#define FP128_SHARED_H
26
27/**
28 * @file fp128_shared.h
29 * @brief Shared definitions, intrinsics, and helper functions for 128-bit fixed-point arithmetic.
30 *
31 * Provides compiler-specific intrinsic wrappers (MSVC and GCC/Clang), bit
32 * manipulation utilities (128-bit shifts, leading zero counts, population counts),
33 * multi-word division algorithms (32-bit and 64-bit word-based, derived from
34 * Hacker's Delight), IEEE 754 bit-layout views, and build configuration macros.
35 *
36 * This header is consumed by fixed_point128.h and should not be included directly.
37 */
38
39#include <array>
40#include <bit> // countl_zero, popcount - the constant evaluated stand-ins for the lzcnt/popcnt intrinsics
41#include <cstdint>
42#include <cassert>
43#include <cctype> // tolower, isspace
44#include <cstdio> // snprintf
45#include <cstring> // strlen, strncmp
46#include <stdexcept>
47#include <memory>
48#include <string>
49#include <type_traits>
50
51/***********************************************************************************
52 * Library Version
53 ************************************************************************************/
54/** @name Library Version
55 * @brief Version of the fixed_point128 library, as macros usable by the preprocessor.
56 *
57 * The version is a four component number, `major.minor.patch.build`, starting at 0.9.0.0. Every
58 * component is kept below 100 so FP128_MAKE_VERSION() can pack the four of them into a single
59 * comparable integer. Bump the components on the usual terms: @c major for a breaking change to the
60 * public interface, @c minor for a backwards compatible addition, @c patch for a fix that changes
61 * neither, and @c build for a rebuild of an otherwise unchanged source tree.
62 *
63 * These are macros rather than constants so a consumer can branch on the version at preprocessing
64 * time, before any of this library's declarations exist:
65 * @code
66 * #if FP128_VERSION >= FP128_MAKE_VERSION(1, 0, 0, 0)
67 * // use something introduced in 1.0
68 * #endif
69 * @endcode
70 * fp128::version_string holds the same value as a string for code that only needs to report it.
71 * @{
72 */
73#define FP128_VERSION_MAJOR 1 ///< Breaking changes to the public interface.
74#define FP128_VERSION_MINOR 0 ///< Backwards compatible additions.
75#define FP128_VERSION_PATCH 1 ///< Fixes that change neither.
76#define FP128_VERSION_BUILD 0 ///< Rebuild of an unchanged source tree.
77
78/// @brief Packs a four component version into one integer, so two versions compare with `<` and `>=`.
79#define FP128_MAKE_VERSION(major, minor, patch, build) ((major) * 1000000 + (minor) * 10000 + (patch) * 100 + (build))
80
81/// @brief This library's version as a single comparable integer, e.g. 90000 for 0.9.0.0.
82#define FP128_VERSION FP128_MAKE_VERSION(FP128_VERSION_MAJOR, FP128_VERSION_MINOR, FP128_VERSION_PATCH, FP128_VERSION_BUILD)
83
84// Two levels of indirection: the outer macro expands its argument before the inner one stringizes it,
85// which is what turns FP128_VERSION_MAJOR into "0" rather than into its own name.
86#define FP128_STRINGIFY_IMPL(x) #x
87#define FP128_STRINGIFY(x) FP128_STRINGIFY_IMPL(x)
88
89/// @brief This library's version as a dotted string literal, e.g. "0.9.0.0".
90#define FP128_VERSION_STRING \
91 FP128_STRINGIFY(FP128_VERSION_MAJOR) \
92 "." FP128_STRINGIFY(FP128_VERSION_MINOR) "." FP128_STRINGIFY(FP128_VERSION_PATCH) "." FP128_STRINGIFY(FP128_VERSION_BUILD)
93/** @} */ // end Library Version
94
95/***********************************************************************************
96 * Build Options
97 ************************************************************************************/
98// Note that under VS 2022/2026, both __clang__ and _MSC_VER are pre-defined when using the Clang toolset
99#if defined(__GNUC__) || defined(__clang__)
100#define FP128_CLANG
101#elif defined(_MSC_VER)
102#define FP128_MSVC
103#endif
104
105// Detect AArch64 (ARMv8 64 bit, e.g. Apple Silicon). Used to select hand written
106// assembly implementations of the x86 intrinsics emulated in the Clang/GCC section below.
107#if defined(FP128_CLANG) && (defined(__aarch64__) || defined(_M_ARM64))
108#define FP128_ARM64
109#endif
110
111// Detect x86-64 under a GCC style frontend. Most of the x86 intrinsics MSVC provides have a
112// __builtin equivalent there, so this is only needed where the operation exists as an instruction
113// but neither as an intrinsic nor as something the compiler will produce on its own - which today
114// means udiv128() and the DIV instruction. MSVC never takes these paths; it has the intrinsic.
115#if defined(FP128_CLANG) && (defined(__x86_64__) || defined(_M_X64))
116#define FP128_X64
117#endif
118
119// Set to TRUE to disable function inlining - useful for profiling a specific function. Default 0
120#ifndef FP128_DISABLE_INLINE
121#define FP128_DISABLE_INLINE 0
122#endif
123
124#ifndef FP128_NO_INLINE
125#if defined(FP128_MSVC)
126#define FP128_NO_INLINE __declspec(noinline)
127#else
128#define FP128_NO_INLINE __attribute__((noinline))
129#endif
130#endif // FP128_NO_INLINE
131
132/**
133 * @def FP128_FORCE_INLINE
134 * @brief Marks a function the compiler must inline rather than merely may.
135 *
136 * Which of the two markers a member of the 128 bit types carries follows a single rule:
137 * <UL>
138 * <LI>FP128_FORCE_INLINE for the trivial members - accessors, comparisons, conversions between the
139 * builtin types - and for every member that only converts its operand and delegates to another
140 * member, such as the binary operators that forward to their compound assignment counterparts
141 * and the mixed type overloads that wrap their argument in the class type.</LI>
142 * <LI>FP128_INLINE for everything with a body of its own: division and modulo, the string
143 * conversions and the transcendental functions.</LI>
144 * </UL>
145 *
146 * The distinction matters because all four types are 16 bytes, which the x64 ABI passes and returns
147 * in memory. Left to its own judgement MSVC declines to inline these forwarders under /GL (whole
148 * program optimization), and the round trip through memory then costs more than the operation being
149 * forwarded to. Forcing the wrapper open does not force the callee open with it, so the code that
150 * does the actual work still gets outlined when the optimizer thinks that is better.
151 *
152 * Two places depart from that rule, and both say why at their definitions. The by value shift
153 * operators of float128 and fixed_point128 are forwarders that are nonetheless *not* forced: what
154 * they forward to is large enough that expanding the wrapper crowds out the arithmetic around it.
155 * float128::get_components() and float128::norm_fraction_sticky() go the other way - they have
156 * bodies of their own and are forced anyway, because the callers' exponent arithmetic only folds
157 * once they are open, and Clang would not open them on its own.
158 *
159 * Treat any addition to the forced set the same way - measure it, and record the number if the
160 * answer is surprising.
161 */
162#if FP128_DISABLE_INLINE != 0
163#define FP128_INLINE FP128_NO_INLINE
164#define FP128_FORCE_INLINE FP128_NO_INLINE
165#else
166
167#if defined(FP128_MSVC)
168#define FP128_INLINE inline
169#define FP128_FORCE_INLINE __forceinline
170#else
171#define FP128_INLINE inline
172#define FP128_FORCE_INLINE inline __attribute__((always_inline))
173#endif
174#endif
175
176/**
177 * @def FP128_SUPPRESS_DEPRECATED_BEGIN
178 * @brief Opens a region in which the use of a deprecated declaration is not reported.
179 *
180 * C++23 deprecated numeric_limits::has_denorm, numeric_limits::has_denorm_loss and the
181 * float_denorm_style enum they are typed with, and C++26 keeps all three in Annex D. The
182 * numeric_limits specializations of this library still declare the two members, because generic
183 * code may read them, and naming the enum is enough for the standard library to warn: Clang over
184 * the MSVC STL reports -Wdeprecated-declarations twice per specialization from C++23 on.
185 *
186 * The warning is silenced around those declarations only. The library's own switch,
187 * _SILENCE_CXX23_DENORM_DEPRECATION_WARNING, would have to be defined before `<limits>` is included
188 * and would hide the warning in the including program as well.
189 *
190 * @def FP128_SUPPRESS_DEPRECATED_END
191 * @brief Closes the region opened by FP128_SUPPRESS_DEPRECATED_BEGIN.
192 */
193#if defined(FP128_MSVC)
194#define FP128_SUPPRESS_DEPRECATED_BEGIN __pragma(warning(push)) __pragma(warning(disable : 4996))
195#define FP128_SUPPRESS_DEPRECATED_END __pragma(warning(pop))
196#else
197#define FP128_SUPPRESS_DEPRECATED_BEGIN _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
198#define FP128_SUPPRESS_DEPRECATED_END _Pragma("GCC diagnostic pop")
199#endif
200
201static constexpr bool FP128_CPP_STYLE_MODULO = true; ///< Use C++ modulo semantics (false = Python-style).
202
203/**
204 * @def FP128_USE_RECIPROCAL_FOR_DIVISION
205 * @brief Selects how fixed_point128 divides by a value that is neither a power of two nor an integer.
206 *
207 * Non zero computes <tt>a / b</tt> as <tt>a * reciprocal(b)</tt>, where reciprocal() refines a double
208 * precision estimate with Newton iterations. Zero (the default) selects the hand written long
209 * division instead. Only the general case is affected either way: a power of two divisor is still
210 * turned into a shift, and an integral divisor that fits in 64 bit still goes through div_64bit().
211 *
212 * Override it on the command line (<tt>/DFP128_USE_RECIPROCAL_FOR_DIVISION=1</tt> or
213 * <tt>-DFP128_USE_RECIPROCAL_FOR_DIVISION=1</tt>) or by defining it before including any header of
214 * this library, exactly as with FP128_DISABLE_INLINE.
215 *
216 * The default used to be non zero, and the reason was speed: against the old 32 bit limb long
217 * division the reciprocal ran 1.4x to 1.7x faster, which was worth its cost in accuracy. div_128bit()
218 * removed that trade. Measured over a table of 256 random divisors on fixed_point128<10>, the long
219 * division now runs at 2.0x (MSVC) and 2.7x (clang-cl) the rate of the reciprocal, so the default is
220 * zero and the accuracy comes for free: the two algorithms disagree on roughly 40% of those divisors,
221 * by up to 1.7 ulp, and comparing the residual <tt>|a - q * b|</tt> of each puts the long division
222 * closer to the exact quotient every single time it differs. Set this to non zero only to reproduce
223 * the older behaviour.
224 *
225 * The flag is deliberately specific to fixed_point128. The other three types are not built the same
226 * way, and measuring them says to leave them alone:
227 * <UL>
228 * <LI>float128 loses on both counts - multiplying by a reciprocal ran at 0.47x (MSVC) to 0.55x
229 * (clang-cl) of its long division before div_128bit, and further behind since, and it is the
230 * less accurate of the two by the same residual test.
231 * reciprocal() is the slower half: it normalizes its operand and then runs two or three float128
232 * multiplications, each of which renormalizes and rounds, where the fixed_point128 equivalent
233 * multiplies raw 128 bit words. So float128::operator/=() always divides.</LI>
234 * <LI>uint128_t and int128_t have no reciprocal to multiply by - 1 / b is zero for every |b| > 1 in
235 * an integer representation. Their equivalent is a scaled reciprocal, floor(2^k / b) followed by
236 * a multiply and a correction, and computing that scaled reciprocal is itself a division of the
237 * kind it is meant to replace. It only pays when one divisor is reused across many dividends,
238 * which operator/=() has no way to know, so those two divide directly.</LI>
239 * </UL>
240 *
241 * @note Setting this to zero used to be enough to fail a unit test, which is worth recording because
242 * the cause was not the division. asin() and acos() refine a double precision estimate with
243 * Newton's method, and at the ends of their domain the derivative they divide by is ~6.1e-17
244 * while the numerator is nothing but the error of sin(). The exact quotient of those two is
245 * a correction of ~7e-5 applied to an estimate that was already right, and the iteration never
246 * recovered. The reciprocal path had been hiding it rather than avoiding it: 1 / 6.1e-17
247 * overflows the type, so reciprocal() saturated and the bad correction came out clamped to
248 * something harmless. Both functions now reject a step that does not improve their residual,
249 * and produce identical results under either setting of this flag.
250 */
251#ifndef FP128_USE_RECIPROCAL_FOR_DIVISION
252#define FP128_USE_RECIPROCAL_FOR_DIVISION 0
253#endif
254
255/***********************************************************************************
256 * Macros
257 ***********************************************************************************/
258/** @name Utility Macros
259 * @brief Bit manipulation and exception macros for fixed-point arithmetic.
260 * @{
261 */
262
263#define FP128_ONE_SHIFT(x) (1ull << (x))
264#define FP128_MAX_VALUE_64(x) (UINT64_MAX >> (64 - (x)))
265#define FP128_GET_BIT(x, n) (((x) >> (n)) & 1)
266#define FP128_GET_BITS(x, b, count) (((x) >> (b)) & FP128_MAX_VALUE_64(count))
267#define FP128_INT_DIVIDE_BY_ZERO_EXCEPTION throw std::logic_error("Integer divide by zero!")
268#define FP128_FLOAT_DIVIDE_BY_ZERO_EXCEPTION throw std::logic_error("Floating point divide by zero!")
269#define FP128_NOT_IMPLEMENTED_EXCEPTION throw std::runtime_error("Not implemented!")
270#if defined _DEBUG || defined DEBUG
271#define FP128_ASSERT assert
272#define FP128_THROW_ONLY_IN_DEBUG
273#else
274#define FP128_ASSERT(x)
275#define FP128_THROW_ONLY_IN_DEBUG noexcept
276#endif // _DEBUG
277/** @} */ // end Utility Macros
278
279/// @name Platform-Specific Intrinsics
280/// @brief Compiler-specific intrinsic wrappers for bit manipulation and extended arithmetic.
281/// @{
282
283//
284// MSVC specific section - keep intrinsics as-is
285//
286#if defined(FP128_MSVC)
287#pragma warning(disable : 4996)
288
289#include <intrin.h>
290#include <immintrin.h>
291
292#define udiv64 _udiv64
293#define udiv128 _udiv128
294#define alloca _alloca
295
296// The 128 bit funnel shifts, which map to a single SHRD/SHLD instruction here.
297// See the note on the naming in the Clang section below.
298#define FP128_SHIFTRIGHT128 fp128_shiftright128
299#define FP128_SHIFTLEFT128 fp128_shiftleft128
300
301//
302// The bit counting and extended arithmetic intrinsics are wrapped in constexpr functions rather
303// than aliased with a macro, so that the operations built on them (fixed_point128's addition,
304// multiplication and get_exponent among them) can be evaluated at compile time.
305//
306// An intrinsic is never a constant expression, so each wrapper serves a constant evaluated call
307// from a portable implementation of the same operation and leaves every other call to the
308// intrinsic. std::is_constant_evaluated() is folded away by the optimizer, so the runtime path is
309// the bare intrinsic it was before, and it is the only path a runtime call can take: the portable
310// code never reaches code generation.
311//
312
313/**
314 * @brief Right funnel shift of a 128 bit value held in two QWORDs.
315 *
316 * Wraps __shiftright128, a single SHRD instruction. The shift count is taken modulo 64 and a
317 * count of zero returns the low QWORD unchanged, which is what the instruction does and what the
318 * constant evaluated path below reproduces.
319 *
320 * @param l Low QWORD.
321 * @param h High QWORD.
322 * @param shift Bits to shift.
323 * @return Lower 64 bits of the result.
324 */
325FP128_FORCE_INLINE constexpr uint64_t fp128_shiftright128(uint64_t l, uint64_t h, unsigned char shift) noexcept
326{
327 if (std::is_constant_evaluated()) {
328 const unsigned char s = shift & 63;
329 // shifting a 64 bit value by 64 is undefined in C++, which is what the zero case would reach
330 return (s == 0) ? l : (l >> s) | (h << (64 - s));
331 }
332 return __shiftright128(l, h, shift);
333}
334
335/**
336 * @brief Left funnel shift of a 128 bit value held in two QWORDs.
337 *
338 * Wraps __shiftleft128, a single SHLD instruction. The shift count is taken modulo 64 and a count
339 * of zero returns the high QWORD unchanged.
340 *
341 * @param l Low QWORD.
342 * @param h High QWORD.
343 * @param shift Bits to shift.
344 * @return Upper 64 bits of the result.
345 */
346FP128_FORCE_INLINE constexpr uint64_t fp128_shiftleft128(uint64_t l, uint64_t h, unsigned char shift) noexcept
347{
348 if (std::is_constant_evaluated()) {
349 const unsigned char s = shift & 63;
350 return (s == 0) ? h : (h << s) | (l >> (64 - s));
351 }
352 return __shiftleft128(l, h, shift);
353}
354
355/**
356 * @brief Count leading zeros in a 32-bit value.
357 * @param x Value to inspect.
358 * @return Number of leading zero bits, 32 for a zero operand.
359 */
360FP128_FORCE_INLINE constexpr uint32_t lzcnt32(uint32_t x) noexcept
361{
362 if (std::is_constant_evaluated()) {
363 return static_cast<uint32_t>(std::countl_zero(x));
364 }
365 return __lzcnt(x);
366}
367
368/**
369 * @brief Count leading zeros in a 64-bit value.
370 * @param x Value to inspect.
371 * @return Number of leading zero bits, 64 for a zero operand.
372 */
373FP128_FORCE_INLINE constexpr uint64_t lzcnt64(uint64_t x) noexcept
374{
375 if (std::is_constant_evaluated()) {
376 return static_cast<uint64_t>(std::countl_zero(x));
377 }
378 return __lzcnt64(x);
379}
380
381/**
382 * @brief Count set bits in a 32-bit value.
383 * @param x Value to inspect.
384 * @return Number of 1 bits in x.
385 */
386FP128_FORCE_INLINE constexpr uint32_t popcnt32(uint32_t x) noexcept
387{
388 if (std::is_constant_evaluated()) {
389 return static_cast<uint32_t>(std::popcount(x));
390 }
391 return __popcnt(x);
392}
393
394/**
395 * @brief Count set bits in a 64-bit value.
396 * @param x Value to inspect.
397 * @return Number of 1 bits in x.
398 */
399FP128_FORCE_INLINE constexpr uint64_t popcnt64(uint64_t x) noexcept
400{
401 if (std::is_constant_evaluated()) {
402 return static_cast<uint64_t>(std::popcount(x));
403 }
404 return __popcnt64(x);
405}
406
407/**
408 * @brief 64x64 -> 128-bit unsigned multiply, wrapping the MULX instruction.
409 *
410 * MSVC has no 128 bit integer type to fall back on, so the constant evaluated path assembles the
411 * product from four 32x32 -> 64 bit partial products, the schoolbook algorithm on 32 bit limbs.
412 *
413 * @param a First operand.
414 * @param b Second operand.
415 * @param hi Pointer to receive the upper 64 bits of the product.
416 * @return Lower 64 bits of the product.
417 */
418FP128_FORCE_INLINE constexpr uint64_t mulx_u64(uint64_t a, uint64_t b, uint64_t* hi) noexcept
419{
420 FP128_ASSERT(hi != nullptr); // Caller must provide a valid pointer for the high part.
421 if (std::is_constant_evaluated()) {
422 const uint64_t a_lo = a & UINT32_MAX, a_hi = a >> 32;
423 const uint64_t b_lo = b & UINT32_MAX, b_hi = b >> 32;
424 const uint64_t p_ll = a_lo * b_lo;
425 const uint64_t p_lh = a_lo * b_hi;
426 const uint64_t p_hl = a_hi * b_lo;
427 const uint64_t p_hh = a_hi * b_hi;
428 // The middle column holds the carry out of the low 32 bits plus the low halves of both
429 // cross products. Three values below 2^32 cannot overflow a 64 bit accumulator.
430 const uint64_t mid = (p_ll >> 32) + (p_lh & UINT32_MAX) + (p_hl & UINT32_MAX);
431 *hi = p_hh + (p_lh >> 32) + (p_hl >> 32) + (mid >> 32);
432 return (mid << 32) | (p_ll & UINT32_MAX);
433 }
434 return _mulx_u64(a, b, hi);
435}
436
437/**
438 * @brief 64-bit add with carry, wrapping the ADCX instruction.
439 * @param c Input carry (0 or 1).
440 * @param a First operand.
441 * @param b Second operand.
442 * @param out Pointer to receive the 64-bit sum.
443 * @return Output carry (0 or 1).
444 */
445FP128_FORCE_INLINE constexpr unsigned char addcarryx_u64(unsigned char c, uint64_t a, uint64_t b, uint64_t* out) noexcept
446{
447 FP128_ASSERT(out != nullptr); // Caller must provide a valid pointer for the result.
448 if (std::is_constant_evaluated()) {
449 // Unsigned addition wraps, so a sum that came out smaller than an operand is exactly the
450 // carry out. The total is at most 2^65-1, so at most one of the two additions can carry.
451 const uint64_t sum = a + b;
452 const uint64_t res = sum + c;
453 *out = res;
454 return static_cast<unsigned char>((sum < a) | (res < sum));
455 }
456 return _addcarryx_u64(c, a, b, out);
457}
458
459/**
460 * @brief 64-bit subtract with borrow, wrapping the SBB instruction.
461 * @param b Input borrow (0 or 1).
462 * @param a Minuend.
463 * @param c Subtrahend.
464 * @param out Pointer to receive the 64-bit difference.
465 * @return Output borrow (0 or 1).
466 */
467FP128_FORCE_INLINE constexpr unsigned char subborrow_u64(unsigned char b, uint64_t a, uint64_t c, uint64_t* out) noexcept
468{
469 FP128_ASSERT(out != nullptr); // Caller must provide a valid pointer for the result.
470 if (std::is_constant_evaluated()) {
471 // Unsigned subtraction wraps, so a difference that came out larger than the minuend is
472 // exactly the borrow out. The result is at least -(2^65-1), so at most one of the two
473 // subtractions can borrow.
474 const uint64_t diff = a - c;
475 const uint64_t res = diff - b;
476 *out = res;
477 return static_cast<unsigned char>((diff > a) | (res > diff));
478 }
479 return _subborrow_u64(b, a, c, out);
480}
481
482//
483// GCC/Clang portable fallback implementations
484//
485#elif defined(FP128_CLANG)
486// The funnel shifts fall back to this library's own implementations.
487//
488// These deliberately do NOT reuse the __shiftright128 / __shiftleft128 spelling. Those names
489// belong to the implementation, and Microsoft's STL calls them for real inside __msvc_int128.hpp,
490// which <algorithm> and friends pull in. Defining them as macros here rewrites those calls to an
491// unqualified name that is not visible at that point, so any translation unit that reached an
492// fp128 header before <algorithm> failed to compile. Prefixing the macro keeps the two apart.
493#define FP128_SHIFTRIGHT128 shift_right128
494#define FP128_SHIFTLEFT128 shift_left128
495
496#if defined(FP128_ARM64)
497#include <arm_neon.h> // for the uint8x8_t type used as an operand of the NEON population count assembly
498#else
499#include <immintrin.h> // for _subborrow_u64, see the note on subborrow_u64() below
500#endif
501
502/**
503 * @brief Portable 32-bit unsigned division with remainder (GCC/Clang fallback).
504 *
505 * On AArch64 this is a single UDIV followed by an MSUB (multiply-subtract) which computes
506 * the remainder without a second division. Both operands are widened to 64 bit, matching the
507 * x86 _udiv64 semantics of a 64 bit numerator; unlike x86 there is no trap when the quotient
508 * exceeds 32 bits, the value is simply truncated.
509 *
510 * @param dividend Numerator.
511 * @param divisor Denominator.
512 * @param remainder Pointer to receive the remainder (may be nullptr).
513 * @return Quotient.
514 */
515FP128_FORCE_INLINE constexpr uint32_t udiv64(uint64_t dividend, uint32_t divisor, uint32_t* remainder)
516{
517#if defined(FP128_ARM64)
518 // Inline assembly is not allowed during constant evaluation, use the portable path instead.
519 if (!std::is_constant_evaluated()) {
520 const uint64_t divisor64 = divisor;
521 uint64_t quot64 = 0, rem64 = 0;
522 // quot64 = dividend / divisor64
523 // rem64 = dividend - quot64 * divisor64
524 __asm__("udiv %[q], %[n], %[d]\n\t"
525 "msub %[r], %[q], %[d], %[n]"
526 : [q] "=&r"(quot64), [r] "=r"(rem64) // q is early-clobber: MSUB reads n and d after q was written
527 : [n] "r"(dividend), [d] "r"(divisor64));
528 if (remainder) {
529 *remainder = static_cast<uint32_t>(rem64);
530 }
531 return static_cast<uint32_t>(quot64);
532 }
533#endif
534 uint32_t quot = dividend / divisor;
535 if (remainder) {
536 *remainder = dividend % divisor;
537 }
538 return quot;
539}
540
541/**
542 * @brief 128-bit by 64-bit unsigned division (GCC/Clang counterpart of the _udiv128 intrinsic).
543 *
544 * @warning The quotient must fit in 64 bits, which means @p hi_dividend must be smaller than
545 * @p divisor. This is the same precondition the MSVC _udiv128 intrinsic carries, and
546 * for the same reason: both compile to the x86 DIV instruction, which raises #DE rather
547 * than truncating. Both callers satisfy it - div_128bit() normalizes its divisor so the
548 * high word it passes is always the smaller, and div_64bit() passes the remainder of a
549 * previous division by the same divisor.
550 *
551 * @note On x86-64 this is one DIV instruction, written as assembly because there is no builtin
552 * for it and the portable expression below does not produce it: Clang cannot prove the
553 * quotient fits, so it lowers `__uint128_t / uint64_t` to a __udivti3 call - a full software
554 * 128/128 division. That call cost 2.8x on `uint128_t` division against MSVC, which has the
555 * intrinsic.
556 *
557 * @note AArch64 has no 128/64 bit divide instruction (UDIV is at most 64/64), so it keeps the
558 * portable path, where the __uint128_t expression lowers to the compiler runtime helper
559 * (__udivti3 / __umodti3) - still faster than any short hand written long division. Callers
560 * on ARM64 should prefer the reciprocal based division path
561 * (see FP128_USE_RECIPROCAL_FOR_DIVISION) built on mulx_u64.
562 *
563 * @param hi_dividend Upper 64 bits of the 128-bit dividend. Must be smaller than @p divisor.
564 * @param lo_dividend Lower 64 bits of the 128-bit dividend.
565 * @param divisor 64-bit divisor.
566 * @param remainder Pointer to receive the 64-bit remainder (may be nullptr).
567 * @return 64-bit quotient.
568 */
569FP128_FORCE_INLINE constexpr uint64_t udiv128(uint64_t hi_dividend, uint64_t lo_dividend, uint64_t divisor, uint64_t* remainder)
570{
571#if defined(FP128_X64)
572 // Inline assembly is not allowed during constant evaluation, use the portable path instead.
573 if (!std::is_constant_evaluated()) {
574 uint64_t quot = 0, rem = 0;
575 // DIV divides RDX:RAX by its operand, leaving the quotient in RAX and the remainder in
576 // RDX. The divisor is constrained to a register rather than "rm" for two reasons: it
577 // cannot then land in either of those - the two tied operands already hold RAX and RDX,
578 // so the allocator has to pick a third register - and a register operand carries its own
579 // width, which lets the mnemonic go without the "q" suffix and so assemble under either
580 // inline assembly dialect. DIV leaves the flags undefined, hence the "cc" clobber.
581 __asm__("div %[d]" : "=a"(quot), "=d"(rem) : [d] "r"(divisor), "a"(lo_dividend), "d"(hi_dividend) : "cc");
582 if (remainder) {
583 *remainder = rem;
584 }
585 return quot;
586 }
587#endif
588 __uint128_t dividend = (static_cast<__uint128_t>(hi_dividend) << 64) | lo_dividend;
589 uint64_t quot = static_cast<uint64_t>(dividend / divisor);
590 if (remainder) {
591 *remainder = static_cast<uint64_t>(dividend % divisor);
592 }
593 return quot;
594}
595
596/**
597 * @brief 64x64 -> 128-bit unsigned multiply (GCC/Clang fallback for _mulx_u64).
598 *
599 * The AArch64 variant uses the MUL/UMULH instruction pair, the direct equivalent of the x86
600 * MULX instruction. The two instructions are independent and dual issue on Apple Silicon.
601 *
602 * @param a First operand.
603 * @param b Second operand.
604 * @param hi Pointer to receive the upper 64 bits of the product.
605 * @return Lower 64 bits of the product.
606 */
607FP128_FORCE_INLINE static constexpr uint64_t mulx_u64(uint64_t a, uint64_t b, uint64_t* hi) noexcept
608{
609 FP128_ASSERT(hi != nullptr); // Caller must provide a valid pointer for the high part. Compatibility with MSVC intrinsic.
610#if defined(FP128_ARM64)
611 // Inline assembly is not allowed during constant evaluation, use the portable path instead.
612 if (!std::is_constant_evaluated()) {
613 uint64_t lo_res = 0, hi_res = 0;
614 __asm__("umulh %[hi], %[a], %[b]\n\t"
615 "mul %[lo], %[a], %[b]"
616 : [hi] "=&r"(hi_res), [lo] "=r"(lo_res) // hi is early-clobber: MUL reads a and b after hi was written
617 : [a] "r"(a), [b] "r"(b));
618 *hi = hi_res;
619 return lo_res;
620 }
621#endif
622 __uint128_t r = (__uint128_t)a * b;
623 *hi = (uint64_t)(r >> 64);
624 return (uint64_t)r;
625}
626
627/**
628 * @brief 64-bit add with carry (GCC/Clang fallback for _addcarryx_u64).
629 *
630 * The AArch64 variant mirrors the x86 ADCX sequence: CMP materializes the incoming carry into
631 * the C flag (the unsigned compare c - 1 sets C when c is non zero), ADCS performs the addition
632 * with that carry and updates the flags, and CSET extracts the outgoing carry.
633 *
634 * @param c Input carry (0 or 1).
635 * @param a First operand.
636 * @param b Second operand.
637 * @param out Pointer to receive the 64-bit sum.
638 * @return Output carry (0 or 1).
639 */
640FP128_FORCE_INLINE static constexpr unsigned char addcarryx_u64(unsigned char c, uint64_t a, uint64_t b, uint64_t* out) noexcept
641{
642 FP128_ASSERT(out != nullptr); // Caller must provide a valid pointer for the result. Compatibility with MSVC intrinsic.
643#if defined(FP128_ARM64)
644 // Inline assembly is not allowed during constant evaluation, use the portable path instead.
645 if (!std::is_constant_evaluated()) {
646 uint64_t sum = 0;
647 uint32_t carry_out = 0;
648 __asm__("cmp %w[cin], #1\n\t" // C = (cin != 0)
649 "adcs %[sum], %[a], %[b]\n\t"
650 "cset %w[cout], cs"
651 : [sum] "=&r"(sum), [cout] "=&r"(carry_out) // both outputs are early-clobber, they must not alias the inputs
652 : [cin] "r"((uint32_t)c), [a] "r"(a), [b] "r"(b)
653 : "cc");
654 *out = sum;
655 return (unsigned char)carry_out;
656 }
657#endif
658 __uint128_t r = (__uint128_t)a + b + c;
659 *out = (uint64_t)r;
660 return (unsigned char)(r >> 64);
661}
662
663/**
664 * @brief 64-bit subtract with borrow (GCC/Clang fallback for _subborrow_u64).
665 *
666 * On x86 this calls the same intrinsic MSVC does, rather than leaving the __uint128_t expression
667 * below to be recognized. The recognition is not symmetric with addition: two chained
668 * addcarryx_u64 calls become the ADD/ADC pair they describe, but two chained calls to the portable
669 * form of this function do not become SUB/SBB. LLVM instead materializes the borrow into a register
670 * with `sbb reg, reg` and folds it back in with a second subtraction, which turns a two instruction
671 * operation into seven and lengthens the dependent chain from one cycle to about one and a half.
672 * That cost the uint128_t subtraction benchmark a third of its throughput against the addition it
673 * should tie with (3.47G/s against 5.10G/s on Clang 17; the intrinsic restores it to 5.10G/s).
674 *
675 * AArch64 has no such intrinsic and does not need one: there the __uint128_t expression already
676 * lowers to the SUBS/SBCS pair a hand written assembly variant would have spelled out.
677 *
678 * @param b Input borrow (0 or 1).
679 * @param a Minuend.
680 * @param c Subtrahend.
681 * @param out Pointer to receive the 64-bit difference.
682 * @return Output borrow (0 or 1).
683 */
684FP128_FORCE_INLINE static constexpr unsigned char subborrow_u64(unsigned char b, uint64_t a, uint64_t c, uint64_t* out) noexcept
685{
686 FP128_ASSERT(out != nullptr); // Caller must provide a valid pointer for the result. Compatibility with MSVC intrinsic.
687#if !defined(FP128_ARM64)
688 // Intrinsics are not allowed during constant evaluation, use the portable path instead.
689 if (!std::is_constant_evaluated()) {
690 // The intrinsic writes an unsigned long long, which is a distinct type from uint64_t on
691 // the LP64 targets even though both are 64 bit. Going through a local keeps the call free
692 // of a cast between two pointer types the optimizer is entitled to assume cannot alias.
693 unsigned long long diff = 0;
694 const unsigned char borrow = _subborrow_u64(b, a, c, &diff);
695 *out = static_cast<uint64_t>(diff);
696
697 return borrow;
698 }
699#endif
700 __uint128_t r = (__uint128_t)a - c - b;
701 *out = (uint64_t)r;
702 // The difference wraps when it borrows, so bit 64 of the 128-bit result is the borrow out.
703 return (unsigned char)((r >> 64) & 1);
704}
705
706/**
707 * @brief Count leading zeros in a 32-bit value (GCC/Clang fallback).
708 *
709 * The AArch64 CLZ instruction is defined for a zero operand (it returns the operand width),
710 * so unlike the x86 BSR based lowering no zero test is needed.
711 */
712FP128_FORCE_INLINE static constexpr uint32_t lzcnt32(uint32_t x) noexcept
713{
714#if defined(FP128_ARM64)
715 // Inline assembly is not allowed during constant evaluation, use the portable path instead.
716 if (!std::is_constant_evaluated()) {
717 uint32_t res = 0;
718 __asm__("clz %w[res], %w[val]" : [res] "=r"(res) : [val] "r"(x));
719 return res;
720 }
721#endif
722 return (x == 0) ? 32u : (uint32_t)__builtin_clz(x);
723}
724
725/**
726 * @brief Count leading zeros in a 64-bit value (GCC/Clang fallback).
727 *
728 * The AArch64 CLZ instruction returns 64 for a zero operand, no zero test is needed.
729 */
730FP128_FORCE_INLINE static constexpr uint64_t lzcnt64(uint64_t x) noexcept
731{
732#if defined(FP128_ARM64)
733 // Inline assembly is not allowed during constant evaluation, use the portable path instead.
734 if (!std::is_constant_evaluated()) {
735 uint64_t res = 0;
736 __asm__("clz %[res], %[val]" : [res] "=r"(res) : [val] "r"(x));
737 return res;
738 }
739#endif
740 return (x == 0) ? 64u : (uint64_t)__builtin_clzll(x);
741}
742
743/**
744 * @brief Count set bits in a 64-bit value (GCC/Clang fallback).
745 *
746 * AArch64 has no general purpose register population count before ARMv8.9 (FEAT_CSSC), which
747 * Apple Silicon does not implement. The value is moved to a NEON register, CNT counts the bits
748 * of each of the 8 bytes in parallel and ADDV sums the 8 byte lanes into a single byte.
749 */
750FP128_FORCE_INLINE static constexpr uint64_t popcnt64(uint64_t x) noexcept
751{
752#if defined(FP128_ARM64)
753 // Inline assembly is not allowed during constant evaluation, use the portable path instead.
754 if (!std::is_constant_evaluated()) {
755 uint32_t res = 0;
756 uint8x8_t tmp;
757 __asm__("fmov %d[tmp], %[val]\n\t"
758 "cnt %[tmp].8b, %[tmp].8b\n\t"
759 "addv %b[tmp], %[tmp].8b\n\t"
760 "fmov %w[res], %s[tmp]"
761 : [res] "=r"(res), [tmp] "=&w"(tmp)
762 : [val] "r"(x));
763 return res;
764 }
765#endif
766 return (uint64_t)__builtin_popcountll(x);
767}
768
769/**
770 * @brief Count set bits in a 32-bit value (GCC/Clang fallback).
771 *
772 * Same NEON sequence as popcnt64. FMOV of a W register zeroes the upper lanes of the NEON
773 * register, so the 4 unused bytes contribute nothing to the ADDV sum.
774 */
775FP128_FORCE_INLINE static constexpr uint32_t popcnt32(uint32_t x) noexcept
776{
777#if defined(FP128_ARM64)
778 // Inline assembly is not allowed during constant evaluation, use the portable path instead.
779 if (!std::is_constant_evaluated()) {
780 uint32_t res = 0;
781 uint8x8_t tmp;
782 __asm__("fmov %s[tmp], %w[val]\n\t"
783 "cnt %[tmp].8b, %[tmp].8b\n\t"
784 "addv %b[tmp], %[tmp].8b\n\t"
785 "fmov %w[res], %s[tmp]"
786 : [res] "=r"(res), [tmp] "=&w"(tmp)
787 : [val] "r"(x));
788 return res;
789 }
790#endif
791 return (uint32_t)__builtin_popcount(x);
792}
793
794#endif // #if defined (FP128_CLANG)
795
796// portable alignment macro
797#if defined(FP128_MSVC)
798#define FP128_ALIGN(_a) __declspec(align(_a))
799//
800// Clang/GCC specific macros
801//
802#elif defined(FP128_CLANG)
803#define FP128_ALIGN(_a) __attribute__((aligned(_a)))
804#endif
805
806#define FP128_ALIGN16 FP128_ALIGN(16)
807/** @} */ // end Platform-Specific Intrinsics
808
809/**
810 * @brief Everything the library provides.
811 *
812 * The namespace holds four value types and the free functions that operate on them:
813 *
814 * - fp128::int128_t and fp128::uint128_t, 128 bit integers, both aliases of fp128::int128_base.
815 * - fp128::fixed_point128, a fixed point type whose single template parameter splits the 128 bits
816 * between the integer and the fraction.
817 * - fp128::float128, an IEEE 754 binary128 floating point type.
818 *
819 * Each of them supports the operators, the `<cmath>` functions, the `std::numeric_limits`,
820 * `std::hash` and `std::formatter` specializations, and the stream insertion and extraction that
821 * the corresponding builtin type does, so they can stand in for one in generic code.
822 *
823 * The rest of the namespace is the machinery those types are built from - 128 bit shifts, multiply,
824 * divide and bit counting over pairs of QWORDs - which is public because the types are header only
825 * and inline everything, not because a user is expected to call it.
826 */
827namespace fp128
828{
829
830/***********************************************************************************
831 * Constants
832 ************************************************************************************/
833
834/// @name Library Version
835/// @brief The FP128_VERSION_* macros as constants, for code that reports the version rather than
836/// branching on it at preprocessing time.
837/// @{
838static constexpr int32_t version_major = FP128_VERSION_MAJOR; ///< Breaking changes to the public interface.
839static constexpr int32_t version_minor = FP128_VERSION_MINOR; ///< Backwards compatible additions.
840static constexpr int32_t version_patch = FP128_VERSION_PATCH; ///< Fixes that change neither.
841static constexpr int32_t version_build = FP128_VERSION_BUILD; ///< Rebuild of an unchanged source tree.
842static constexpr int32_t version = FP128_VERSION; ///< All four packed into one comparable integer.
843static constexpr const char* version_string = FP128_VERSION_STRING; ///< Dotted form, e.g. "0.9.0.0".
844/// @}
845
846/// @name IEEE 754 Layout Constants
847/// @{
848static constexpr int32_t flt_frac_bits = 23; ///< Mantissa bit count of an IEEE 754 float.
849static constexpr int32_t flt_exp_bits = 8; ///< Exponent bit count of an IEEE 754 float.
850static constexpr int32_t dbl_frac_bits = 52; ///< Mantissa bit count of an IEEE 754 double.
851static constexpr int32_t dbl_exp_bits = 11; ///< Exponent bit count of an IEEE 754 double.
852/// @}
853
854/***********************************************************************************
855 * Containers
856 ************************************************************************************/
857/**
858 * @struct Double
859 * @brief Bit level view of an IEEE 754 double-precision value.
860 *
861 * Gives access to the mantissa, exponent and sign of a double without manual bit shifting, and
862 * assembles a double back out of those three fields.
863 *
864 * The value is held as a raw bit pattern and converted with std::bit_cast rather than being
865 * overlaid with a union. The two produce identical code - a single move between register classes -
866 * but reading the inactive member of a union is not allowed during constant evaluation, which
867 * would keep every conversion between these types and a double out of a constant expression.
868 */
869struct Double {
870 uint64_t bits; ///< The raw bit pattern of the double.
871
872 /// @brief Constructs from a double, or from positive zero when no value is given.
873 constexpr Double(double v = 0) noexcept : bits(std::bit_cast<uint64_t>(v)) {}
874
875 /// @brief Mantissa (fraction) bits.
876 [[nodiscard]] constexpr uint64_t f() const noexcept { return bits & FRAC_MASK; }
877 /// @brief Biased exponent bits.
878 [[nodiscard]] constexpr uint64_t e() const noexcept { return (bits >> dbl_frac_bits) & EXP_MASK; }
879 /// @brief Sign bit (0 = positive, 1 = negative).
880 [[nodiscard]] constexpr uint64_t s() const noexcept { return bits >> SIGN_SHIFT; }
881 /// @brief The double these bits encode.
882 [[nodiscard]] constexpr double val() const noexcept { return std::bit_cast<double>(bits); }
883
884 /// @brief Sets the mantissa. Bits above the field width are dropped, as a bit-field assignment would.
885 constexpr void set_f(uint64_t v) noexcept { bits = (bits & ~FRAC_MASK) | (v & FRAC_MASK); }
886 /// @brief Sets the biased exponent. Bits above the field width are dropped.
887 constexpr void set_e(uint64_t v) noexcept { bits = (bits & ~(EXP_MASK << dbl_frac_bits)) | ((v & EXP_MASK) << dbl_frac_bits); }
888 /// @brief Sets the sign bit.
889 constexpr void set_s(uint64_t v) noexcept { bits = (bits & ~(1ull << SIGN_SHIFT)) | ((v & 1) << SIGN_SHIFT); }
890
891 /**
892 * @brief Assembles a double out of its three fields.
893 *
894 * Preferred over three set_ calls wherever the value is built from scratch: those each mask
895 * the old field out before merging the new one, which is wasted work when there is nothing
896 * there yet.
897 *
898 * @param s Sign bit.
899 * @param e Biased exponent. Bits above the field width are dropped.
900 * @param f Mantissa. Bits above the field width are dropped.
901 * @return The assembled double.
902 */
903 [[nodiscard]] static constexpr double make(uint64_t s, uint64_t e, uint64_t f) noexcept
904 {
905 return std::bit_cast<double>(((s & 1) << SIGN_SHIFT) | ((e & EXP_MASK) << dbl_frac_bits) | (f & FRAC_MASK));
906 }
907
908private:
909 static constexpr uint64_t FRAC_MASK = (1ull << dbl_frac_bits) - 1; ///< Mask of the mantissa field.
910 static constexpr uint64_t EXP_MASK = (1ull << dbl_exp_bits) - 1; ///< Mask of the exponent field, once shifted down.
911 static constexpr int32_t SIGN_SHIFT = dbl_frac_bits + dbl_exp_bits; ///< Bit position of the sign.
912};
913static_assert(sizeof(Double) == sizeof(double), "The Double view should have the same size as a double variable!");
914
915/**
916 * @struct Float
917 * @brief Bit level view of an IEEE 754 single-precision value.
918 *
919 * The single precision counterpart of @ref Double, see its documentation.
920 */
921struct Float {
922 uint32_t bits; ///< The raw bit pattern of the float.
923
924 /// @brief Constructs from a float, or from positive zero when no value is given.
925 constexpr Float(float v = 0) noexcept : bits(std::bit_cast<uint32_t>(v)) {}
926
927 /// @brief Mantissa (fraction) bits.
928 [[nodiscard]] constexpr uint32_t f() const noexcept { return bits & FRAC_MASK; }
929 /// @brief Biased exponent bits.
930 [[nodiscard]] constexpr uint32_t e() const noexcept { return (bits >> flt_frac_bits) & EXP_MASK; }
931 /// @brief Sign bit (0 = positive, 1 = negative).
932 [[nodiscard]] constexpr uint32_t s() const noexcept { return bits >> SIGN_SHIFT; }
933 /// @brief The float these bits encode.
934 [[nodiscard]] constexpr float val() const noexcept { return std::bit_cast<float>(bits); }
935
936 /// @brief Sets the mantissa. Bits above the field width are dropped, as a bit-field assignment would.
937 constexpr void set_f(uint32_t v) noexcept { bits = (bits & ~FRAC_MASK) | (v & FRAC_MASK); }
938 /// @brief Sets the biased exponent. Bits above the field width are dropped.
939 constexpr void set_e(uint32_t v) noexcept { bits = (bits & ~(EXP_MASK << flt_frac_bits)) | ((v & EXP_MASK) << flt_frac_bits); }
940 /// @brief Sets the sign bit.
941 constexpr void set_s(uint32_t v) noexcept { bits = (bits & ~(1u << SIGN_SHIFT)) | ((v & 1) << SIGN_SHIFT); }
942
943 /// @brief Assembles a float out of its three fields, see Double::make().
944 /// @param s Sign bit. @param e Biased exponent. @param f Mantissa. @return The assembled float.
945 [[nodiscard]] static constexpr float make(uint32_t s, uint32_t e, uint32_t f) noexcept
946 {
947 return std::bit_cast<float>(((s & 1) << SIGN_SHIFT) | ((e & EXP_MASK) << flt_frac_bits) | (f & FRAC_MASK));
948 }
949
950private:
951 static constexpr uint32_t FRAC_MASK = (1u << flt_frac_bits) - 1; ///< Mask of the mantissa field.
952 static constexpr uint32_t EXP_MASK = (1u << flt_exp_bits) - 1; ///< Mask of the exponent field, once shifted down.
953 static constexpr int32_t SIGN_SHIFT = flt_frac_bits + flt_exp_bits; ///< Bit position of the sign.
954};
955static_assert(sizeof(Float) == sizeof(float), "The Float view should have the same size as a float variable!");
956
957/***********************************************************************************
958 * Functions
959 ************************************************************************************/
960
961/**
962 * @brief Copy a string to lowercase, up to n characters.
963 * @param dest Destination buffer.
964 * @param src Source string.
965 * @param n Maximum number of characters to copy.
966 * @return 0 on success, EINVAL if dest or src is nullptr.
967 */
968FP128_INLINE static errno_t strnlwr(char* dest, const char* src, size_t n) noexcept
969{
970 if (src == nullptr || dest == nullptr)
971 return EINVAL;
972 size_t i = 0;
973 for (; i < n && src[i] != '\0'; ++i) {
974 dest[i] = static_cast<char>(::tolower(static_cast<unsigned char>(src[i])));
975 }
976 if (i < n)
977 dest[i] = '\0';
978 return 0;
979}
980
981/**
982 * @brief Calculates the element count of a C style array at build time
983 * Example:
984 * int a[5];
985 * constexpr int len = array_length(a); // returns 5 at build time
986 * @tparam T array type
987 * @param a array instance
988 * @return Element count in array
989 */
990template <typename T>[[nodiscard]] constexpr uint32_t array_length(const T& a)
991{
992 static_assert(sizeof(a[0]) != 0, "Requires an array of non-zero sized elements!");
993 return sizeof(a) / sizeof(a[0]);
994}
995/**
996 * @brief Right-shift a 64-bit value with rounding.
997 *
998 * Undefined behavior when shift is outside the range [1, 63].
999 *
1000 * @param x Value to shift.
1001 * @param shift Number of bits to shift.
1002 * @return The rounded result of x >> shift.
1003 */
1004[[nodiscard]] FP128_INLINE constexpr uint64_t shift_right64_round(uint64_t x, int shift) noexcept
1005{
1006 FP128_ASSERT(shift > 0 && shift < 64);
1007 x += 1ull << (shift - 1);
1008 return x >> shift;
1009}
1010
1011/**
1012 * @brief Right shift a 128 bit unsigned integer (inplace).
1013 * Limited range, inplace and no parameter checks (checked via assert in debug builds)
1014 * @param l Low QWORD
1015 * @param h High QWORD
1016 * @param shift Bits to shift, between 1-63
1017 */
1018FP128_INLINE constexpr void shift_right128_inplace(uint64_t& l, uint64_t& h, int shift) noexcept
1019{
1020 FP128_ASSERT(shift > 0 && shift < 64);
1021 l = (l >> shift) | (h << (64 - shift));
1022 h >>= shift;
1023}
1024/**
1025 * @brief Left shift a 128 bit integer (inplace).
1026 * Limited range, inplace and no parameter checks (checked via assert in debug builds)
1027 * @param l Low QWORD
1028 * @param h High QWORD
1029 * @param shift Bits to shift, between 1-63
1030 */
1031FP128_INLINE constexpr void shift_left128_inplace(uint64_t& l, uint64_t& h, int shift) noexcept
1032{
1033 FP128_ASSERT(shift > 0 && shift < 64);
1034 h = (h << shift) | (l >> (64 - shift));
1035 l <<= shift;
1036}
1037/**
1038 * @brief Adds a rounding bit into a 128 bit value held as two QWORDs, as l and h are named there.
1039 *
1040 * A macro rather than a function because the two QWORDs are always members of the caller, and
1041 * taking references to them is what a function would have to do. MSVC then keeps them in memory
1042 * for the whole of the surrounding routine even with __forceinline, which costs more than this
1043 * whole operation is worth: written as a function it made fixed_point128<10>::log2() 40% slower.
1044 *
1045 * The rounding bit is bit F-1 of a product, which is as good as random for every caller that
1046 * multiplies data rather than constants. A branch on it therefore mispredicts about half the time,
1047 * and this macro sits in operator*=() and square(), the two hottest routines in the library. The
1048 * carry propagating form has no branch to mispredict: BT sets the carry flag and two ADCs consume
1049 * it, four instructions of fixed latency.
1050 *
1051 * Both compilers want that form, and MSVC wants it far more than Clang does. MSVC used to be given
1052 * the branch instead, on the strength of a log2() measurement in which it if converted the branch
1053 * into a conditional move; that if conversion is not something it does reliably, and in the
1054 * Mandelbrot escape-time loop of a real renderer it emits a real branch, three per iteration on three
1055 * unpredictable bits. There the change is worth 1.9x - a 640x360 frame at 2048 iterations goes from
1056 * 625ms to 324ms, taking MSVC from roughly half of clang-cl's speed to level with it.
1057 *
1058 * Measured on an i9-12900K, one core, fastest of three runs, over the 32 fixed_point128<10>
1059 * benchmarks in bench/Bench.cpp. Ratios are the carry propagating form against the branch:
1060 *
1061 * | | MSVC P-core | MSVC E-core | Clang P-core |
1062 * | -------------------------- | ----------- | ----------- | ------------ |
1063 * | median over all 32 | +52% | +43% | +6.7% |
1064 * | exp2 / exp / pow / expm1 | 1.87-1.81x | 1.77-1.74x | 1.17-1.11x |
1065 * | atan / asin / acos | 1.78-1.67x | 1.61-1.40x | 1.09-1.00x |
1066 * | tan / sin / cos | 1.63-1.56x | 1.50-1.43x | 1.03-1.01x |
1067 * | log2 / log | 1.54-1.55x | 1.62-1.63x | 1.15-1.14x |
1068 * | sqrt, reciprocal | -2%, -3% | 0%, +20% | +1%, +3% |
1069 * | isolated operator*=() loop | -7% | 2.01x | -4% |
1070 *
1071 * The transcendentals gain most because they reach this code once per bit of their result, so the
1072 * rounding was a large part of their inner loop. The isolated multiplication loop is the one case
1073 * that regresses on a P-core: accumulating a single product per iteration leaves the core enough
1074 * slack to hide the branch, which no caller that chains multiplications gives it. The same loop is
1075 * twice as fast on an E-core, whose narrower recovery pays more for a misprediction than it saves.
1076 *
1077 * A warning for anyone re-measuring this. Until 2026-08-21 bench/Bench.cpp built its operands as an
1078 * arithmetic progression and multiplied them by an operand that silently saturated to the type
1079 * maximum, which made the rounding bit **1 for every argument in the set** - a branch that never
1080 * changes direction is free, and the benchmark reported this change as a 6% regression. Randomising
1081 * the operands costs the branch build 45-48% on the transcendentals and the carry build 1-3%; that
1082 * asymmetry is the check that the benchmark can see a misprediction at all. bench_mandelbrot() still
1083 * shows a small loss because it iterates one bounded orbit with no escape test, the shape MSVC does
1084 * if convert - it is not a substitute for measuring a real render.
1085 */
1086#define FP128_ADD_ROUND_BIT(l, h, round_up) ((h) += addcarryx_u64(0, (l), static_cast<uint64_t>(round_up), &(l)))
1087/**
1088 * @brief Right shift of an unsigned 128 bit integer (inplace), rounded to nearest with a tie going up.
1089 *
1090 * The magnitude is divided by 2^shift and rounded to the nearest integer; an exact tie rounds up,
1091 * which for a magnitude is away from zero. That is the rule fixed_point128 applies to every rounded
1092 * result - the multiply, the divisions and the signed shift below - so a value gets the same answer
1093 * whichever of them produced it.
1094 *
1095 * Rounding half up needs no sticky bit: the result moves up exactly when the highest dropped bit is
1096 * set, whatever lies below it, which keeps this free of branches beyond the choice of QWORD.
1097 *
1098 * @param l Low QWORD
1099 * @param h High QWORD
1100 * @param shift Bits to shift, any non negative count. 128 rounds 2^127 and above up to one, more
1101 * than 128 always leaves zero.
1102 */
1103FP128_FORCE_INLINE constexpr void shift_right128_inplace_safe(uint64_t& l, uint64_t& h, int shift) noexcept
1104{
1105 FP128_ASSERT(shift >= 0);
1106 if (shift == 0)
1107 return;
1108
1109 uint64_t round_bit = 0; // the highest bit shifted out
1110 switch (shift >> 6) {
1111 case 0: // 1-63 bit
1112 round_bit = (l >> (shift - 1)) & 1;
1113 l = (l >> shift) | (h << (64 - shift));
1114 h >>= shift;
1115 break;
1116 case 1: // 64-127 bit
1117 round_bit = (shift == 64) ? (l >> 63) : ((h >> (shift - 65)) & 1);
1118 l = h >> (shift - 64);
1119 h = 0;
1120 break;
1121 default: // 128 bit and above
1122 round_bit = (shift == 128) ? (h >> 63) : 0;
1123 h = l = 0;
1124 }
1125
1126 // a plain add and compare, which the compiler turns into ADD and ADC
1127 l += round_bit;
1128 h += static_cast<uint64_t>(l < round_bit);
1129}
1130/**
1131 * @brief The shifts by 64 bits or more of shift_right128_inplace_safe_signed().
1132 *
1133 * Kept apart so that the common case stays small: the callers of that function, the shift operators
1134 * of fixed_point128 among them, are inlined only while it is, and a shift by a constant count then
1135 * folds down to a handful of instructions. The QWORDs travel by value: a reference would take their
1136 * address and push the caller's value through memory on the common path as well.
1137 *
1138 * Only the low QWORD of the result is returned. The high one is the sign of the input, or zero when
1139 * the low QWORD is zero: the quotient fits in 64 bits, and a negative one is never zero there unless
1140 * rounding carried it all the way up from minus one half.
1141 *
1142 * @param l Low QWORD
1143 * @param h High QWORD, holding the sign in its MSB
1144 * @param shift Bits to shift, 64 or more
1145 * @return The low QWORD of the rounded quotient.
1146 */
1147[[nodiscard]] constexpr uint64_t shift_right128_wide_signed_low(uint64_t l, uint64_t h, int shift) noexcept
1148{
1149 FP128_ASSERT(shift >= 64);
1150 const int64_t value = static_cast<int64_t>(h);
1151 const uint64_t sign_bits = static_cast<uint64_t>(value >> 63); // all zeros or all ones
1152 if (shift >= 128) {
1153 // the quotient is in [-1/2, 1/2), and only lowest() shifted by exactly 128 reaches -1/2: a
1154 // tie, which goes away from zero to minus one
1155 return (shift == 128 && h == (1ull << 63) && l == 0) ? UINT64_MAX : 0;
1156 }
1157
1158 const int32_t s = shift - 64; // 0-63
1159 // bit shift-1 of the value: bits 126:63 of it are (h << 1) | (l >> 63)
1160 const uint64_t round_bit = (((h << 1) | (l >> 63)) >> s) & 1;
1161 // every bit below it: l, without its top bit when s is zero, and bits [s-2:0] of h. The left
1162 // shift by 2 + 63 - s keeps exactly those, and nothing at all for s below 2.
1163 const bool sticky = ((l << static_cast<int32_t>(s == 0)) | ((h << 2) << (63 - s))) != 0;
1164 const uint64_t round_up = round_bit & (static_cast<uint64_t>(sticky) | (~sign_bits & 1));
1165 return static_cast<uint64_t>(value >> s) + round_up;
1166}
1167/**
1168 * @brief Arithmetic right shift of a 128 bit two's complement value (inplace), rounded to nearest
1169 * with a tie going away from zero.
1170 *
1171 * The signed counterpart of shift_right128_inplace_safe: the vacated top bits are filled with
1172 * copies of the sign bit instead of zeros, so the shift divides by a power of two for negative
1173 * values as well as positive ones. The result is the quotient rounded to the nearest integer, and an
1174 * exact tie goes away from zero - the same answer as rounding the magnitude half up and putting the
1175 * sign back, which is what the multiply and the divisions of fixed_point128 do.
1176 *
1177 * The arithmetic shift itself rounds towards minus infinity. One is added back when the dropped
1178 * part is above one half, or is exactly one half of a non negative value; the sticky bit, which
1179 * tells those two apart, is every dropped bit below the highest one.
1180 *
1181 * A shift of 128 or more leaves zero, except that lowest() shifted by exactly 128 is a tie at minus
1182 * one half and so rounds away from zero, to minus one.
1183 *
1184 * @param l Low QWORD
1185 * @param h High QWORD, holding the sign in its MSB
1186 * @param shift Bits to shift, any non negative count
1187 */
1188FP128_FORCE_INLINE constexpr void shift_right128_inplace_safe_signed(uint64_t& l, uint64_t& h, int shift) noexcept
1189{
1190 FP128_ASSERT(shift >= 0);
1191 if (shift == 0)
1192 return;
1193 if (shift >= 64) {
1194 const uint64_t sign = static_cast<uint64_t>(static_cast<int64_t>(h) >> 63);
1195 l = shift_right128_wide_signed_low(l, h, shift);
1196 h = (l == 0) ? 0 : sign;
1197 return;
1198 }
1199
1200 const uint64_t sign_bits = static_cast<uint64_t>(static_cast<int64_t>(h) >> 63); // all zeros or all ones
1201 const uint64_t round_bit = (l >> (shift - 1)) & 1; // the highest bit shifted out
1202 // bits [shift-2:0] of l, the ones below it, moved to the top. Shifting by one first keeps both
1203 // counts below 64 and makes a shift of one, which has no bit below the rounding bit, give zero.
1204 const bool sticky = ((l << 1) << (64 - shift)) != 0;
1205 l = (l >> shift) | (h << (64 - shift));
1206 h = static_cast<uint64_t>(static_cast<int64_t>(h) >> shift);
1207
1208 // above one half always rounds up; exactly one half rounds up only for a non negative value. A
1209 // plain add and compare, which the compiler turns into ADD and ADC, see shift_right128_inplace_safe.
1210 const uint64_t round_up = round_bit & (static_cast<uint64_t>(sticky) | (~sign_bits & 1));
1211 l += round_up;
1212 h += static_cast<uint64_t>(l < round_up);
1213}
1214/**
1215 * @brief Left shift a 128 bit integer (inplace).
1216 * Handles any positive shift value.
1217 * @param l Low QWORD
1218 * @param h High QWORD
1219 * @param shift Bits to shift, between 1-inf
1220 */
1221FP128_INLINE constexpr void shift_left128_inplace_safe(uint64_t& l, uint64_t& h, int shift) noexcept
1222{
1223 FP128_ASSERT(shift >= 0);
1224 if (shift == 0)
1225 return;
1226
1227 switch (shift >> 6) {
1228 case 0: // 1-63 bit
1229 h = (h << shift) | (l >> (64 - shift));
1230 l <<= shift;
1231 break;
1232 case 1: // 64-127 bit
1233 h = l << (shift - 64);
1234 l = 0;
1235 break;
1236 default: // >127 bit or negative
1237 h = l = 0;
1238 }
1239}
1240/**
1241 * @brief Right shift a 128 bit integer. When shift is a compile time constant, this function generates optimal code for all shift values.
1242 * @param l Low QWORD
1243 * @param h High QWORD
1244 * @
1245 * @return Lower 64 bit of the result
1246 */
1247template <int shift> [[nodiscard]] FP128_INLINE constexpr uint64_t shift_right128(uint64_t l, uint64_t h) noexcept
1248{
1249 FP128_ASSERT(shift >= 0 && shift < 128);
1250 if constexpr (shift == 0) {
1251 return l;
1252 } else if constexpr (shift < 64) {
1253 // Left as the portable spelling on purpose. MSVC does not recognize it as a funnel shift
1254 // and expands it into SHR, SHL and OR where SHRD would be one instruction, and forcing
1255 // __shiftright128 here is 6% faster on a Golden Cove P-core - but 47% slower on a
1256 // Gracemont E-core, where SHRD is microcoded. On a hybrid part the OpenMP render spreads
1257 // over both core types, so the E-core penalty swamps the P-core gain and the whole frame
1258 // gets slower. Clang matches this pattern into SHRD on its own where it pays.
1259 return (l >> shift) | (h << (64 - shift));
1260 } else if constexpr (shift < 128) {
1261 return h >> (shift - 64);
1262 } else {
1263 return 0;
1264 }
1265 }
1266/**
1267 * @brief Left shift a 128 bit integer. When shift is a compile time constant, this function generates optimal code for all shift values.
1268 * @param l Low QWORD
1269 * @param h High QWORD
1270 * @
1271 * @return Upper 64 bit of the result
1272 */
1273 template <int shift> [[nodiscard]] FP128_FORCE_INLINE constexpr uint64_t shift_left128(uint64_t l, uint64_t h) noexcept
1274 {
1275 FP128_ASSERT(shift >= 0 && shift < 128);
1276 if constexpr (shift == 0) {
1277 return h;
1278 } else if constexpr (shift < 64) {
1279 return (h << shift) | (l >> (64 - shift));
1280 } else if constexpr (shift < 128) {
1281 return l << (shift - 64);
1282 } else {
1283 return 0;
1284 }
1285}
1286/**
1287 * @brief Right shift a 128 bit integer.
1288 * @param l Low QWORD
1289 * @param h High QWORD
1290 * @param shift Bits to shift, between 0-127
1291 * @return Lower 64 bit of the result
1292 */
1293[[nodiscard]] FP128_FORCE_INLINE constexpr uint64_t shift_right128(uint64_t l, uint64_t h, int shift) noexcept
1294{
1295 FP128_ASSERT(shift >= 0 && shift < 128);
1296 switch (shift >> 6) {
1297 case 0: // 0-63 bit
1298 // h moves by 64 - shift, which is 64 when shift is 0 and too wide for one shift: that is
1299 // undefined behavior, and x64 hardware would mask it to 0 and OR all of h in. Two shifts
1300 // of at most 63 each give the 0 the math calls for.
1301 return (l >> shift) | ((h << 1) << (63 - shift));
1302 case 1: // 64-127 bit
1303 return h >> (shift ^ 64);
1304 default:
1305 return 0;
1306 }
1307}
1308/**
1309 * @brief Right shift a 128 bit integer with rounding.
1310 * @param l Low QWORD
1311 * @param h High QWORD
1312 * @param shift Bits to shift, between 0-127
1313 * @return Lower 64 bit of the result
1314 */
1315[[nodiscard]] FP128_FORCE_INLINE constexpr uint64_t shift_right128_round(uint64_t l, uint64_t h, int shift) noexcept
1316{
1317 shift_right128_inplace_safe(l, h, shift);
1318 return l;
1319}
1320/**
1321 * @brief Left shift a 128 bit integer.
1322 * @param l Low QWORD
1323 * @param h High QWORD
1324 * @param shift Bits to shift, between 0-127
1325 * @return Upper 64 bit of the result
1326 */
1327[[nodiscard]] FP128_FORCE_INLINE constexpr uint64_t shift_left128(uint64_t l, uint64_t h, int shift) noexcept
1328{
1329 FP128_ASSERT(shift >= 0 && shift < 128);
1330 switch (shift >> 6) {
1331 case 0: // 0-63 bit
1332 // two shifts for the same reason as in shift_right128(): 64 - shift is 64 when shift is 0
1333 return (h << shift) | ((l >> 1) >> (63 - shift));
1334 case 1:
1335 return l << (shift - 64);
1336 default:
1337 return 0;
1338 }
1339}
1340/**
1341 * @brief converts a 128 integer to negative via 2's complement.
1342 * @param l Low QWORD (ref)
1343 * @param h High QWORD (ref)
1344 */
1345FP128_INLINE constexpr void twos_complement128(uint64_t& l, uint64_t& h) noexcept
1346{
1347 l = ~l + 1ull;
1348 h = ~h + (l == 0);
1349}
1350/**
1351 * @brief 64 bit words unsigned divide function. Variation of the code from the book Hacker's Delight.
1352 * @param q (output) Pointer to receive the quotient. Expected to be initialized to zero
1353 * @param r (output, optional) Pointer to receive the remainder. Can be nullptr
1354 * @param u Pointer to Numerator, an array of uint64_t
1355 * @param v denominator (uint64_t)
1356 * @param m Count of elements in u
1357 * @return true on success, false when a pointer is null or the divisor is zero.
1358 */
1359FP128_INLINE static bool div_64bit(uint64_t* q, uint64_t* r, const uint64_t* u, uint64_t v, int64_t m) noexcept
1360{
1361 if (u == nullptr || q == nullptr)
1362 return false;
1363 uint64_t dummy_reminder {};
1364 if (r == nullptr) {
1365 r = &dummy_reminder;
1366 }
1367
1368 if (v == 0) // error case
1369 return false;
1370
1371 while (m > 0 && u[m - 1] == 0)
1372 --m;
1373
1374 // Trivial cases
1375 if (m < 2) {
1376 if (m == 0 || u[0] < v) {
1377 *r = (m == 0) ? 0 : u[0];
1378 return true;
1379 }
1380 if (u[0] == v) {
1381 *q = 1;
1382 *r = 0;
1383 return true;
1384 }
1385 }
1386
1387 uint64_t k[2] = {};
1388 for (auto j = m - 1; j >= 0; --j) {
1389 k[0] = u[j];
1390 q[j] = udiv128(k[1], k[0], v, &k[1]);
1391 }
1392
1393 // Remainder
1394 *r = k[1];
1395 return true;
1396}
1397/**
1398 * @brief Divides an unsigned integer of up to 256 bits by a 128 bit one. Knuth algorithm D, 64 bit limbs.
1399 *
1400 * This is the divide every 128 bit type in this library reaches once the divisor needs more than 64
1401 * bits: int128_t and uint128_t divide 128 by 128, fixed_point128 and float128 divide 256 by 128
1402 * because they scale the numerator by 2^128 first to keep the fraction bits of the quotient.
1403 *
1404 * The limb width is the whole point. The same algorithm over 32 bit limbs sees those shapes as
1405 * m=4,n=4 and m=8,n=4 - up to five main loop passes with a four iteration multiply-subtract in each,
1406 * where 64 bit limbs need one and three passes of two. The quotient estimate costs one DIV
1407 * instruction either way. Measured on the 256/128 shape, pinned to a single core, the wider limbs
1408 * are worth 3.1x under MSVC and 7.9x under clang-cl, and the float128 division benchmarks gain 109%
1409 * and 382% respectively. Narrow limbs also cost Clang more than they cost MSVC: it used to trail by
1410 * 1.6x on this division and is the faster of the two toolchains here.
1411 *
1412 * The estimate needs a 128/64 divide, which x86-64 has and AArch64 does not; udiv128() provides it
1413 * either way, falling back to the compiler runtime helper where there is no instruction.
1414 *
1415 * @note This does not shrink its operands: leading zero words in @p u cost one wasted pass each but
1416 * no accuracy, and a divisor whose high word is zero is rejected rather than handled, because
1417 * that case belongs in div_64bit() which is cheaper again. Every caller here already branches
1418 * on it.
1419 *
1420 * The word count is a template parameter so that every call site gets a division specialized for
1421 * its own shape - the loops unrolled for that count - whether or not the compiler inlines it. Every
1422 * caller in the library knows the count when it compiles. As a function argument it only became a
1423 * constant where the compiler happened to inline the call or specialize it for its call sites, and
1424 * with callers in three headers sharing one out of line copy, clang++ did neither: that copy cost
1425 * fixed_point128's long division 15%. div_128bit(q, r, u, v, m) below takes the count at run time.
1426 *
1427 * @tparam m Count of words in @p u. Must be 2, 3 or 4.
1428 * @param q (output) Quotient, m - 1 words, q[0] lowest. Only those words are written, so a caller
1429 * wanting a wider zero filled result must zero the rest itself.
1430 * @param r (output, optional) Remainder, two words. Can be nullptr.
1431 * @param u Numerator, @p m words, u[0] lowest.
1432 * @param v Denominator, two words. v[1] must be non zero.
1433 * @return true on success, false when a parameter fails one of the conditions above.
1434 */
1435template <int64_t m> FP128_INLINE static bool div_128bit(uint64_t* q, uint64_t* r, const uint64_t* u, const uint64_t* v) noexcept
1436{
1437 constexpr int64_t MAX_WORDS = 4; // 256 bit numerator, the widest any type here divides
1438 static_assert(m >= 2 && m <= MAX_WORDS, "div_128bit divides a numerator of 2 to 4 words");
1439 if (q == nullptr || u == nullptr || v == nullptr || v[1] == 0)
1440 return false;
1441
1442 // Normalize so the divisor's high bit is set, which is what bounds the quotient estimate to two
1443 // too large. The numerator gains a word for the bits shifted out of its top.
1444 const int32_t s = static_cast<int32_t>(lzcnt64(v[1]));
1445 const uint64_t vn1 = (s != 0) ? ((v[1] << s) | (v[0] >> (64 - s))) : v[1];
1446 const uint64_t vn0 = v[0] << s;
1447
1448 uint64_t un[MAX_WORDS + 1] {};
1449 un[m] = (s != 0) ? (u[m - 1] >> (64 - s)) : 0;
1450 for (int64_t i = m - 1; i > 0; --i) {
1451 un[i] = (s != 0) ? ((u[i] << s) | (u[i - 1] >> (64 - s))) : u[i];
1452 }
1453 un[0] = u[0] << s;
1454
1455 for (int64_t j = m - 2; j >= 0; --j) {
1456 uint64_t qhat, rhat;
1457 bool correct = true;
1458 if (un[j + 2] >= vn1) {
1459 // The exact estimate is at least 2^64 here, which DIV cannot return - it raises #DE
1460 // instead of truncating. Knuth's cap of b - 1 applies, with the remainder it implies.
1461 qhat = UINT64_MAX;
1462 rhat = un[j + 1] + vn1;
1463 correct = (rhat >= vn1); // a carry out puts rhat past 2^64, where no correction applies
1464 } else {
1465 qhat = udiv128(un[j + 2], un[j + 1], vn1, &rhat);
1466 }
1467
1468 // Walk the estimate down while qhat * vn0 exceeds the two words it has to fit under.
1469 while (correct) {
1470 uint64_t phi;
1471 const uint64_t plo = mulx_u64(qhat, vn0, &phi);
1472 if (phi < rhat || (phi == rhat && plo <= un[j])) {
1473 break;
1474 }
1475 --qhat;
1476 const uint64_t next = rhat + vn1;
1477 if (next < rhat) {
1478 break;
1479 }
1480 rhat = next;
1481 }
1482
1483 // Multiply and subtract: un[j..j+2] -= qhat * vn, the product being three words wide.
1484 uint64_t p0hi, p1hi, product1;
1485 const uint64_t p0 = mulx_u64(qhat, vn0, &p0hi);
1486 const uint64_t p1 = mulx_u64(qhat, vn1, &p1hi);
1487 const uint64_t product2 = p1hi + addcarryx_u64(0, p1, p0hi, &product1);
1488
1489 unsigned char borrow = subborrow_u64(0, un[j], p0, &un[j]);
1490 borrow = subborrow_u64(borrow, un[j + 1], product1, &un[j + 1]);
1491 borrow = subborrow_u64(borrow, un[j + 2], product2, &un[j + 2]);
1492
1493 q[j] = qhat;
1494 if (borrow != 0) {
1495 // The estimate was one too large after all, which the correction above cannot always
1496 // catch. Undo the overshoot by adding the divisor back; Knuth puts this at about two
1497 // divisors in 2^64, so the branch is essentially never taken.
1498 --q[j];
1499 unsigned char carry = addcarryx_u64(0, un[j], vn0, &un[j]);
1500 carry = addcarryx_u64(carry, un[j + 1], vn1, &un[j + 1]);
1501 un[j + 2] += carry;
1502 }
1503 }
1504
1505 if (r != nullptr) {
1506 r[0] = (s != 0) ? ((un[0] >> s) | (un[1] << (64 - s))) : un[0];
1507 r[1] = un[1] >> s;
1508 }
1509
1510 return true;
1511}
1512/**
1513 * @brief div_128bit() with the word count of the numerator chosen at run time.
1514 *
1515 * Dispatches to the specialization for @p m. The library's own callers all know the count when they
1516 * compile and call div_128bit<m>() directly; this form is for a count that is only known at run time.
1517 *
1518 * @param q (output) Quotient, m - 1 words, q[0] lowest.
1519 * @param r (output, optional) Remainder, two words. Can be nullptr.
1520 * @param u Numerator, @p m words, u[0] lowest.
1521 * @param v Denominator, two words. v[1] must be non zero.
1522 * @param m Count of words in @p u. Must be 2, 3 or 4.
1523 * @return true on success, false when @p m is out of range or a parameter fails a condition of
1524 * div_128bit<m>().
1525 */
1526FP128_INLINE static bool div_128bit(uint64_t* q, uint64_t* r, const uint64_t* u, const uint64_t* v, int64_t m) noexcept
1527{
1528 switch (m) {
1529 case 2:
1530 return div_128bit<2>(q, r, u, v);
1531 case 3:
1532 return div_128bit<3>(q, r, u, v);
1533 case 4:
1534 return div_128bit<4>(q, r, u, v);
1535 default:
1536 return false;
1537 }
1538}
1539/**
1540 * @brief Counts the number of 1 bits (population count) in a 128-bit unsigned integer.
1541 * @param l Low QWORD
1542 * @param h High QWORD
1543 * @return Number of 1 bits in the 128 bit value.
1544 */
1545[[nodiscard]] FP128_INLINE constexpr uint64_t popcnt128(uint64_t l, uint64_t h) noexcept
1546{
1547 return popcnt64(l) + popcnt64(h);
1548}
1549/**
1550 * @brief Left zero count 128 bit
1551 * @param l Low QWORD
1552 * @param h High QWORD
1553 * @return Left zero count
1554 */
1555[[nodiscard]] FP128_INLINE constexpr uint64_t lzcnt128(uint64_t l, uint64_t h) noexcept
1556{
1557 return (h != 0) ? lzcnt64(h) : 64 + lzcnt64(l);
1558}
1559/**
1560 * @brief Calculates the Log base 2 of x: log2(x)
1561 * Rounding is always towards zero so the maximum error is close to 1.
1562 * @param l Lower QWORD of the value
1563 * @param h High QWORD of the value
1564 * @return log2(x). Returns zero when x is zero.
1565 */
1566[[nodiscard]] FP128_INLINE constexpr uint64_t log2(uint64_t l, uint64_t h) noexcept
1567{
1568 return (h != 0 || l != 0) ? 127 - lzcnt128(l, h) : 0;
1569}
1570/**
1571 * @brief Calculates the Log base 2 of x: log2(x)
1572 * Rounding is always towards zero so the maximum error is close to 1.
1573 * @param x The number to perform log2 on.
1574 * @return log2(x). Returns zero when x is zero.
1575 */
1576[[nodiscard]] FP128_INLINE constexpr uint64_t log2(uint64_t x) noexcept
1577{
1578 return (x) ? 63ull - lzcnt64(x) : 0;
1579}
1580/**
1581 * @brief Calculates the Log base 2 of x: log2(x)
1582 * Rounding is always towards zero so the maximum error is close to 1.
1583 * @param x The number to perform log2 on.
1584 * @return log2(x). Returns zero when x is zero.
1585 */
1586[[nodiscard]] FP128_INLINE constexpr uint32_t log2(uint32_t x) noexcept
1587{
1588 return (x) ? 31ull - lzcnt32(x) : 0;
1589}
1590
1591/**
1592 * @brief Upper 128 bits of the product of two 128 bit unsigned values.
1593 *
1594 * Used by the argument reduction in fixed_point128::log2(), which needs a multiplication of two
1595 * pure fractions and only the leading half of the result. Working on the raw QWORDs rather than on
1596 * fixed_point128 keeps the reduction independent of that type's template parameter: both operands
1597 * are values in [0,1) scaled by 2^128 whatever the caller's scaling happens to be.
1598 *
1599 * The lowest QWORD of the 256 bit product is discarded. Nothing is added into that column, so it
1600 * produces no carry and the result is the exact product truncated - low by less than 2^-256 of a
1601 * relative unit, which is far below anything the caller can represent.
1602 *
1603 * @param a_low Low QWORD of the first operand.
1604 * @param a_high High QWORD of the first operand.
1605 * @param b_low Low QWORD of the second operand.
1606 * @param b_high High QWORD of the second operand.
1607 * @param res_low Receives the low QWORD of the upper half of the product.
1608 * @param res_high Receives the high QWORD of the upper half of the product.
1609 */
1610FP128_INLINE constexpr void 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
1611{
1612 uint64_t ll_high = 0, lh_high = 0, hl_high = 0, hh_high = 0;
1613 [[maybe_unused]] const uint64_t ll_low = mulx_u64(a_low, b_low, &ll_high);
1614 const uint64_t lh_low = mulx_u64(a_low, b_high, &lh_high);
1615 const uint64_t hl_low = mulx_u64(a_high, b_low, &hl_high);
1616 const uint64_t hh_low = mulx_u64(a_high, b_high, &hh_high);
1617
1618 // Column at 2^64: the high half of low*low plus the low halves of both cross products. Its
1619 // carries move up into the 2^128 column, which is the first one that is kept.
1620 uint64_t mid = 0;
1621 uint8_t carry = addcarryx_u64(0, ll_high, lh_low, &mid);
1622 uint64_t mid_carries = carry;
1623 carry = addcarryx_u64(0, mid, hl_low, &mid);
1624 mid_carries += carry;
1625
1626 // Column at 2^128 and above.
1627 uint64_t low = 0, high = 0;
1628 carry = addcarryx_u64(0, hh_low, lh_high, &low);
1629 high = hh_high + carry;
1630 carry = addcarryx_u64(0, low, hl_high, &low);
1631 high += carry;
1632 carry = addcarryx_u64(0, low, mid_carries, &low);
1633 high += carry;
1634
1635 // Round to nearest on the discarded half rather than truncating. The top bit of the 2^64
1636 // column decides it, and rounding rather than truncating halves this function's contribution
1637 // to the error of the log2 it was written for.
1638 carry = addcarryx_u64(0, low, mid >> 63, &low);
1639 high += carry;
1640
1641 res_low = low;
1642 res_high = high;
1643}
1644
1645/**
1646 * @brief 1/(1 + j/64) as a 128 bit fraction, the reciprocals fixed_point128::log2() reduces with.
1647 *
1648 * Entry zero would be exactly one, which is not a 128 bit fraction, so it holds the largest value
1649 * below one instead. That makes the reduction a near no-op rather than an exact one, and
1650 * log2_value_table absorbs the difference.
1651 */
1652inline constexpr uint64_t log2_recip_table[][2] = {
1653 {0xFFFFFFFFFFFFFFFFull, 0xFFFFFFFFFFFFFFFFull},
1654 {0xFC0FC0FC0FC0FC0Full, 0xC0FC0FC0FC0FC0FCull},
1655 {0xF83E0F83E0F83E0Full, 0x83E0F83E0F83E0F8ull},
1656 {0xF4898D5F85BB3950ull, 0x3D226357E16ECE54ull},
1657 {0xF0F0F0F0F0F0F0F0ull, 0xF0F0F0F0F0F0F0F1ull},
1658 {0xED7303B5CC0ED730ull, 0x3B5CC0ED7303B5CCull},
1659 {0xEA0EA0EA0EA0EA0Eull, 0xA0EA0EA0EA0EA0EAull},
1660 {0xE6C2B4481CD85689ull, 0x039B0AD12073615Aull},
1661 {0xE38E38E38E38E38Eull, 0x38E38E38E38E38E4ull},
1662 {0xE070381C0E070381ull, 0xC0E070381C0E0704ull},
1663 {0xDD67C8A60DD67C8Aull, 0x60DD67C8A60DD67Dull},
1664 {0xDA740DA740DA740Dull, 0xA740DA740DA740DAull},
1665 {0xD79435E50D79435Eull, 0x50D79435E50D7943ull},
1666 {0xD4C77B03531DEC0Dull, 0x4C77B03531DEC0D5ull},
1667 {0xD20D20D20D20D20Dull, 0x20D20D20D20D20D2ull},
1668 {0xCF6474A8819EC8E9ull, 0x51033D91D2A2067Bull},
1669 {0xCCCCCCCCCCCCCCCCull, 0xCCCCCCCCCCCCCCCDull},
1670 {0xCA4587E6B74F0329ull, 0x161F9ADD3C0CA458ull},
1671 {0xC7CE0C7CE0C7CE0Cull, 0x7CE0C7CE0C7CE0C8ull},
1672 {0xC565C87B5F9D4D1Bull, 0xC2503159721ED7E7ull},
1673 {0xC30C30C30C30C30Cull, 0x30C30C30C30C30C3ull},
1674 {0xC0C0C0C0C0C0C0C0ull, 0xC0C0C0C0C0C0C0C1ull},
1675 {0xBE82FA0BE82FA0BEull, 0x82FA0BE82FA0BE83ull},
1676 {0xBC52640BC52640BCull, 0x52640BC52640BC52ull},
1677 {0xBA2E8BA2E8BA2E8Bull, 0xA2E8BA2E8BA2E8BAull},
1678 {0xB81702E05C0B8170ull, 0x2E05C0B81702E05Cull},
1679 {0xB60B60B60B60B60Bull, 0x60B60B60B60B60B6ull},
1680 {0xB40B40B40B40B40Bull, 0x40B40B40B40B40B4ull},
1681 {0xB21642C8590B2164ull, 0x2C8590B21642C859ull},
1682 {0xB02C0B02C0B02C0Bull, 0x02C0B02C0B02C0B0ull},
1683 {0xAE4C415C9882B931ull, 0x0572620AE4C415CAull},
1684 {0xAC7691840AC76918ull, 0x40AC7691840AC769ull},
1685 {0xAAAAAAAAAAAAAAAAull, 0xAAAAAAAAAAAAAAABull},
1686 {0xA8E83F5717C0A8E8ull, 0x3F5717C0A8E83F57ull},
1687 {0xA72F05397829CBC1ull, 0x4E5E0A72F0539783ull},
1688 {0xA57EB50295FAD40Aull, 0x57EB50295FAD40A5ull},
1689 {0xA3D70A3D70A3D70Aull, 0x3D70A3D70A3D70A4ull},
1690 {0xA237C32B16CFD772ull, 0x0F353A4C0A237C33ull},
1691 {0xA0A0A0A0A0A0A0A0ull, 0xA0A0A0A0A0A0A0A1ull},
1692 {0x9F1165E7254813E2ull, 0x2CBCE4A9027C4598ull},
1693 {0x9D89D89D89D89D89ull, 0xD89D89D89D89D89Eull},
1694 {0x9C09C09C09C09C09ull, 0xC09C09C09C09C09Cull},
1695 {0x9A90E7D95BC609A9ull, 0x0E7D95BC609A90E8ull},
1696 {0x991F1A515885FB37ull, 0x072D753BD02647C7ull},
1697 {0x97B425ED097B425Eull, 0xD097B425ED097B42ull},
1698 {0x964FDA6C0964FDA6ull, 0xC0964FDA6C0964FEull},
1699 {0x94F2094F2094F209ull, 0x4F2094F2094F2095ull},
1700 {0x939A85C40939A85Cull, 0x40939A85C40939A8ull},
1701 {0x9249249249249249ull, 0x2492492492492492ull},
1702 {0x90FDBC090FDBC090ull, 0xFDBC090FDBC090FEull},
1703 {0x8FB823EE08FB823Eull, 0xE08FB823EE08FB82ull},
1704 {0x8E78356D1408E783ull, 0x56D1408E78356D14ull},
1705 {0x8D3DCB08D3DCB08Dull, 0x3DCB08D3DCB08D3Eull},
1706 {0x8C08C08C08C08C08ull, 0xC08C08C08C08C08Cull},
1707 {0x8AD8F2FBA9386822ull, 0xB63CBEEA4E1A08AEull},
1708 {0x89AE4089AE4089AEull, 0x4089AE4089AE408Aull},
1709 {0x8888888888888888ull, 0x8888888888888889ull},
1710 {0x8767AB5F34E47EF1ull, 0x30A9419637021D9Full},
1711 {0x864B8A7DE6D1D608ull, 0x64B8A7DE6D1D6086ull},
1712 {0x8534085340853408ull, 0x5340853408534085ull},
1713 {0x8421084210842108ull, 0x4210842108421084ull},
1714 {0x83126E978D4FDF3Bull, 0x645A1CAC083126E9ull},
1715 {0x8208208208208208ull, 0x2082082082082082ull},
1716 {0x8102040810204081ull, 0x0204081020408102ull},
1717};
1718
1719/**
1720 * @brief -log2 of the matching log2_recip_table entry, as a 128 bit fraction.
1721 *
1722 * Derived from the reciprocal that is actually stored rather than from 1 + j/64, so that
1723 * log2(m) = log2(m * recip) - log2(recip) holds exactly whatever the reciprocal rounded to. That is
1724 * what keeps the argument reduction from contributing any error of its own.
1725 */
1726inline constexpr uint64_t log2_value_table[][2] = {
1727 {0x0000000000000000ull, 0x0000000000000001ull},
1728 {0x05B9E5A170B48A62ull, 0x9B89F8846042BE52ull},
1729 {0x0B5D69BAC77EC398ull, 0x9B03784B5BE08491ull},
1730 {0x10EB389FA29F9AB3ull, 0xCF74BAB999217067ull},
1731 {0x1663F6FAC913167Cull, 0xCC53826144575AC4ull},
1732 {0x1BC84240ADABBA63ull, 0xB2C5A6E5197AB879ull},
1733 {0x2118B119B4F3C72Cull, 0x4F78DFA14AA5157Bull},
1734 {0x2655D3C4F15C343Eull, 0xA3E580EB4E974C9Bull},
1735 {0x2B803473F7AD0F3Full, 0x401624140D175BA2ull},
1736 {0x309857A05E0765FBull, 0xA4491DCEC752AE1Eull},
1737 {0x359EBC5B69D927DFull, 0xC23D9780306C6969ull},
1738 {0x3A93DC9864B2DF91ull, 0xE96ACA04740A8839ull},
1739 {0x3F782D7204D01447ull, 0x51B3314F09DE6BE5ull},
1740 {0x444C1F6B4C2DD72Cull, 0x25C169E5693A7F06ull},
1741 {0x49101EAC381CE609ull, 0x16E52E91300EFEEFull},
1742 {0x4DC4933A9337B366ull, 0x44CDB2581FB9186Full},
1743 {0x5269E12F346E2BF9ull, 0x24AFDBFD36BF6D33ull},
1744 {0x570068E7EF5A1E7Eull, 0x802C48281A2EB745ull},
1745 {0x5B8887367433795Eull, 0x35482D13DC0F110Cull},
1746 {0x6002958C587150CAull, 0xBAD827D37DEB2237ull},
1747 {0x646EEA247C5C22D2ull, 0xCAD415AE1A715618ull},
1748 {0x68CDD829FD814275ull, 0xF1035E5E7B16C7F7ull},
1749 {0x6D1FAFDCE20A8290ull, 0x51BBE3F6289E3AB7ull},
1750 {0x7164BEB4A56D59F9ull, 0xFB952BBBCCC314F1ull},
1751 {0x759D4F80CBA83BF8ull, 0xFAF866415554D6C0ull},
1752 {0x79C9AA879D534831ull, 0x46784BD1C44CCD5Full},
1753 {0x7DEA15A32C1B3B38ull, 0x64C6001143D6C8D6ull},
1754 {0x81FED45CBCCBF99Cull, 0xA1A3202B3D68F965ull},
1755 {0x86082806B1D532C4ull, 0x12BA94DB12EF0AA8ull},
1756 {0x8A064FD50F2A1CF0ull, 0xAD29518B0252C226ull},
1757 {0x8DF988F4AE806F1Dull, 0xA89D4EE66C3700E3ull},
1758 {0x91E20EA1393E4040ull, 0x76630D4C409DD918ull},
1759 {0x95C01A39FBD6879Full, 0xA00B120A068BADD0ull},
1760 {0x9993E355A4E53643ull, 0x5C902FD21101093Aull},
1761 {0x9D5D9FD5010B3666ull, 0x5592074827CB508Eull},
1762 {0xA11D83F4C3554B38ull, 0x3B0E8A55626C3263ull},
1763 {0xA4D3C25E68DC57F2ull, 0x495FB7FA6D7EDA66ull},
1764 {0xA8808C384547C6EFull, 0x4A49BC591348F145ull},
1765 {0xAC241134C4E99E1Cull, 0x6C5E946B4AE30894ull},
1766 {0xAFBE7FA0F04D75C6ull, 0x58D602E66B04D3B5ull},
1767 {0xB35004723C465E69ull, 0x76DA1C872983511Dull},
1768 {0xB6D8CB53B0CA4ECBull, 0xEF83F1AB5130C34Cull},
1769 {0xBA58FEB2703A9E37ull, 0x2BC1FE8A8648E9EBull},
1770 {0xBDD0C7C9A817204Full, 0x55BBF90CE3F6815Aull},
1771 {0xC1404EADF38396DEull, 0xE021361E13A30974ull},
1772 {0xC4A7BA58377C5A03ull, 0x75163EC8D56242F8ull},
1773 {0xC80730B0001667F2ull, 0x1FA8423E8C1443F3ull},
1774 {0xCB5ED69565AFAF7Full, 0x6248A98A36F8173Cull},
1775 {0xCEAECFEA80859B33ull, 0x2AC903A413E5A848ull},
1776 {0xD1F73F9C70C0F683ull, 0xCC68D510B4A2B099ull},
1777 {0xD53847AC00A69BE6ull, 0xF1BE4359106A19B6ull},
1778 {0xD8720935E6435EBDull, 0x376A70D849AE77DCull},
1779 {0xDBA4A47AA996D25Aull, 0x5B8A19B1C637671Eull},
1780 {0xDED038E633F36DA8ull, 0xB6F0409B369AACC0ull},
1781 {0xE1F4E5170D02A99Bull, 0x4C5A724DBD8180F7ull},
1782 {0xE512C6E54998B1AFull, 0xF71C8605583D030Aull},
1783 {0xE829FB693044B398ull, 0xC4BAEE073D4B1B03ull},
1784 {0xEB3A9F01975077F1ull, 0xF5F0CC82AAA9AD7Eull},
1785 {0xEE44CD59FFAB62F3ull, 0x39D5D6A218C633A0ull},
1786 {0xF148A170700A00FDull, 0xD5533F1DE29ABEDEull},
1787 {0xF446359B13539551ull, 0x0D1E3F80FBC71454ull},
1788 {0xF73DA38D9D4A83EBull, 0x6E0F93F7A43E479Cull},
1789 {0xFA2F045E7832AA72ull, 0x6ADF27B820FD03EAull},
1790 {0xFD1A708BBE119B14ull, 0x945CF6BA73D491EAull},
1791};
1792
1793/**
1794 * @brief 1/(n*ln2) for n = 1 upwards, as a raw 128 bit value with 127 fraction bits; entry [i] holds
1795 * 1/((i+1)*ln2).
1796 *
1797 * Stored pre-scaled because the series loop reads one entry per iteration, and bringing a value
1798 * into place from a decimal string every time is out of the question.
1799 *
1800 * The division by ln(2) that turns the natural logarithm into a base two one is folded into these
1801 * constants rather than applied once at the end. That removes a multiply from every call and, more
1802 * importantly, the rounding that came with it - which mattered for the instantiations whose own
1803 * precision is close to the 127 bits the series runs at.
1804 *
1805 * Two readings of the same bits, one per consumer:
1806 * <UL>
1807 * <LI>float128 takes an entry as a plain 128 bit fraction, which makes it 1/(2n*ln2) - half the
1808 * mathematical value, so that every one of them stays below one. It doubles the series once at
1809 * the end.</LI>
1810 * <LI>fixed_point128 takes it as a fixed_point128<1>, whose 126 fraction bits are one short of what
1811 * the entry carries, so it shifts each one down by a bit as it reads it. That gives 1/(n*ln2)
1812 * itself; entry zero is 1.4427 and the accumulator peaks around 1.47, both inside the range of
1813 * that instantiation, which reaches just under 2.</LI>
1814 * </UL>
1815 */
1816inline constexpr uint64_t log2_inv_n_table[][2] = {
1817 {0xB8AA3B295C17F0BBull, 0xBE87FED0691D3E89ull},
1818 {0x5C551D94AE0BF85Dull, 0xDF43FF68348E9F44ull},
1819 {0x3D8E13B87407FAE9ull, 0x3F82AA45785F14D8ull},
1820 {0x2E2A8ECA5705FC2Eull, 0xEFA1FFB41A474FA2ull},
1821 {0x24EED8A1DF37FCF2ull, 0x594E6629AE9F72E8ull},
1822 {0x1EC709DC3A03FD74ull, 0x9FC15522BC2F8A6Cull},
1823 {0x1A61762A7ADED93Full, 0x645C921DC5DF9B38ull},
1824 {0x171547652B82FE17ull, 0x77D0FFDA0D23A7D1ull},
1825 {0x1484B13D7C02A8F8ull, 0x6A80E36C7D7506F3ull},
1826 {0x12776C50EF9BFE79ull, 0x2CA73314D74FB974ull},
1827 {0x10C9A84994022D28ull, 0x5723A2CD20D41CF5ull},
1828 {0x0F6384EE1D01FEBAull, 0x4FE0AA915E17C536ull},
1829 {0x0E347AB4698BB00Eull, 0x711E274B1BC72C32ull},
1830 {0x0D30BB153D6F6C9Full, 0xB22E490EE2EFCD9Cull},
1831 {0x0C4F9D8B4A67FEFBull, 0x731A220DE4DFD0F8ull},
1832 {0x0B8AA3B295C17F0Bull, 0xBBE87FED0691D3E9ull},
1833 {0x0ADCD64DBA1F86A1ull, 0xA1CBC3B1E810C771ull},
1834 {0x0A42589EBE01547Cull, 0x354071B63EBA8379ull},
1835 {0x09B81E0FA687FF32ull, 0x4D65793363D91E3Dull},
1836 {0x093BB62877CDFF3Cull, 0x9653998A6BA7DCBAull},
1837 {0x08CB27637E4A486Aull, 0x76C98609EC9FDE68ull},
1838 {0x0864D424CA011694ull, 0x2B91D166906A0E7Bull},
1839 {0x080766BF04010A77ull, 0x77969BC6475A50A2ull},
1840 {0x07B1C2770E80FF5Dull, 0x27F05548AF0BE29Bull},
1841};
1842
1843/** @brief Bits of argument reduction fixed_point128::log2() applies; log2_recip_table has 2^this entries. */
1844inline constexpr int32_t log2_reduction_bits = 6;
1845
1846} // namespace fp128
1847
1848#endif // FP128_SHARED_H
#define FP128_ASSERT(x)
#define FP128_VERSION_BUILD
Rebuild of an unchanged source tree.
static constexpr bool FP128_CPP_STYLE_MODULO
Use C++ modulo semantics (false = Python-style).
#define FP128_INLINE
#define FP128_VERSION_MAJOR
Breaking changes to the public interface.
#define FP128_VERSION
This library's version as a single comparable integer, e.g. 90000 for 0.9.0.0.
#define FP128_FORCE_INLINE
Marks a function the compiler must inline rather than merely may.
#define FP128_VERSION_MINOR
Backwards compatible additions.
#define FP128_VERSION_PATCH
Fixes that change neither.
#define FP128_VERSION_STRING
This library's version as a dotted string literal, e.g. "0.9.0.0".
Everything the library provides.
constexpr void 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 uint32_t array_length(const T &a)
Calculates the element count of a C style array at build time Example: int a[5]; constexpr int len = ...
constexpr void 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.
constexpr void 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 (che...
static bool 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.
constexpr int32_t log2_reduction_bits
Bits of argument reduction fixed_point128::log2() applies; log2_recip_table has 2^this entries.
fixed_point128< I > log2(fixed_point128< I > x) noexcept
constexpr uint64_t shift_right128_round(uint64_t l, uint64_t h, int shift) noexcept
Right shift a 128 bit integer with rounding.
constexpr void twos_complement128(uint64_t &l, uint64_t &h) noexcept
converts a 128 integer to negative via 2's complement.
uint64_t lzcnt128(const fixed_point128< I > &x) noexcept
constexpr uint64_t 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 ...
constexpr void 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 a...
static bool 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,...
static constexpr int32_t flt_exp_bits
Exponent bit count of an IEEE 754 float.
static constexpr int32_t flt_frac_bits
Mantissa bit count of an IEEE 754 float.
static constexpr int32_t version_patch
Fixes that change neither.
constexpr uint64_t log2_recip_table[][2]
1/(1 + j/64) as a 128 bit fraction, the reciprocals fixed_point128::log2() reduces with.
static constexpr const char * version_string
Dotted form, e.g. "0.9.0.0".
static errno_t strnlwr(char *dest, const char *src, size_t n) noexcept
Copy a string to lowercase, up to n characters.
constexpr uint64_t 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 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 g...
static constexpr int32_t version_major
Breaking changes to the public interface.
constexpr uint64_t shift_right64_round(uint64_t x, int shift) noexcept
Right-shift a 64-bit value with rounding.
static constexpr int32_t dbl_frac_bits
Mantissa bit count of an IEEE 754 double.
constexpr void 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.
static constexpr int32_t version_build
Rebuild of an unchanged source tree.
float128 remainder(const float128 &x, const float128 &y) noexcept
Definition float128.h:6305
constexpr uint64_t 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)*...
constexpr uint64_t 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...
static constexpr int32_t version_minor
Backwards compatible additions.
constexpr uint64_t log2_value_table[][2]
-log2 of the matching log2_recip_table entry, as a 128 bit fraction.
static constexpr int32_t dbl_exp_bits
Exponent bit count of an IEEE 754 double.
constexpr uint64_t popcnt128(uint64_t l, uint64_t h) noexcept
Counts the number of 1 bits (population count) in a 128-bit unsigned integer.
static constexpr int32_t version
All four packed into one comparable integer.
STL namespace.
constexpr void set_s(uint64_t v) noexcept
Sets the sign bit.
constexpr uint64_t f() const noexcept
Mantissa (fraction) bits.
uint64_t bits
The raw bit pattern of the double.
constexpr uint64_t s() const noexcept
Sign bit (0 = positive, 1 = negative).
constexpr double val() const noexcept
The double these bits encode.
constexpr void set_e(uint64_t v) noexcept
Sets the biased exponent. Bits above the field width are dropped.
constexpr void set_f(uint64_t v) noexcept
Sets the mantissa. Bits above the field width are dropped, as a bit-field assignment would.
static constexpr double make(uint64_t s, uint64_t e, uint64_t f) noexcept
Assembles a double out of its three fields.
constexpr Double(double v=0) noexcept
Constructs from a double, or from positive zero when no value is given.
constexpr uint64_t e() const noexcept
Biased exponent bits.
constexpr void set_s(uint32_t v) noexcept
Sets the sign bit.
constexpr uint32_t f() const noexcept
Mantissa (fraction) bits.
constexpr void set_e(uint32_t v) noexcept
Sets the biased exponent. Bits above the field width are dropped.
constexpr void set_f(uint32_t v) noexcept
Sets the mantissa. Bits above the field width are dropped, as a bit-field assignment would.
uint32_t bits
The raw bit pattern of the float.
static constexpr float make(uint32_t s, uint32_t e, uint32_t f) noexcept
Assembles a float out of its three fields, see Double::make().
constexpr uint32_t e() const noexcept
Biased exponent bits.
constexpr float val() const noexcept
The float these bits encode.
constexpr uint32_t s() const noexcept
Sign bit (0 = positive, 1 = negative).
constexpr Float(float v=0) noexcept
Constructs from a float, or from positive zero when no value is given.