diff --git a/doc/modules/ROOT/nav.adoc b/doc/modules/ROOT/nav.adoc index 4452c0b8..5f427aa7 100644 --- a/doc/modules/ROOT/nav.adoc +++ b/doc/modules/ROOT/nav.adoc @@ -42,6 +42,7 @@ * xref:unsigned_integers.adoc[] * xref:signed_integers.adoc[] * xref:floats.adoc[] +* xref:simd.adoc[] * xref:bounded_uint.adoc[] * xref:bounded_int.adoc[] * xref:bounded_float.adoc[] diff --git a/doc/modules/ROOT/pages/api_reference.adoc b/doc/modules/ROOT/pages/api_reference.adoc index 6dd10a4f..05d2a4ed 100644 --- a/doc/modules/ROOT/pages/api_reference.adoc +++ b/doc/modules/ROOT/pages/api_reference.adoc @@ -16,6 +16,7 @@ https://www.boost.org/LICENSE_1_0.txt | Name | Description | `boost::charconv` | `to_chars` and `from_chars` overloads | `boost::safe_numbers` | All other parts of the library +| `boost::safe_numbers::simd` | `vec` and its free functions, from `` |=== [#api_types] @@ -118,6 +119,16 @@ https://www.boost.org/LICENSE_1_0.txt | Safe floating-point value constrained to a compile-time range `[Min, Max]` |=== +=== SIMD Vectors + +[cols="1,2", options="header"] +|=== +| Type | Description + +| xref:simd.adoc[`simd::vec`] +| `N` safe values of type `T` checked a whole vector at a time, on `std::simd` when available and a portable backend otherwise +|=== + === Enumerations [cols="1,2", options="header"] @@ -438,6 +449,34 @@ These wrap the standard `` functions for the floating-point types `f32` a | Generic policy-parameterized arithmetic (takes `overflow_policy` as template parameter) |=== +=== SIMD Vectors + +[cols="1,2", options="header"] +|=== +| Function | Description + +| xref:simd.adoc[`saturating_*`, `overflowing_*`, `checked_*`, `strict_*`] +| The scalar free function families (`add`, `sub`, `mul`, `div`, `mod`, and for unsigned elements `shl`, `shr`) applied lane by lane + +| xref:simd.adoc[`widening_add`, `widening_mul`] +| Exact results in lanes twice as wide + +| xref:simd.adoc[`add`, `sub`, `mul`, `div`, `mod`, `shl`, `shr`] +| Vector operations with the policy chosen at the call site (`shl` and `shr` for unsigned elements only) + +| xref:simd.adoc[`select`, `min`, `max`, `clamp`] +| Lane by lane selection and ordering + +| xref:simd.adoc[`reduce`, `reduce_min`, `reduce_max`] +| Reductions; `reduce` folds left in lane order with the element's operation + +| xref:simd.adoc[`all_of`, `any_of`, `none_of`, `reduce_count`, `reduce_min_index`, `reduce_max_index`] +| Mask reductions + +| xref:simd.adoc[`unchecked_load`, `partial_load`, `unchecked_store`, `partial_store`] +| Loads and stores of contiguous ranges of the element type +|=== + == `` === `gcd` @@ -512,6 +551,10 @@ This header is not included in the convenience header since it requires external | `` | All safe floating-point types (`f32`, `f64`) +| `` +| `simd::vec` and its free functions. +This header is not included in the convenience header + | `` | Bounded unsigned and signed integer types (`bounded_uint`, `bounded_int`) diff --git a/doc/modules/ROOT/pages/simd.adoc b/doc/modules/ROOT/pages/simd.adoc new file mode 100644 index 00000000..46855cba --- /dev/null +++ b/doc/modules/ROOT/pages/simd.adoc @@ -0,0 +1,363 @@ +//// +Copyright 2026 Matt Borland +Distributed under the Boost Software License, Version 1.0. +https://www.boost.org/LICENSE_1_0.txt +//// + +[#simd] + += SIMD Vectors + +== Description + +`boost::safe_numbers::simd::vec` holds `N` values of a safe type `T` and checks a whole vector at a time. +Each operation computes every lane without branching, builds a mask of the lanes where the scalar operation would report an error, and tests that mask once. +A loop over vectors therefore pays one error branch per vector operation instead of one per element. + +C++26 adds `` (`std::simd::vec`), but only the standard integer, character, and floating-point types are vectorizable, and its lane operations have no overflow detection. +`simd::vec` wraps a vector of the basis type and adds the checks, so it follows the C++26 interface closely while keeping every rule of the scalar safe types. + +The header is opt-in and is not part of the convenience header ``: + +[source,c++] +---- +#include +---- + +This release supports the unsigned element types `u8`, `u16`, `u32`, `u64`, the signed element types `i8`, `i16`, `i32`, `i64`, and their policy forms (`sat_u32`, `strict_i64`, `basic_i32`, and so on). + +== The Semantic Rule + +For every policy, lane `i` of a vector operation equals the scalar operation on lane `i`. +When the scalar loop over `i = 0 ... N - 1` would throw or exit, the vector operation throws the same exception type with the same message as the *lowest* failing lane, and produces no result. + +* `throw_exception` elements throw exactly what the scalar type throws. +* `saturate` elements clamp every failing lane, branch free. Division and modulo by zero still throw `std::domain_error`, as in the scalar types. +* `strict` elements call `std::exit(EXIT_FAILURE)`. +* User defined handlers are called once for every failing lane, in lane order, with exactly the arguments the scalar type passes, and their return values become those lanes. + +When the error mask has any lane set, the vector replays the scalar operation lane by lane on a cold, out of line path. +The exception classification, the messages, and the handler arguments therefore come from the scalar types themselves. + +Compound assignment and `++`/`--` compute the result before storing it, so a vector that throws is left unchanged. + +== Backends + +[cols="1,2,2", options="header"] +|=== +| Backend | Selected when | Lane storage + +| `std::simd` +| The standard library provides ``: today GCC 16 libstdc++ with `-std=c++26` on x86 (SSE2 or later) +| `std::simd::vec` + +| Portable fallback +| Every other C++20 configuration, or whenever `BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND` is defined +| `std::array` with lane loops written for auto vectorization +|=== + +`BOOST_SAFE_NUMBERS_HAS_STD_SIMD` is defined when the `std::simd` backend is in use. +Detection uses `__cpp_lib_simd` or libstdc++'s `__glibcxx_simd`, because libstdc++ 16 does not define `__cpp_lib_simd`. +Both backends run the same safe number logic, and the interface is identical except for the `std::simd::vec` conversions listed below. + +The default lane count `N` is implementation defined: one native register on the `std::simd` backend and 16 bytes worth of lanes on the fallback. +Use an explicit `N` whenever the layout matters, for example in a data structure or a file format. + +The fallback is a correctness first implementation. +With GCC and Clang at `-O2` on x86-64 and ARM64, its addition and saturating addition vectorize with a single error branch (none for saturation), while multiplication and 64-bit lanes are partly or entirely scalar, and GCC may call the multiplication kernel out of line. +On the `std::simd` backend (GCC 16, x86-64, `-O2`), checked addition, subtraction, and multiplication compile to vector lane operations, one mask extraction, and one branch, with no calls on the path that does not fail. + +With AVX-512, GCC 16's `` pads a vector whose lane count is not a power of two with zero lanes, and its `/` and `%` may divide those lanes too, which raises `SIGFPE`. +`simd::vec` divides lane by lane in exactly that configuration, and uses the vector division everywhere else. + +NOTE: GCC 16's `` returns 32-byte vectors from internal helpers when AVX is not enabled, which `-Wpsabi` reports at the end of the translation unit even for plain `std::simd` code. +Under `-Werror`, add `-Wno-psabi` or `#pragma GCC diagnostic ignored "-Wpsabi"` to translation units that use vectors of 32 bytes or more (including the 64-bit lanes the 32-bit multiplication check widens into). + +== Synopsis + +[source,c++] +---- +#include + +namespace boost::safe_numbers::simd { + +template +class vec +{ +public: + using value_type = T; + using basis_type = typename T::basis_type; + using mask_type = /* std::simd::mask or a fallback mask with the same interface */; + + static constexpr auto error_policy {T::error_policy}; + static constexpr std::integral_constant size {}; + + // Zero in every lane + constexpr vec() noexcept = default; + + // Broadcast: only the exact element type + template requires std::is_same_v + explicit constexpr vec(U x) noexcept; + + // Lane i is gen(std::integral_constant{}); gen must return exactly T + template + explicit constexpr vec(G&& gen); + + // Raw lane interop on every backend + explicit constexpr vec(const std::array& lanes) noexcept; + explicit constexpr operator std::array() const noexcept; + + // Only when BOOST_SAFE_NUMBERS_HAS_STD_SIMD is defined + explicit constexpr vec(const std::simd::vec& lanes) noexcept; + explicit constexpr operator std::simd::vec() const noexcept; + + // Lane conversion as the scalar types convert; an out of range lane throws + // std::domain_error whatever the policy + template + explicit constexpr vec(const vec& other); + + // Read only lane access. Precondition: 0 <= i < N + constexpr T operator[](int i) const noexcept; + + // Compound assignment for + - * / %, and for unsigned elements & | ^ << >>, with a vec or a T + template constexpr vec& operator+=(const U& rhs); + // ... + + constexpr vec& operator++(); + constexpr vec operator++(int); + constexpr vec& operator--(); + constexpr vec operator--(int); + constexpr vec operator+() const noexcept; +}; + +// Arithmetic: + - * / % with the element's error policy +// Unsigned elements only: << >> and the bitwise & | ^ ~ +// Signed elements only: unary - +// Comparisons: == != < <= > >= return mask_type +// Each binary operator also accepts (vec, T) and (T, vec), which broadcast the element. + +// Free function families, as for the scalar types +template constexpr vec saturating_add(const vec&, const vec&) noexcept; +template constexpr std::pair, typename vec::mask_type> overflowing_add(const vec&, const vec&) noexcept; +template constexpr std::optional> checked_add(const vec&, const vec&) noexcept; +template constexpr vec strict_add(const vec&, const vec&) noexcept; +// ... and likewise for sub, mul, div, mod, and for unsigned elements shl, shr + +// Exact results in lanes twice as wide (8, 16, and 32-bit lanes) +template constexpr auto widening_add(const vec&, const vec&) noexcept; +template constexpr auto widening_mul(const vec&, const vec&) noexcept; + +// Policy chosen at the call site +template constexpr auto add(const vec&, const vec&); +// ... and likewise sub, mul, div, mod, and for unsigned elements shl, shr + +// Lane algorithms +template constexpr vec select(const typename vec::mask_type&, const vec&, const vec&) noexcept; +template constexpr vec min(const vec&, const vec&) noexcept; +template constexpr vec max(const vec&, const vec&) noexcept; +template constexpr vec clamp(const vec& v, const vec& lo, const vec& hi) noexcept; + +// Reductions: reduce folds left in lane order with the element's operation +template > constexpr T reduce(const vec&, BinaryOperation = {}); +template constexpr T reduce_min(const vec&) noexcept; +template constexpr T reduce_max(const vec&) noexcept; + +// Mask reductions (std::simd's own on the std::simd backend) +using /* ... */::all_of; +using /* ... */::any_of; +using /* ... */::none_of; +using /* ... */::reduce_count; +using /* ... */::reduce_min_index; +using /* ... */::reduce_max_index; + +// Loads and stores of exactly the element type +template constexpr V unchecked_load(R&& r) noexcept; +template constexpr V unchecked_load(It first, std::iter_difference_t n) noexcept; +template constexpr V partial_load(R&& r) noexcept; +template constexpr V partial_load(It first, std::iter_difference_t n) noexcept; +template constexpr void unchecked_store(const vec&, R&& r) noexcept; +template constexpr void unchecked_store(const vec&, It first, std::iter_difference_t n) noexcept; +template constexpr void partial_store(const vec&, R&& r) noexcept; +template constexpr void partial_store(const vec&, It first, std::iter_difference_t n) noexcept; + +} // namespace boost::safe_numbers::simd +---- + +== Element Types and Mixing + +The element type and its error policy are part of the vector type, and mixing follows the scalar rules exactly: + +* Operations take two vectors of the same element type and lane count, or a vector and one value of its element type, which is broadcast. +* Mixed widths (`vec + vec`), mixed signedness (`vec + vec`), mixed policies (`vec + vec`), mixed lane counts (`vec + vec`), and built-in operands (`v + 1U`) are compile time errors with a `static_assert` message. +* `u128` and `i128` elements are rejected, because `std::simd` has no 128-bit lanes, and so are the bounded types. +* Unary minus is rejected for unsigned elements, and the bitwise and shift operators for signed elements, as for the scalar types. +* The converting constructor converts between widths and policies of one signedness only. The scalar types never convert between signed and unsigned, so neither do the vectors. + +A `mask_type` is keyed on the lane size, so a mask from a vector of `u64` can not select between vectors of `u32` on either backend. + +== Construction, Loads, and Stores + +The loads and stores read and write contiguous ranges of exactly the element type (`std::array`, `std::vector`, `std::span`, built-in arrays), or an iterator and a count. +Lanes are copied through each element's conversion to its basis type, so there is no `reinterpret_cast` and the copies compile to vector loads and stores. + +* `unchecked_load` and `unchecked_store` require at least `N` elements; a range with a static extent shorter than `N` is a compile time error. +* `partial_load` reads `min(size, N)` elements and zero fills the remaining lanes; `partial_store` writes `min(size, N)` lanes. + +Built-in data moves through the raw lane conversions, `vec(const std::array&)` and `operator std::array()`, which never check anything because every basis value is a valid lane. + +== Unsigned Operations + +[cols="1,2,2", options="header"] +|=== +| Operation | Error lanes | Error under `throw_exception` + +| `+`, `++` +| The sum wraps +| `std::overflow_error` + +| `-`, `--` +| The difference would be negative +| `std::underflow_error` + +| `*` +| The product exceeds the maximum +| `std::overflow_error` + +| `/`, `%` +| The divisor is zero +| `std::domain_error` (also under `saturate`) + +| `<<` +| `bit_width(lhs) + rhs >= digits`, as in the scalar types +| `std::overflow_error` + +| `>>` +| `rhs >= digits` +| `std::overflow_error` + +| `&`, `\|`, `^`, `~` +| Never +| None +|=== + +Every lane computation is free of undefined behavior. +Lanes narrower than `int` multiply in lanes of twice their width, because `u16 * u16` promotes to a signed `int` in which `65535 * 65535` overflows. +Shift counts are sanitized before shifting, and a zero divisor lane takes the error path before any lane is divided. + +The 64-bit multiplication has no 128-bit lane to widen into, so it splits each operand into 32-bit halves held in 64-bit lanes. +The product overflows exactly when both high halves are nonzero, when the cross term `ah * bl + al * bh` reaches 2^32, or when adding the shifted cross term to `al * bl` carries out. +Every operation stays in vector lanes on every target, so the speed of each one follows the vector instructions of the target and the standard library. + +The `overflowing_*` functions return the wrapped lanes and the error mask, and `checked_*` return `std::nullopt` when any lane fails. +Division and modulo still throw `std::domain_error` on a zero divisor in the `saturating_*` and `overflowing_*` families, exactly as the scalar functions do. + +== Signed Operations + +[cols="1,2,2", options="header"] +|=== +| Operation | Error lanes | Error under `throw_exception` + +| `+`, `-`, `*`, `++`, `--` +| The exact result is above the maximum, or below the minimum +| `std::overflow_error` or `std::underflow_error` respectively + +| `/`, `%` +| The divisor is zero +| `std::domain_error` (also under `saturate`) + +| `/`, `%` +| `min / -1` and `min % -1` +| `std::overflow_error` + +| unary `-` +| `-min` +| `std::domain_error` +|=== + +`saturate` elements clamp toward the side the exact result left the range on: to the maximum or the minimum for `+`, `-`, and `*`, to the maximum for `min / -1` and `-min`, and to 0, the mathematical result, for `min % -1`. +A user defined handler receives exactly the scalar arguments, including `error_kind::overflow` for `-min`, where `throw_exception` reports `std::domain_error`. + +Signed lane arithmetic would be undefined behavior on overflow, so every lane computation avoids it: + +* Addition, subtraction, negation, `++`, and `--` run in the unsigned lanes of the same width, where they wrap, and convert back. The overflow test is the sign test of the scalar types: an addition overflows when the operands share a sign that the result does not. +* Lanes of 8, 16, and 32 bits multiply exactly in signed lanes of twice their width and compare the product with the limits. +* 64-bit lanes multiply the magnitudes with the unsigned 32-bit split. The magnitude of a positive product may reach `2^63 - 1` and that of a negative product `2^63`, so `min * 1` fits and `min * -1` does not. +* Before any lane is divided, a zero divisor takes the error path, and the `min / -1` lanes divide by 1 instead (`min / 1` is `min` and `min % 1` is 0, which are the wrapped values `overflowing_div` and `overflowing_mod` return). + +The `saturating_*`, `overflowing_*`, `checked_*`, and `strict_*` families cover `add`, `sub`, `mul`, `div`, and `mod`, as for the scalar signed types; there are no shift functions. +`overflowing_div` and `overflowing_mod` flag the `min / -1` lanes, and `widening_add` and `widening_mul` return lanes of `i16`, `i32`, or `i64`. + +== Deferred Checking + +The `overflowing_*` functions never branch on the error, so a loop can accumulate the masks and test them once at the end: + +[source,c++] +---- +auto errors {vec4::mask_type{false}}; +for (/* each step */) +{ + const auto [next, overflowed] {simd::overflowing_add(sum, values)}; + sum = next; + errors = errors || overflowed; +} + +if (any_of(errors)) +{ + // handle the overflow once +} +---- + +== Example + +.This https://github.com/boostorg/safe_numbers/blob/develop/examples/simd_unsigned.cpp[example] demonstrates checked vector arithmetic, the overflowing and saturating forms, deferred checking, and loads and stores. +==== +[source, c++] +---- +include::example$simd_unsigned.cpp[tags=**;!exclude] +---- + +Output: +---- +Error: Overflow detected in u32 multiplication +lane 0: 300 +lane 1: 500 +lane 2: 1705032704 (overflowed) +lane 3: 70 +saturated lane 2: 4294967295 +lanes that overflowed while summing: 1 +min(p, 50 * c) = 100 100 100 7 +---- +==== + +.This https://github.com/boostorg/safe_numbers/blob/develop/examples/simd_signed.cpp[example] demonstrates signed vector arithmetic, where the lowest failing lane decides between overflow and underflow, together with the overflowing and saturating forms, negation, and division. +==== +[source, c++] +---- +include::example$simd_signed.cpp[tags=**;!exclude] +---- + +Output: +---- +Error: Underflow detected in i32 addition +lane 0: 750 +lane 1: 2147483296 (out of range) +lane 2: -1794967296 (out of range) +lane 3: 25 +saturated: 750 -2147483648 2147483647 25 +Error: Overflow in i32 unary minus operator +lanes where min / -1 overflowed: 4 (wrapped quotient -2147483648) +---- +==== + +== Limitations + +These are not supported yet: + +* Floating-point element types. +* `u128` and `i128` elements, since `std::simd` has no 128-bit lanes. +* Bounded element types. +* CUDA and SYCL device code, which have no ``. +* The C++20 module. +* `` and `` style functions for vectors (GCC 16 implements neither [simd.math] nor [simd.bit]). +* Formatting and stream I/O for vectors, and debugger pretty printers. +* Masked loads, stores, and reductions. diff --git a/examples/simd_signed.cpp b/examples/simd_signed.cpp new file mode 100644 index 00000000..b05ef23b --- /dev/null +++ b/examples/simd_signed.cpp @@ -0,0 +1,82 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// tag::exclude[] +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif +// end::exclude[] + +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + using namespace boost::safe_numbers; + using vec4 = simd::vec; + + // Balances and the changes to apply to them + const std::array balances {i32{1'000}, i32{-2'147'483'000}, i32{2'000'000'000}, i32{-50}}; + const std::array changes {i32{-250}, i32{-1'000}, i32{500'000'000}, i32{75}}; + + const auto b {simd::unchecked_load(balances)}; + const auto c {simd::unchecked_load(changes)}; + + // Lane 1 underflows and lane 2 overflows. The lowest failing lane decides what is + // thrown, exactly as a scalar loop over the lanes would. + try + { + const auto totals {b + c}; + static_cast(totals); + } + catch (const std::underflow_error& e) + { + std::cout << "Error: " << e.what() << '\n'; + } + + // overflowing_add returns the wrapped lanes and a mask of the lanes that failed + const auto [wrapped, failed] {simd::overflowing_add(b, c)}; + for (int i {}; i < vec4::size(); ++i) + { + std::cout << "lane " << i << ": " << wrapped[i] << (failed[i] ? " (out of range)" : "") << '\n'; + } + + // sat_i32 lanes clamp toward the side the result left the range on + using sat_vec4 = simd::vec; + const auto clamped {sat_vec4{b} + sat_vec4{c}}; + std::cout << "saturated:"; + for (int i {}; i < sat_vec4::size(); ++i) + { + std::cout << ' ' << clamped[i]; + } + std::cout << '\n'; + + // Negation and division are checked too: -min and min / -1 do not fit + const vec4 lowest {i32{std::numeric_limits::min()}}; + try + { + const auto negated {-lowest}; + static_cast(negated); + } + catch (const std::domain_error& e) + { + std::cout << "Error: " << e.what() << '\n'; + } + + const auto [quotients, overflowed] {simd::overflowing_div(lowest, vec4{i32{-1}})}; + std::cout << "lanes where min / -1 overflowed: " << reduce_count(overflowed) + << " (wrapped quotient " << quotients[0] << ")\n"; + + // As for the scalar signed types, bitwise and shift operators do not compile: + // b & c; // static_assert: Bitwise AND is deliberately disabled for signed safe integers + + return 0; +} diff --git a/examples/simd_unsigned.cpp b/examples/simd_unsigned.cpp new file mode 100644 index 00000000..d4b8b5b1 --- /dev/null +++ b/examples/simd_unsigned.cpp @@ -0,0 +1,78 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// tag::exclude[] +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif +// end::exclude[] + +#include +#include +#include +#include +#include + +int main() +{ + using namespace boost::safe_numbers; + using vec4 = simd::vec; + + // Lanes load from a contiguous range of exactly the element type + const std::array prices {u32{100U}, u32{250U}, u32{3'000'000'000U}, u32{7U}}; + const std::array counts {u32{3U}, u32{2U}, u32{2U}, u32{10U}}; + + const auto p {simd::unchecked_load(prices)}; + const auto c {simd::unchecked_load(counts)}; + + // One check covers every lane: lane 2 overflows, so the whole multiplication + // throws exactly what the scalar u32 operation throws + try + { + const auto totals {p * c}; + static_cast(totals); + } + catch (const std::overflow_error& e) + { + std::cout << "Error: " << e.what() << '\n'; + } + + // overflowing_mul returns the wrapped lanes and a mask of the lanes that overflowed + const auto [wrapped, overflowed] {simd::overflowing_mul(p, c)}; + for (int i {}; i < vec4::size(); ++i) + { + std::cout << "lane " << i << ": " << wrapped[i] << (overflowed[i] ? " (overflowed)" : "") << '\n'; + } + + // The error policy comes from the element type: sat_u32 lanes clamp instead + using sat_vec4 = simd::vec; + const auto clamped {sat_vec4{p} * sat_vec4{c}}; + std::cout << "saturated lane 2: " << clamped[2] << '\n'; + + // Deferred checking: accumulate the masks and test once at the end + auto sum {vec4{}}; + auto errors {vec4::mask_type{false}}; + for (int step {}; step < 3; ++step) + { + const auto [next, carry] {simd::overflowing_add(sum, p)}; + sum = next; + errors = errors || carry; + } + + std::cout << "lanes that overflowed while summing: " << reduce_count(errors) << '\n'; + + // Elementwise operations without errors store straight back to safe values + std::array out {}; + simd::unchecked_store(simd::min(p, c * u32{50U}), out); + std::cout << "min(p, 50 * c) ="; + for (const auto x : out) + { + std::cout << ' ' << x; + } + std::cout << '\n'; + + return 0; +} diff --git a/include/boost/safe_numbers/detail/simd/array_backend.hpp b/include/boost/safe_numbers/detail/simd/array_backend.hpp new file mode 100644 index 00000000..6dbcf864 --- /dev/null +++ b/include/boost/safe_numbers/detail/simd/array_backend.hpp @@ -0,0 +1,532 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#ifndef BOOST_SAFE_NUMBERS_DETAIL_SIMD_ARRAY_BACKEND_HPP +#define BOOST_SAFE_NUMBERS_DETAIL_SIMD_ARRAY_BACKEND_HPP + +#include + +#ifndef BOOST_SAFE_NUMBERS_HAS_STD_SIMD + +// Portable fallback with the subset of the std::simd::basic_vec surface that the +// wrapper uses. Every lane operation is expanded over the lanes at compile time, so +// even at -O2 the optimizers see straight-line code they can vectorize, and no lane +// operation is ever undefined behavior. + +namespace boost::safe_numbers::detail::simd_impl { + +template +struct mask_lane; + +template <> +struct mask_lane<1U> { using type = std::uint8_t; }; + +template <> +struct mask_lane<2U> { using type = std::uint16_t; }; + +template <> +struct mask_lane<4U> { using type = std::uint32_t; }; + +template <> +struct mask_lane<8U> { using type = std::uint64_t; }; + +// Unsigned type at least as wide as unsigned int, so lane arithmetic never promotes to int +template +using wrap_type_t = std::conditional_t<(sizeof(B) <= sizeof(unsigned)), unsigned, std::uint64_t>; + +// MSVC for ARM64 at /O2 crashes (C1001) on some expanded lane forms and miscompiles +// others (seen on 19.51 and 19.52), so the affected operations use a form it gets right +#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_ARM64) +inline constexpr bool msvc_arm64_workarounds {true}; +#else +inline constexpr bool msvc_arm64_workarounds {false}; +#endif + +// Builds the array {f(0), f(1), ..., f(N - 1)} +template +constexpr auto make_lanes(F f) -> std::array +{ + return [&f](std::index_sequence) + { + return std::array{{static_cast(f(I))...}}; + }(std::make_index_sequence{}); +} + +struct raw_lanes_t {}; + +inline constexpr raw_lanes_t raw_lanes {}; + +template +class array_mask +{ +public: + + using lane_type = typename mask_lane::type; + using value_type = bool; + using lanes_type = std::array(N)>; + + static constexpr std::integral_constant size {}; + + // Every lane holds all zeros or all ones, like a hardware vector mask + static constexpr auto lane_of(const bool b) noexcept -> lane_type + { + using acc_type = wrap_type_t; + return static_cast(acc_type{0} - static_cast(b)); + } + +private: + + static constexpr auto lanes {static_cast(N)}; + + lanes_type lanes_ {}; + +public: + + constexpr array_mask() noexcept = default; + + explicit constexpr array_mask(const bool b) noexcept + : lanes_ {make_lanes([b](std::size_t) { return lane_of(b); })} {} + + constexpr array_mask(raw_lanes_t, const lanes_type& init) noexcept : lanes_ {init} {} + + // Explicit, as in C++26 [simd.mask.ctor] + template + explicit constexpr array_mask(const array_mask& other) noexcept + : lanes_ {make_lanes([&other](const std::size_t i) { return lane_of(other.raw()[i] != 0U); })} {} + + [[nodiscard]] constexpr auto raw() const noexcept -> const lanes_type& { return lanes_; } + + [[nodiscard]] constexpr auto operator[](const int i) const noexcept -> bool + { + return lanes_[static_cast(i)] != 0U; + } + + friend constexpr auto operator!(const array_mask& m) noexcept -> array_mask + { + return array_mask{raw_lanes, make_lanes([&m](const std::size_t i) { return ~m.lanes_[i]; })}; + } + + friend constexpr auto operator&(const array_mask& lhs, const array_mask& rhs) noexcept -> array_mask + { + return array_mask{raw_lanes, make_lanes([&](const std::size_t i) { return lhs.lanes_[i] & rhs.lanes_[i]; })}; + } + + friend constexpr auto operator|(const array_mask& lhs, const array_mask& rhs) noexcept -> array_mask + { + return array_mask{raw_lanes, make_lanes([&](const std::size_t i) { return lhs.lanes_[i] | rhs.lanes_[i]; })}; + } + + friend constexpr auto operator^(const array_mask& lhs, const array_mask& rhs) noexcept -> array_mask + { + return array_mask{raw_lanes, make_lanes([&](const std::size_t i) { return lhs.lanes_[i] ^ rhs.lanes_[i]; })}; + } + + friend constexpr auto operator&&(const array_mask& lhs, const array_mask& rhs) noexcept -> array_mask + { + return lhs & rhs; + } + + friend constexpr auto operator||(const array_mask& lhs, const array_mask& rhs) noexcept -> array_mask + { + return lhs | rhs; + } + + friend constexpr auto operator==(const array_mask& lhs, const array_mask& rhs) noexcept -> array_mask + { + return !(lhs ^ rhs); + } + + friend constexpr auto operator!=(const array_mask& lhs, const array_mask& rhs) noexcept -> array_mask + { + return lhs ^ rhs; + } +}; + +// Mask reductions. These live in the mask's namespace so that unqualified calls +// find them by ADL, exactly as std::simd masks find the std::simd overloads. +// The lanes are folded as unsigned integers at compile time: bool OR reductions +// and rolled loops do not reliably vectorize. + +namespace impl { + +template +constexpr auto or_lanes(const Lanes& lanes, std::index_sequence) noexcept -> Acc +{ + return static_cast((static_cast(lanes[I]) | ...)); +} + +template +constexpr auto and_lanes(const Lanes& lanes, std::index_sequence) noexcept -> Acc +{ + return static_cast((static_cast(lanes[I]) & ...)); +} + +template +constexpr auto count_lanes(const Lanes& lanes, std::index_sequence) noexcept -> unsigned +{ + return (static_cast(lanes[I] & 1U) + ...); +} + +} // namespace impl + +template +[[nodiscard]] constexpr auto any_of(const array_mask& m) noexcept -> bool +{ + // MSVC ARM64 fuses the fold with the compare that built m and reloads 16-bit lanes as 32 bits + if constexpr (msvc_arm64_workarounds) + { + auto res {false}; + for (int i {}; i < N; ++i) + { + res = res || m[i]; + } + + return res; + } + else + { + using acc_type = wrap_type_t::lane_type>; + return impl::or_lanes(m.raw(), std::make_index_sequence(N)>{}) != 0U; + } +} + +template +[[nodiscard]] constexpr auto all_of(const array_mask& m) noexcept -> bool +{ + // See any_of + if constexpr (msvc_arm64_workarounds) + { + auto res {true}; + for (int i {}; i < N; ++i) + { + res = res && m[i]; + } + + return res; + } + else + { + using acc_type = wrap_type_t::lane_type>; + return impl::and_lanes(m.raw(), std::make_index_sequence(N)>{}) != 0U; + } +} + +template +[[nodiscard]] constexpr auto none_of(const array_mask& m) noexcept -> bool +{ + return !any_of(m); +} + +template +[[nodiscard]] constexpr auto reduce_count(const array_mask& m) noexcept -> int +{ + return static_cast(impl::count_lanes(m.raw(), std::make_index_sequence(N)>{})); +} + +// Precondition: any_of(m) +template +[[nodiscard]] constexpr auto reduce_min_index(const array_mask& m) noexcept -> int +{ + for (int i {}; i < N; ++i) + { + if (m[i]) + { + return i; + } + } + + return N; +} + +// Precondition: any_of(m) +template +[[nodiscard]] constexpr auto reduce_max_index(const array_mask& m) noexcept -> int +{ + for (int i {N - 1}; i >= 0; --i) + { + if (m[i]) + { + return i; + } + } + + return -1; +} + +template +class array_vec +{ +public: + + using value_type = B; + using mask_type = array_mask; + using lanes_type = std::array(N)>; + + static constexpr std::integral_constant size {}; + +private: + + // + - * << ~ & | ^ wrap through this unsigned type and convert back, which is + // modular (C++20), so narrow lanes never overflow a promoted int + using wrap_type = wrap_type_t; + using mask_lane_type = typename mask_type::lane_type; + + static constexpr auto lanes {static_cast(N)}; + + lanes_type lanes_ {}; + + template + static constexpr auto wrap_op(const array_vec& lhs, const array_vec& rhs, F f) noexcept -> array_vec + { + return array_vec{make_lanes([&](const std::size_t i) + { + return f(static_cast(lhs.lanes_[i]), static_cast(rhs.lanes_[i])); + })}; + } + + template + static constexpr auto plain_op(const array_vec& lhs, const array_vec& rhs, F f) noexcept -> array_vec + { + return array_vec{make_lanes([&](const std::size_t i) { return f(lhs.lanes_[i], rhs.lanes_[i]); })}; + } + + template + static constexpr auto compare(const array_vec& lhs, const array_vec& rhs, F f) noexcept -> mask_type + { + return mask_type{raw_lanes, make_lanes([&](const std::size_t i) + { + return mask_type::lane_of(f(lhs.lanes_[i], rhs.lanes_[i])); + })}; + } + + // MSVC ARM64 crashes (C1001) on the expanded form of a narrowing to half width into + // 16 bytes (u32 x 8 to u16), and miscompiles the loop form of a widening + template + static constexpr auto convert_lanes(const std::array& from) noexcept -> lanes_type + { + if constexpr (msvc_arm64_workarounds && sizeof(B) < sizeof(U)) + { + lanes_type res {}; + for (std::size_t i {}; i < lanes; ++i) + { + res[i] = static_cast(from[i]); + } + + return res; + } + else + { + return make_lanes([&from](const std::size_t i) { return from[i]; }); + } + } + +public: + + constexpr array_vec() noexcept = default; + + explicit constexpr array_vec(const B x) noexcept + : lanes_ {make_lanes([x](std::size_t) { return x; })} {} + + explicit constexpr array_vec(const lanes_type& a) noexcept : lanes_ {a} {} + + // Lane i is gen(std::integral_constant{}) + template + requires std::invocable> + explicit constexpr array_vec(G&& gen) + : lanes_ {[&gen](std::index_sequence) + { + return lanes_type{{static_cast(gen(std::integral_constant(I)>{}))...}}; + }(std::make_index_sequence{})} {} + + template + requires (!std::is_same_v) + explicit constexpr array_vec(const array_vec& other) noexcept + : lanes_ {convert_lanes(other.raw())} {} + + [[nodiscard]] constexpr auto raw() const noexcept -> const lanes_type& { return lanes_; } + + [[nodiscard]] constexpr auto operator[](const int i) const noexcept -> B + { + return lanes_[static_cast(i)]; + } + + friend constexpr auto operator+(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return wrap_op(lhs, rhs, [](const wrap_type x, const wrap_type y) { return static_cast(x + y); }); + } + + friend constexpr auto operator-(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return wrap_op(lhs, rhs, [](const wrap_type x, const wrap_type y) { return static_cast(x - y); }); + } + + friend constexpr auto operator*(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return wrap_op(lhs, rhs, [](const wrap_type x, const wrap_type y) { return static_cast(x * y); }); + } + + // Precondition: no zero lane in rhs + friend constexpr auto operator/(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return plain_op(lhs, rhs, [](const B x, const B y) { return x / y; }); + } + + // Precondition: no zero lane in rhs + friend constexpr auto operator%(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return plain_op(lhs, rhs, [](const B x, const B y) { return x % y; }); + } + + friend constexpr auto operator&(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return wrap_op(lhs, rhs, [](const wrap_type x, const wrap_type y) { return static_cast(x & y); }); + } + + friend constexpr auto operator|(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return wrap_op(lhs, rhs, [](const wrap_type x, const wrap_type y) { return static_cast(x | y); }); + } + + friend constexpr auto operator^(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return wrap_op(lhs, rhs, [](const wrap_type x, const wrap_type y) { return static_cast(x ^ y); }); + } + + // Precondition: every rhs lane is less than the lane width in bits + friend constexpr auto operator<<(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return wrap_op(lhs, rhs, [](const wrap_type x, const wrap_type y) { return static_cast(x << y); }); + } + + // Precondition: every rhs lane is less than the lane width in bits + friend constexpr auto operator>>(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec + { + return plain_op(lhs, rhs, [](const B x, const B y) { return x >> y; }); + } + + friend constexpr auto operator~(const array_vec& v) noexcept -> array_vec + { + return array_vec{make_lanes([&v](const std::size_t i) { return ~static_cast(v.lanes_[i]); })}; + } + + friend constexpr auto operator==(const array_vec& lhs, const array_vec& rhs) noexcept -> mask_type + { + return compare(lhs, rhs, [](const B x, const B y) { return x == y; }); + } + + friend constexpr auto operator!=(const array_vec& lhs, const array_vec& rhs) noexcept -> mask_type + { + return compare(lhs, rhs, [](const B x, const B y) { return x != y; }); + } + + friend constexpr auto operator<(const array_vec& lhs, const array_vec& rhs) noexcept -> mask_type + { + return compare(lhs, rhs, [](const B x, const B y) { return x < y; }); + } + + friend constexpr auto operator<=(const array_vec& lhs, const array_vec& rhs) noexcept -> mask_type + { + return compare(lhs, rhs, [](const B x, const B y) { return x <= y; }); + } + + friend constexpr auto operator>(const array_vec& lhs, const array_vec& rhs) noexcept -> mask_type + { + return compare(lhs, rhs, [](const B x, const B y) { return x > y; }); + } + + friend constexpr auto operator>=(const array_vec& lhs, const array_vec& rhs) noexcept -> mask_type + { + return compare(lhs, rhs, [](const B x, const B y) { return x >= y; }); + } +}; + +template +using storage_t = array_vec; + +template +using mask_t = array_mask; + +// One 128-bit register worth of lanes, the common SIMD width +template +inline constexpr int native_lanes {static_cast(16U / sizeof(B))}; + +// Bitwise blend of each lane, which the optimizers turn into a vector blend +template +[[nodiscard]] constexpr auto select(const array_mask& m, const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec +{ + using wrap_type = wrap_type_t; + + return array_vec{make_lanes(N)>([&](const std::size_t i) + { + const auto bits {static_cast(m.raw()[i])}; + return (static_cast(lhs.raw()[i]) & bits) | (static_cast(rhs.raw()[i]) & static_cast(~bits)); + })}; +} + +template +[[nodiscard]] constexpr auto min(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec +{ + return select(lhs < rhs, lhs, rhs); +} + +template +[[nodiscard]] constexpr auto max(const array_vec& lhs, const array_vec& rhs) noexcept -> array_vec +{ + return select(lhs < rhs, rhs, lhs); +} + +template +[[nodiscard]] constexpr auto reduce_min(const array_vec& v) noexcept -> B +{ + auto res {v[0]}; + for (int i {1}; i < N; ++i) + { + res = v[i] < res ? v[i] : res; + } + + return res; +} + +template +[[nodiscard]] constexpr auto reduce_max(const array_vec& v) noexcept -> B +{ + auto res {v[0]}; + for (int i {1}; i < N; ++i) + { + res = res < v[i] ? v[i] : res; + } + + return res; +} + +// Precondition: no zero lane in b, and no lane dividing min by -1 +template +constexpr auto divide_lanes(const array_vec& a, const array_vec& b) noexcept -> array_vec +{ + return a / b; +} + +template +constexpr auto modulo_lanes(const array_vec& a, const array_vec& b) noexcept -> array_vec +{ + return a % b; +} + +template +[[nodiscard]] constexpr auto to_array(const array_vec& v) noexcept -> std::array(N)> +{ + return v.raw(); +} + +template +[[nodiscard]] constexpr auto from_array(const std::array(N)>& a) noexcept -> array_vec +{ + return array_vec{a}; +} + +} // namespace boost::safe_numbers::detail::simd_impl + +#endif // BOOST_SAFE_NUMBERS_HAS_STD_SIMD + +#endif // BOOST_SAFE_NUMBERS_DETAIL_SIMD_ARRAY_BACKEND_HPP diff --git a/include/boost/safe_numbers/detail/simd/config.hpp b/include/boost/safe_numbers/detail/simd/config.hpp new file mode 100644 index 00000000..ad4ff74e --- /dev/null +++ b/include/boost/safe_numbers/detail/simd/config.hpp @@ -0,0 +1,45 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#ifndef BOOST_SAFE_NUMBERS_DETAIL_SIMD_CONFIG_HPP +#define BOOST_SAFE_NUMBERS_DETAIL_SIMD_CONFIG_HPP + +#include + +#ifndef BOOST_SAFE_NUMBERS_BUILD_MODULE + +// The feature-test macros are only reliable after (libstdc++ defines nothing earlier) +#if __has_include() +# include +#endif + +#endif // BOOST_SAFE_NUMBERS_BUILD_MODULE + +// libstdc++ 16 ships but defines only __glibcxx_simd, never __cpp_lib_simd. +// Defining BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND selects the portable fallback. +#if (defined(__cpp_lib_simd) || defined(__glibcxx_simd)) && !defined(BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND) +# define BOOST_SAFE_NUMBERS_HAS_STD_SIMD +#endif + +#ifndef BOOST_SAFE_NUMBERS_BUILD_MODULE + +#ifdef BOOST_SAFE_NUMBERS_HAS_STD_SIMD +# include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#endif // BOOST_SAFE_NUMBERS_BUILD_MODULE + +#endif // BOOST_SAFE_NUMBERS_DETAIL_SIMD_CONFIG_HPP diff --git a/include/boost/safe_numbers/detail/simd/signed_ops.hpp b/include/boost/safe_numbers/detail/simd/signed_ops.hpp new file mode 100644 index 00000000..7e099c69 --- /dev/null +++ b/include/boost/safe_numbers/detail/simd/signed_ops.hpp @@ -0,0 +1,751 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#ifndef BOOST_SAFE_NUMBERS_DETAIL_SIMD_SIGNED_OPS_HPP +#define BOOST_SAFE_NUMBERS_DETAIL_SIMD_SIGNED_OPS_HPP + +#include +#include +#include + +namespace boost::safe_numbers::detail::simd_impl { + +// ------------------------------ +// Lane kernels +// ------------------------------ + +// Signed lane arithmetic would be undefined behavior on overflow, so + - * of the +// operands and the negations run in the unsigned lanes of the same width, where they +// wrap, and convert back (modular since C++20). The kernels share the policy +// machinery of the unsigned ones and add the direction of each error lane. + +template +struct signed_kernel_result +{ + S value; + M error; + M toward_min; // the error lanes whose saturated value is min rather than max +}; + +template +signed_kernel_result(S, M, M) -> signed_kernel_result; + +template +using unsigned_lanes_t = storage_t, N>; + +// Masks of signed and unsigned lanes of one width are the same type on both backends +// today; the explicit conversion keeps the kernels independent of that +template +constexpr auto mask_cast(const M& m) noexcept -> To +{ + return static_cast(m); +} + +template +constexpr auto signed_add_lanes(const storage_t& lhs, const storage_t& rhs) noexcept +{ + using storage_type = storage_t; + using unsigned_storage = unsigned_lanes_t; + + const storage_type zero {static_cast(0)}; + const auto ulhs {static_cast(lhs)}; + const auto urhs {static_cast(rhs)}; + const auto ures {ulhs + urhs}; + + // Overflow when the operands share a sign and the result's sign differs. The sign + // bit is tested by converting back to signed lanes. Its direction is lhs's sign. + const auto sign_flip {static_cast(~(ulhs ^ urhs) & (ulhs ^ ures))}; + return signed_kernel_result{static_cast(ures), sign_flip < zero, lhs < zero}; +} + +template +constexpr auto signed_sub_lanes(const storage_t& lhs, const storage_t& rhs) noexcept +{ + using storage_type = storage_t; + using unsigned_storage = unsigned_lanes_t; + + const storage_type zero {static_cast(0)}; + const auto ulhs {static_cast(lhs)}; + const auto urhs {static_cast(rhs)}; + const auto ures {ulhs - urhs}; + + // Overflow when the operands' signs differ and the result's sign differs from lhs's + const auto sign_flip {static_cast((ulhs ^ urhs) & (ulhs ^ ures))}; + return signed_kernel_result{static_cast(ures), sign_flip < zero, lhs < zero}; +} + +template +constexpr auto signed_mul_lanes(const storage_t& lhs, const storage_t& rhs) noexcept +{ + using storage_type = storage_t; + using mask_type = mask_t; + + const storage_type zero {static_cast(0)}; + const auto negative {(lhs < zero) != (rhs < zero)}; + + if constexpr (sizeof(B) < sizeof(std::int64_t)) + { + // The exact product fits the doubled signed lane width, so the wide multiply + // never overflows + using wide_basis = signed_promoted_type; + using wide_storage = storage_t; + + const auto wide {static_cast(lhs) * static_cast(rhs)}; + const auto out_of_range {(wide > wide_storage{static_cast(std::numeric_limits::max())}) || + (wide < wide_storage{static_cast(std::numeric_limits::min())})}; + + return signed_kernel_result{static_cast(wide), mask_cast(out_of_range), negative}; + } + else + { + // Multiply the magnitudes with the unsigned 32-bit split. |min| = 2^63 is exact in + // an unsigned lane. A positive product may reach 2^63 - 1 and a negative one 2^63. + using unsigned_basis = std::make_unsigned_t; + using unsigned_storage = unsigned_lanes_t; + using unsigned_mask = mask_t; + + const unsigned_storage unsigned_zero {static_cast(0U)}; + const auto ulhs {static_cast(lhs)}; + const auto urhs {static_cast(rhs)}; + + const auto lhs_magnitude {select(mask_cast(lhs < zero), unsigned_zero - ulhs, ulhs)}; + const auto rhs_magnitude {select(mask_cast(rhs < zero), unsigned_zero - urhs, urhs)}; + const auto magnitude {mul_lanes(lhs_magnitude, rhs_magnitude)}; + + const auto negative_lanes {mask_cast(negative)}; + const auto limit {select(negative_lanes, + unsigned_storage{static_cast(static_cast(std::numeric_limits::max()) + 1U)}, + unsigned_storage{static_cast(std::numeric_limits::max())})}; + + // The wrapped product is the magnitude product with the product's sign + const auto wrapped {select(negative_lanes, unsigned_zero - magnitude.value, magnitude.value)}; + const auto error {magnitude.error || (magnitude.value > limit)}; + + return signed_kernel_result{static_cast(wrapped), mask_cast(error), negative}; + } +} + +// ------------------------------ +// Helpers +// ------------------------------ + +template +constexpr auto min_of() noexcept +{ + return std::numeric_limits::min(); +} + +// The saturated value of each lane: min in the lanes that err toward min, else max +template +constexpr auto saturated_lanes(const Kernel& lanes) noexcept +{ + using storage_type = typename simd::vec::storage_type; + return select(lanes.toward_min, storage_type{min_of()}, storage_type{max_of()}); +} + +// Lanes that divide min by -1, the only quotient that overflows +template +constexpr auto min_by_minus_one(const simd::vec& lhs, const simd::vec& rhs) noexcept +{ + using basis_type = typename T::basis_type; + using storage_type = typename simd::vec::storage_type; + + return (access::data(lhs) == storage_type{min_of()}) && + (access::data(rhs) == storage_type{static_cast(-1)}); +} + +// The divisor with the min / -1 lanes replaced by 1, where min / 1 is min and min % 1 is 0, +// exactly the scalar fallback values. Precondition: no zero divisor lane. +template +constexpr auto safe_divisor(const simd::vec& rhs, const Mask& overflow) noexcept +{ + using basis_type = typename T::basis_type; + using storage_type = typename simd::vec::storage_type; + + return select(overflow, storage_type{static_cast(1)}, access::data(rhs)); +} + +template +constexpr auto zero_divisor_lanes(const simd::vec& rhs) noexcept +{ + using storage_type = typename simd::vec::storage_type; + return access::data(rhs) == storage_type{zero_of()}; +} + +// ------------------------------ +// Operations under an explicit policy +// ------------------------------ + +// The cold path replays through the scalar detail::impl::*_impl, so the overflow +// and underflow classification, the messages, and the handler arguments are the scalar ones + +template +constexpr auto signed_add_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using basis_type = typename T::basis_type; + + const auto lanes {signed_add_lanes(access::data(lhs), access::data(rhs))}; + return apply_policy(lhs, rhs, lanes, saturated_lanes(lanes), + [](const T x, const T y) { return detail::impl::add_impl(x, y); }); +} + +template +constexpr auto signed_sub_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using basis_type = typename T::basis_type; + + const auto lanes {signed_sub_lanes(access::data(lhs), access::data(rhs))}; + return apply_policy(lhs, rhs, lanes, saturated_lanes(lanes), + [](const T x, const T y) { return detail::impl::sub_impl(x, y); }); +} + +template +constexpr auto signed_mul_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using basis_type = typename T::basis_type; + + const auto lanes {signed_mul_lanes(access::data(lhs), access::data(rhs))}; + return apply_policy(lhs, rhs, lanes, saturated_lanes(lanes), + [](const T x, const T y) { return detail::impl::mul_impl(x, y); }); +} + +// A zero divisor lane takes the cold path before any lane is divided, under every +// policy (saturate throws there too, as in the scalar types). min / -1 saturates to max, +// and is the error of every other policy. +template +constexpr auto signed_div_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using V = simd::vec; + using storage_type = typename V::storage_type; + + const auto scalar_op {[](const T x, const T y) { return detail::impl::div_impl(x, y); }}; + const auto overflow {min_by_minus_one(lhs, rhs)}; + + if constexpr (policy_equals(overflow_policy::saturate)) + { + if (any_of(zero_divisor_lanes(rhs))) [[unlikely]] + { + return replay_binary(lhs, rhs, scalar_op); + } + + const auto quotient {divide_lanes(access::data(lhs), safe_divisor(rhs, overflow))}; + return access::make(select(overflow, storage_type{max_of()}, quotient)); + } + else + { + if (any_of(zero_divisor_lanes(rhs) || overflow)) [[unlikely]] + { + return replay_binary(lhs, rhs, scalar_op); + } + + return access::make(divide_lanes(access::data(lhs), access::data(rhs))); + } +} + +// min % -1 saturates to 0, the mathematical result, and is the error of every other policy +template +constexpr auto signed_mod_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using V = simd::vec; + + const auto scalar_op {[](const T x, const T y) { return detail::impl::mod_impl(x, y); }}; + const auto overflow {min_by_minus_one(lhs, rhs)}; + + if constexpr (policy_equals(overflow_policy::saturate)) + { + if (any_of(zero_divisor_lanes(rhs))) [[unlikely]] + { + return replay_binary(lhs, rhs, scalar_op); + } + + return access::make(modulo_lanes(access::data(lhs), safe_divisor(rhs, overflow))); + } + else + { + if (any_of(zero_divisor_lanes(rhs) || overflow)) [[unlikely]] + { + return replay_binary(lhs, rhs, scalar_op); + } + + return access::make(modulo_lanes(access::data(lhs), access::data(rhs))); + } +} + +// overflowing_div and overflowing_mod flag min / -1 and min % -1 with the wrapped values +// min and 0, and still throw on a zero divisor +template +constexpr auto signed_overflowing_div_op(const simd::vec& lhs, const simd::vec& rhs) + -> std::pair, typename simd::vec::mask_type> +{ + using V = simd::vec; + using mask_type = typename V::mask_type; + + if (any_of(zero_divisor_lanes(rhs))) [[unlikely]] + { + const auto res {replay_binary(lhs, rhs, [](const T x, const T y) { return detail::impl::div_impl(x, y).first; })}; + return std::pair{res, mask_type{false}}; // LCOV_EXCL_LINE : the replay always throws + } + + const auto overflow {min_by_minus_one(lhs, rhs)}; + return std::pair{access::make(divide_lanes(access::data(lhs), safe_divisor(rhs, overflow))), overflow}; +} + +template +constexpr auto signed_overflowing_mod_op(const simd::vec& lhs, const simd::vec& rhs) + -> std::pair, typename simd::vec::mask_type> +{ + using V = simd::vec; + using mask_type = typename V::mask_type; + + if (any_of(zero_divisor_lanes(rhs))) [[unlikely]] + { + const auto res {replay_binary(lhs, rhs, [](const T x, const T y) { return detail::impl::mod_impl(x, y).first; })}; + return std::pair{res, mask_type{false}}; // LCOV_EXCL_LINE : the replay always throws + } + + const auto overflow {min_by_minus_one(lhs, rhs)}; + return std::pair{access::make(modulo_lanes(access::data(lhs), safe_divisor(rhs, overflow))), overflow}; +} + +template +constexpr auto signed_checked_div_op(const simd::vec& lhs, const simd::vec& rhs) noexcept -> std::optional> +{ + using V = simd::vec; + + if (any_of(zero_divisor_lanes(rhs) || min_by_minus_one(lhs, rhs))) + { + return std::nullopt; + } + + return std::optional{access::make(divide_lanes(access::data(lhs), access::data(rhs)))}; +} + +template +constexpr auto signed_checked_mod_op(const simd::vec& lhs, const simd::vec& rhs) noexcept -> std::optional> +{ + using V = simd::vec; + + if (any_of(zero_divisor_lanes(rhs) || min_by_minus_one(lhs, rhs))) + { + return std::nullopt; + } + + return std::optional{access::make(modulo_lanes(access::data(lhs), access::data(rhs)))}; +} + +// ------------------------------ +// Unary minus, increment, decrement, conversions +// ------------------------------ + +// -min is the only error. The scalar type throws std::domain_error there but hands a +// user handler error_kind::overflow, which the replay reproduces. +template +constexpr auto negate(const simd::vec& v) -> simd::vec +{ + using V = simd::vec; + using basis_type = typename T::basis_type; + using storage_type = typename V::storage_type; + using unsigned_storage = unsigned_lanes_t; + + const auto& lanes {access::data(v)}; + const auto res {static_cast(unsigned_storage{static_cast>(0U)} - static_cast(lanes))}; + const auto error {lanes == storage_type{min_of()}}; + + if constexpr (policy_equals(overflow_policy::saturate)) + { + return access::make(select(error, storage_type{max_of()}, res)); + } + else + { + if (any_of(error)) [[unlikely]] + { + return replay_unary(v, [](const T x) { return -x; }); + } + + return access::make(res); + } +} + +// Replays through the scalar ++ and --, whose messages and handler arguments differ +// from those of + 1 and - 1. Saturation leaves max and min unchanged. +template + requires is_signed_element_v +constexpr auto increment(adl_tag, const simd::vec& v) -> simd::vec +{ + using V = simd::vec; + using basis_type = typename T::basis_type; + using storage_type = typename V::storage_type; + using unsigned_storage = unsigned_lanes_t; + + const auto& lanes {access::data(v)}; + const auto res {static_cast(static_cast(lanes) + unsigned_storage{static_cast>(1U)})}; + const auto error {lanes == storage_type{max_of()}}; + + if constexpr (policy_equals(overflow_policy::saturate)) + { + return access::make(select(error, lanes, res)); + } + else + { + if (any_of(error)) [[unlikely]] + { + return replay_unary(v, [](const T x) + { + auto y {x}; + ++y; + return y; + }); + } + + return access::make(res); + } +} + +template + requires is_signed_element_v +constexpr auto decrement(adl_tag, const simd::vec& v) -> simd::vec +{ + using V = simd::vec; + using basis_type = typename T::basis_type; + using storage_type = typename V::storage_type; + using unsigned_storage = unsigned_lanes_t; + + const auto& lanes {access::data(v)}; + const auto res {static_cast(static_cast(lanes) - unsigned_storage{static_cast>(1U)})}; + const auto error {lanes == storage_type{min_of()}}; + + if constexpr (policy_equals(overflow_policy::saturate)) + { + return access::make(select(error, lanes, res)); + } + else + { + if (any_of(error)) [[unlikely]] + { + return replay_unary(v, [](const T x) + { + auto y {x}; + --y; + return y; + }); + } + + return access::make(res); + } +} + +// Every lane converts as T{static_cast(lane)} does: narrowing out of range +// throws std::domain_error whatever the policy, widening is always exact +template + requires (is_signed_element_v && is_signed_element_v) +constexpr auto convert_elements(adl_tag, std::type_identity, const simd::vec& v) -> simd::vec +{ + using from_basis = typename From::basis_type; + using to_basis = typename To::basis_type; + using from_storage = storage_t; + using result_type = simd::vec; + + const auto& lanes {access::data(v)}; + + if constexpr (sizeof(to_basis) < sizeof(from_basis)) + { + const auto error {(lanes > from_storage{static_cast(std::numeric_limits::max())}) || + (lanes < from_storage{static_cast(std::numeric_limits::min())})}; + + if (any_of(error)) [[unlikely]] + { + return replay_unary(v, [](const From x) { return To{static_cast(x)}; }); + } + } + + return access::make(static_cast>(lanes)); +} + +// The scalar types do not convert between signed and unsigned, so neither do the vectors +template + requires ((is_signed_element_v && is_unsigned_element_v) || (is_unsigned_element_v && is_signed_element_v)) +constexpr auto convert_elements(adl_tag, std::type_identity, const simd::vec&) -> simd::vec +{ + static_assert(dependent_false, + "simd::vec can not convert between signed and unsigned elements, because the scalar safe " + "types can not: copy the raw lanes out with operator std::array() and " + "convert each value explicitly"); + + return simd::vec{}; // LCOV_EXCL_LINE : deliberately unreachable +} + +} // namespace boost::safe_numbers::detail::simd_impl + +namespace boost::safe_numbers::simd { + +// ------------------------------ +// Operators +// ------------------------------ + +#define BOOST_SAFE_NUMBERS_SIMD_SIGNED_OPERATOR(OP_SYMBOL, OP_IMPL, NOTHROW) \ +template \ + requires detail::simd_impl::is_signed_element_v \ +[[nodiscard]] constexpr auto OP_SYMBOL(const vec& lhs, const vec& rhs) \ + noexcept(detail::NOTHROW()) -> vec \ +{ \ + return detail::simd_impl::OP_IMPL(lhs, rhs); \ +} + +BOOST_SAFE_NUMBERS_SIMD_SIGNED_OPERATOR(operator+, signed_add_op, policy_is_nothrow_arith) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_OPERATOR(operator-, signed_sub_op, policy_is_nothrow_arith) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_OPERATOR(operator*, signed_mul_op, policy_is_nothrow_arith) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_OPERATOR(operator/, signed_div_op, policy_is_nothrow_div) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_OPERATOR(operator%, signed_mod_op, policy_is_nothrow_div) + +#undef BOOST_SAFE_NUMBERS_SIMD_SIGNED_OPERATOR + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto operator-(const vec& v) + noexcept(detail::policy_is_nothrow_arith()) -> vec +{ + return detail::simd_impl::negate(v); +} + +// Bitwise and shift operators are disabled for signed elements, as for the scalar types + +#define BOOST_SAFE_NUMBERS_SIMD_SIGNED_DISABLED(OP_SYMBOL, MESSAGE) \ +template \ + requires detail::simd_impl::is_signed_element_v \ +constexpr auto OP_SYMBOL(const vec& lhs, const vec&) noexcept -> vec \ +{ \ + static_assert(detail::dependent_false, MESSAGE); \ + return lhs; /* LCOV_EXCL_LINE : deliberately unreachable */ \ +} + +BOOST_SAFE_NUMBERS_SIMD_SIGNED_DISABLED(operator&, "Bitwise AND is deliberately disabled for signed safe integers (see Ada)") +BOOST_SAFE_NUMBERS_SIMD_SIGNED_DISABLED(operator|, "Bitwise OR is deliberately disabled for signed safe integers (see Ada)") +BOOST_SAFE_NUMBERS_SIMD_SIGNED_DISABLED(operator^, "Bitwise XOR is deliberately disabled for signed safe integers (see Ada)") +BOOST_SAFE_NUMBERS_SIMD_SIGNED_DISABLED(operator<<, "Left shift is deliberately disabled for signed safe integers (see Ada)") +BOOST_SAFE_NUMBERS_SIMD_SIGNED_DISABLED(operator>>, "Right shift is deliberately disabled for signed safe integers (see Ada)") + +#undef BOOST_SAFE_NUMBERS_SIMD_SIGNED_DISABLED + +template + requires detail::simd_impl::is_signed_element_v +constexpr auto operator~(const vec& v) noexcept -> vec +{ + static_assert(detail::dependent_false, "Bitwise NOT is deliberately disabled for signed safe integers (see Ada)"); + return v; // LCOV_EXCL_LINE : deliberately unreachable +} + +// ------------------------------ +// Saturating, overflowing, checked, and strict families +// ------------------------------ + +#define BOOST_SAFE_NUMBERS_SIMD_SIGNED_FAMILY(OP, OP_IMPL, KERNEL) \ +template \ + requires detail::simd_impl::is_signed_element_v \ +[[nodiscard]] constexpr auto saturating_##OP(const vec& lhs, const vec& rhs) noexcept -> vec \ +{ \ + return detail::simd_impl::OP_IMPL(lhs, rhs); \ +} \ + \ +template \ + requires detail::simd_impl::is_signed_element_v \ +[[nodiscard]] constexpr auto overflowing_##OP(const vec& lhs, const vec& rhs) noexcept \ + -> std::pair, typename vec::mask_type> \ +{ \ + using access = detail::simd_impl::access; \ + const auto lanes {detail::simd_impl::KERNEL(access::data(lhs), access::data(rhs))}; \ + return detail::simd_impl::as_overflowing>(lanes); \ +} \ + \ +template \ + requires detail::simd_impl::is_signed_element_v \ +[[nodiscard]] constexpr auto checked_##OP(const vec& lhs, const vec& rhs) noexcept \ + -> std::optional> \ +{ \ + using access = detail::simd_impl::access; \ + const auto lanes {detail::simd_impl::KERNEL(access::data(lhs), access::data(rhs))}; \ + return detail::simd_impl::as_checked>(lanes); \ +} \ + \ +template \ + requires detail::simd_impl::is_signed_element_v \ +[[nodiscard]] constexpr auto strict_##OP(const vec& lhs, const vec& rhs) noexcept -> vec \ +{ \ + return detail::simd_impl::OP_IMPL(lhs, rhs); \ +} + +BOOST_SAFE_NUMBERS_SIMD_SIGNED_FAMILY(add, signed_add_op, signed_add_lanes) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_FAMILY(sub, signed_sub_op, signed_sub_lanes) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_FAMILY(mul, signed_mul_op, signed_mul_lanes) + +#undef BOOST_SAFE_NUMBERS_SIMD_SIGNED_FAMILY + +// Division and modulo throw std::domain_error on a zero divisor lane in every family +// except checked_* (std::nullopt) and strict_* (exit), as in the scalar types + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto saturating_div(const vec& lhs, const vec& rhs) -> vec +{ + return detail::simd_impl::signed_div_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto saturating_mod(const vec& lhs, const vec& rhs) -> vec +{ + return detail::simd_impl::signed_mod_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto overflowing_div(const vec& lhs, const vec& rhs) + -> std::pair, typename vec::mask_type> +{ + return detail::simd_impl::signed_overflowing_div_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto overflowing_mod(const vec& lhs, const vec& rhs) + -> std::pair, typename vec::mask_type> +{ + return detail::simd_impl::signed_overflowing_mod_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto checked_div(const vec& lhs, const vec& rhs) noexcept -> std::optional> +{ + return detail::simd_impl::signed_checked_div_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto checked_mod(const vec& lhs, const vec& rhs) noexcept -> std::optional> +{ + return detail::simd_impl::signed_checked_mod_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto strict_div(const vec& lhs, const vec& rhs) noexcept -> vec +{ + return detail::simd_impl::signed_div_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto strict_mod(const vec& lhs, const vec& rhs) noexcept -> vec +{ + return detail::simd_impl::signed_mod_op(lhs, rhs); +} + +// ------------------------------ +// Widening +// ------------------------------ + +// The exact sum or product in signed lanes of twice the width, with the same policy. +// 64-bit lanes have no wider lane type. + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto widening_add(const vec& lhs, const vec& rhs) noexcept +{ + using basis_type = typename T::basis_type; + + static_assert(sizeof(basis_type) < sizeof(std::int64_t), + "widening_add of i64 lanes is not supported: std::simd has no 128-bit lanes"); + + if constexpr (sizeof(basis_type) < sizeof(std::int64_t)) + { + using access = detail::simd_impl::access; + using wide_basis = detail::signed_promoted_type; + using wide_storage = detail::simd_impl::storage_t; + using result_type = vec, N>; + + return access::make(static_cast(access::data(lhs)) + static_cast(access::data(rhs))); + } + else + { + return lhs; // LCOV_EXCL_LINE : rejected above + } +} + +template + requires detail::simd_impl::is_signed_element_v +[[nodiscard]] constexpr auto widening_mul(const vec& lhs, const vec& rhs) noexcept +{ + using basis_type = typename T::basis_type; + + static_assert(sizeof(basis_type) < sizeof(std::int64_t), + "widening_mul of i64 lanes is not supported: std::simd has no 128-bit lanes"); + + if constexpr (sizeof(basis_type) < sizeof(std::int64_t)) + { + using access = detail::simd_impl::access; + using wide_basis = detail::signed_promoted_type; + using wide_storage = detail::simd_impl::storage_t; + using result_type = vec, N>; + + return access::make(static_cast(access::data(lhs)) * static_cast(access::data(rhs))); + } + else + { + return lhs; // LCOV_EXCL_LINE : rejected above + } +} + +// ------------------------------ +// Generic policy-parameterized functions +// ------------------------------ + +#define BOOST_SAFE_NUMBERS_SIMD_SIGNED_GENERIC(OP, OP_IMPL, NOEXCEPT_SPEC, WIDEN_BRANCH) \ +template \ + requires detail::simd_impl::is_signed_element_v \ +[[nodiscard]] constexpr auto OP(const vec& lhs, const vec& rhs) noexcept(NOEXCEPT_SPEC) \ +{ \ + if constexpr (Policy == overflow_policy::throw_exception) \ + { \ + return detail::simd_impl::OP_IMPL(lhs, rhs); \ + } \ + else if constexpr (Policy == overflow_policy::saturate) \ + { \ + return saturating_##OP(lhs, rhs); \ + } \ + else if constexpr (Policy == overflow_policy::overflow_tuple) \ + { \ + return overflowing_##OP(lhs, rhs); \ + } \ + else if constexpr (Policy == overflow_policy::checked) \ + { \ + return checked_##OP(lhs, rhs); \ + } \ + else if constexpr (Policy == overflow_policy::strict) \ + { \ + return strict_##OP(lhs, rhs); \ + } \ + WIDEN_BRANCH \ + else \ + { \ + static_assert(detail::dependent_false, "Policy is not supported for this operation"); \ + return lhs; \ + } \ +} + +#define BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN +#define BOOST_SAFE_NUMBERS_SIMD_WIDEN(OP) else if constexpr (Policy == overflow_policy::widen) { return widening_##OP(lhs, rhs); } + +BOOST_SAFE_NUMBERS_SIMD_SIGNED_GENERIC(add, signed_add_op, Policy != overflow_policy::throw_exception, BOOST_SAFE_NUMBERS_SIMD_WIDEN(add)) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_GENERIC(sub, signed_sub_op, Policy != overflow_policy::throw_exception, BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_GENERIC(mul, signed_mul_op, Policy != overflow_policy::throw_exception, BOOST_SAFE_NUMBERS_SIMD_WIDEN(mul)) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_GENERIC(div, signed_div_op, Policy == overflow_policy::checked || Policy == overflow_policy::strict, BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN) +BOOST_SAFE_NUMBERS_SIMD_SIGNED_GENERIC(mod, signed_mod_op, Policy == overflow_policy::checked || Policy == overflow_policy::strict, BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN) + +#undef BOOST_SAFE_NUMBERS_SIMD_WIDEN +#undef BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN +#undef BOOST_SAFE_NUMBERS_SIMD_SIGNED_GENERIC + +} // namespace boost::safe_numbers::simd + +#endif // BOOST_SAFE_NUMBERS_DETAIL_SIMD_SIGNED_OPS_HPP diff --git a/include/boost/safe_numbers/detail/simd/std_backend.hpp b/include/boost/safe_numbers/detail/simd/std_backend.hpp new file mode 100644 index 00000000..a43828cd --- /dev/null +++ b/include/boost/safe_numbers/detail/simd/std_backend.hpp @@ -0,0 +1,100 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#ifndef BOOST_SAFE_NUMBERS_DETAIL_SIMD_STD_BACKEND_HPP +#define BOOST_SAFE_NUMBERS_DETAIL_SIMD_STD_BACKEND_HPP + +#include + +#ifdef BOOST_SAFE_NUMBERS_HAS_STD_SIMD + +namespace boost::safe_numbers::detail::simd_impl { + +// Lane storage is the C++26 vector of the basis type, so every lane operation +// below is the standard one; the wrapper only adds the error checks. +template +using storage_t = std::simd::vec; + +template +using mask_t = std::simd::mask; + +// One register of B lanes on the target +template +inline constexpr int native_lanes {std::simd::vec::size()}; + +using std::simd::all_of; +using std::simd::any_of; +using std::simd::none_of; +using std::simd::reduce_count; +using std::simd::reduce_min_index; +using std::simd::reduce_max_index; +using std::simd::select; +using std::simd::min; +using std::simd::max; +using std::simd::reduce_min; +using std::simd::reduce_max; + +// libstdc++ 16 with AVX-512 pads a vector whose lane count is not a power of two with zero +// lanes, and / and % may divide those too: a SIGFPE at run time, and not a constant +// expression. Only that configuration divides lane by lane, because elsewhere GCC divides +// some lane types much faster through floating point. +template +inline constexpr bool divide_by_lane { +#ifdef __AVX512F__ + (N & (N - 1)) != 0 +#else + false +#endif +}; + +// Precondition: no zero lane in b, and no lane dividing min by -1 +template +constexpr auto divide_lanes(const storage_t& a, const storage_t& b) noexcept -> storage_t +{ + if constexpr (divide_by_lane) + { + return storage_t{[&a, &b](const auto i) { return static_cast(a[i] / b[i]); }}; + } + else + { + return a / b; + } +} + +template +constexpr auto modulo_lanes(const storage_t& a, const storage_t& b) noexcept -> storage_t +{ + if constexpr (divide_by_lane) + { + return storage_t{[&a, &b](const auto i) { return static_cast(a[i] % b[i]); }}; + } + else + { + return a % b; + } +} + +template +constexpr auto to_array(const storage_t& v) noexcept -> std::array(N)> +{ + std::array(N)> res {}; + for (std::size_t i {}; i < static_cast(N); ++i) + { + res[i] = v[static_cast(i)]; + } + + return res; +} + +template +constexpr auto from_array(const std::array(N)>& a) noexcept -> storage_t +{ + return storage_t{[&a](const auto i) { return a[static_cast(i)]; }}; +} + +} // namespace boost::safe_numbers::detail::simd_impl + +#endif // BOOST_SAFE_NUMBERS_HAS_STD_SIMD + +#endif // BOOST_SAFE_NUMBERS_DETAIL_SIMD_STD_BACKEND_HPP diff --git a/include/boost/safe_numbers/detail/simd/unsigned_ops.hpp b/include/boost/safe_numbers/detail/simd/unsigned_ops.hpp new file mode 100644 index 00000000..35c346a1 --- /dev/null +++ b/include/boost/safe_numbers/detail/simd/unsigned_ops.hpp @@ -0,0 +1,713 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#ifndef BOOST_SAFE_NUMBERS_DETAIL_SIMD_UNSIGNED_OPS_HPP +#define BOOST_SAFE_NUMBERS_DETAIL_SIMD_UNSIGNED_OPS_HPP + +#include +#include + +namespace boost::safe_numbers::detail::simd_impl { + +// ------------------------------ +// Lane kernels +// ------------------------------ + +// Every kernel is branch free and never undefined behavior in any lane. It returns +// the lane results and the mask of lanes where the scalar operation reports an error. +// The operators, saturating_*, overflowing_*, and checked_* all use the same kernel. + +template +struct kernel_result +{ + S value; + M error; +}; + +template +kernel_result(S, M) -> kernel_result; + +template +constexpr auto add_lanes(const storage_t& lhs, const storage_t& rhs) noexcept +{ + const auto res {lhs + rhs}; + return kernel_result{res, res < lhs}; +} + +template +constexpr auto sub_lanes(const storage_t& lhs, const storage_t& rhs) noexcept +{ + return kernel_result{lhs - rhs, rhs > lhs}; +} + +template +constexpr auto mul_lanes(const storage_t& lhs, const storage_t& rhs) noexcept +{ + using storage_type = storage_t; + using mask_type = mask_t; + + if constexpr (sizeof(B) < sizeof(std::uint64_t)) + { + // The exact product fits the doubled lane width. Lanes narrower than int are + // never multiplied at their own width: u16 * u16 promotes to a signed int, + // where 65535 * 65535 would overflow. + using wide_basis = promoted_type; + using wide_storage = storage_t; + + const auto wide {static_cast(lhs) * static_cast(rhs)}; + const auto error {static_cast(wide > wide_storage{static_cast(std::numeric_limits::max())})}; + return kernel_result{static_cast(wide), error}; + } + else + { + // No 128-bit lanes, so split each operand into 32-bit halves held in 64-bit lanes: + // a * b = ah * bh * 2^64 + (ah * bl + al * bh) * 2^32 + al * bl. It overflows when + // both high halves are set, when the cross term reaches 2^32, or when adding the + // shifted cross term to al * bl carries out. The wrapped sum is the wrapped product. + const storage_type low_half {static_cast(0xFFFFFFFFU)}; + const storage_type half_width {static_cast(32U)}; + const storage_type zero {static_cast(0U)}; + + const auto lhs_lo {lhs & low_half}; + const auto lhs_hi {lhs >> half_width}; + const auto rhs_lo {rhs & low_half}; + const auto rhs_hi {rhs >> half_width}; + + const auto low {lhs_lo * rhs_lo}; + const auto cross {lhs_hi * rhs_lo + lhs_lo * rhs_hi}; + const auto res {(cross << half_width) + low}; + + const auto error {((lhs_hi != zero) && (rhs_hi != zero)) || ((cross >> half_width) != zero) || (res < low)}; + return kernel_result{res, error}; + } +} + +// Mirrors shl_helper: an error when bit_width(lhs) + rhs >= digits. For rhs < digits +// that is lhs >= 2^(digits - 1 - rhs), and every rhs >= digits is an error. The value +// is what overflowing_shl returns: zero for rhs >= digits, else the wrapped shift. +template +constexpr auto shl_lanes(const storage_t& lhs, const storage_t& rhs) noexcept +{ + using storage_type = storage_t; + + constexpr auto digits {static_cast(std::numeric_limits::digits)}; + const storage_type zero {static_cast(0U)}; + + const auto too_far {rhs >= storage_type{digits}}; + const auto count {select(too_far, zero, rhs)}; + const auto shifted {select(too_far, zero, lhs << count)}; + const auto top {lhs >> (storage_type{static_cast(digits - 1U)} - count)}; + + return kernel_result{shifted, too_far || (top != zero)}; +} + +// Mirrors shr_helper: an error when rhs >= digits, where the value is zero +template +constexpr auto shr_lanes(const storage_t& lhs, const storage_t& rhs) noexcept +{ + using storage_type = storage_t; + + constexpr auto digits {static_cast(std::numeric_limits::digits)}; + const storage_type zero {static_cast(0U)}; + + const auto too_far {rhs >= storage_type{digits}}; + const auto count {select(too_far, zero, rhs)}; + + return kernel_result{select(too_far, zero, lhs >> count), too_far}; +} + +// ------------------------------ +// Policy application +// ------------------------------ + +// Saturate selects the clamp value in the failing lanes. Every other policy keeps the +// hot path branch free up to a single any_of, and replays the scalar operation lane +// by lane only when some lane failed. +template +constexpr auto apply_policy(const V& lhs, const V& rhs, const Kernel& lanes, + const typename V::storage_type& saturated, Scalar scalar_op) -> V +{ + if constexpr (policy_equals(overflow_policy::saturate)) + { + static_cast(lhs); + static_cast(rhs); + static_cast(scalar_op); + return access::make(select(lanes.error, saturated, lanes.value)); + } + else + { + static_cast(saturated); + + if (any_of(lanes.error)) [[unlikely]] + { + return replay_binary(lhs, rhs, scalar_op); + } + + return access::make(lanes.value); + } +} + +template +constexpr auto as_overflowing(const Kernel& lanes) noexcept -> std::pair +{ + return std::pair{access::make(lanes.value), lanes.error}; +} + +template +constexpr auto as_checked(const Kernel& lanes) noexcept -> std::optional +{ + if (any_of(lanes.error)) + { + return std::nullopt; + } + + return std::optional{access::make(lanes.value)}; +} + +template +constexpr auto max_of() noexcept +{ + return std::numeric_limits::max(); +} + +template +constexpr auto zero_of() noexcept +{ + return static_cast(0U); +} + +// ------------------------------ +// Operations under an explicit policy +// ------------------------------ + +// Policy is one of throw_exception, saturate, strict, or a user handler. The cold +// path replays through the scalar *_impl, so exceptions, messages, and handler +// arguments are exactly the scalar ones. + +template +constexpr auto add_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using V = simd::vec; + using basis_type = typename T::basis_type; + + const auto lanes {add_lanes(access::data(lhs), access::data(rhs))}; + return apply_policy(lhs, rhs, lanes, typename V::storage_type{max_of()}, + [](const T x, const T y) { return add_impl(x, y); }); +} + +template +constexpr auto sub_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using V = simd::vec; + using basis_type = typename T::basis_type; + + const auto lanes {sub_lanes(access::data(lhs), access::data(rhs))}; + return apply_policy(lhs, rhs, lanes, typename V::storage_type{zero_of()}, + [](const T x, const T y) { return sub_impl(x, y); }); +} + +template +constexpr auto mul_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using V = simd::vec; + using basis_type = typename T::basis_type; + + const auto lanes {mul_lanes(access::data(lhs), access::data(rhs))}; + return apply_policy(lhs, rhs, lanes, typename V::storage_type{max_of()}, + [](const T x, const T y) { return mul_impl(x, y); }); +} + +template +constexpr auto shl_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using V = simd::vec; + using basis_type = typename T::basis_type; + + const auto lanes {shl_lanes(access::data(lhs), access::data(rhs))}; + return apply_policy(lhs, rhs, lanes, typename V::storage_type{max_of()}, + [](const T x, const T y) { return shl_impl(x, y); }); +} + +template +constexpr auto shr_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using V = simd::vec; + using basis_type = typename T::basis_type; + + const auto lanes {shr_lanes(access::data(lhs), access::data(rhs))}; + return apply_policy(lhs, rhs, lanes, typename V::storage_type{zero_of()}, + [](const T x, const T y) { return shr_impl(x, y); }); +} + +// A zero divisor lane takes the cold path before any lane is divided, so the vector +// division never sees a zero. Saturate throws there too, as in the scalar types. +template +constexpr auto div_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using V = simd::vec; + + const auto& divisor {access::data(rhs)}; + if (any_of(divisor == typename V::storage_type{zero_of()})) [[unlikely]] + { + return replay_binary(lhs, rhs, [](const T x, const T y) { return div_impl(x, y); }); + } + + return access::make(divide_lanes(access::data(lhs), divisor)); +} + +template +constexpr auto mod_op(const simd::vec& lhs, const simd::vec& rhs) -> simd::vec +{ + using V = simd::vec; + + const auto& divisor {access::data(rhs)}; + if (any_of(divisor == typename V::storage_type{zero_of()})) [[unlikely]] + { + return replay_binary(lhs, rhs, [](const T x, const T y) { return mod_impl(x, y); }); + } + + return access::make(modulo_lanes(access::data(lhs), divisor)); +} + +// overflowing_div and overflowing_mod never overflow, but still throw on a zero divisor +template +constexpr auto overflowing_div_op(const simd::vec& lhs, const simd::vec& rhs) + -> std::pair, typename simd::vec::mask_type> +{ + using V = simd::vec; + using mask_type = typename V::mask_type; + + const auto& divisor {access::data(rhs)}; + if (any_of(divisor == typename V::storage_type{zero_of()})) [[unlikely]] + { + const auto res {replay_binary(lhs, rhs, [](const T x, const T y) { return div_impl(x, y).first; })}; + return std::pair{res, mask_type{false}}; // LCOV_EXCL_LINE : the replay always throws + } + + return std::pair{access::make(divide_lanes(access::data(lhs), divisor)), mask_type{false}}; +} + +template +constexpr auto overflowing_mod_op(const simd::vec& lhs, const simd::vec& rhs) + -> std::pair, typename simd::vec::mask_type> +{ + using V = simd::vec; + using mask_type = typename V::mask_type; + + const auto& divisor {access::data(rhs)}; + if (any_of(divisor == typename V::storage_type{zero_of()})) [[unlikely]] + { + const auto res {replay_binary(lhs, rhs, [](const T x, const T y) { return mod_impl(x, y).first; })}; + return std::pair{res, mask_type{false}}; // LCOV_EXCL_LINE : the replay always throws + } + + return std::pair{access::make(modulo_lanes(access::data(lhs), divisor)), mask_type{false}}; +} + +template +constexpr auto checked_div_op(const simd::vec& lhs, const simd::vec& rhs) noexcept -> std::optional> +{ + using V = simd::vec; + + const auto& divisor {access::data(rhs)}; + if (any_of(divisor == typename V::storage_type{zero_of()})) + { + return std::nullopt; + } + + return std::optional{access::make(divide_lanes(access::data(lhs), divisor))}; +} + +template +constexpr auto checked_mod_op(const simd::vec& lhs, const simd::vec& rhs) noexcept -> std::optional> +{ + using V = simd::vec; + + const auto& divisor {access::data(rhs)}; + if (any_of(divisor == typename V::storage_type{zero_of()})) + { + return std::nullopt; + } + + return std::optional{access::make(modulo_lanes(access::data(lhs), divisor))}; +} + +// ------------------------------ +// Increment, decrement, conversions +// ------------------------------ + +// Replays through the scalar ++ and --, whose messages and handler arguments +// differ from those of + 1 and - 1 +template + requires is_unsigned_element_v +constexpr auto increment(adl_tag, const simd::vec& v) -> simd::vec +{ + using V = simd::vec; + using storage_type = typename V::storage_type; + + const auto& lanes {access::data(v)}; + const auto res {lanes + storage_type{static_cast(1U)}}; + const auto error {lanes == storage_type{max_of()}}; + + if constexpr (policy_equals(overflow_policy::saturate)) + { + return access::make(select(error, lanes, res)); + } + else + { + if (any_of(error)) [[unlikely]] + { + return replay_unary(v, [](const T x) + { + auto y {x}; + ++y; + return y; + }); + } + + return access::make(res); + } +} + +template + requires is_unsigned_element_v +constexpr auto decrement(adl_tag, const simd::vec& v) -> simd::vec +{ + using V = simd::vec; + using storage_type = typename V::storage_type; + + const auto& lanes {access::data(v)}; + const auto res {lanes - storage_type{static_cast(1U)}}; + const auto error {lanes == storage_type{zero_of()}}; + + if constexpr (policy_equals(overflow_policy::saturate)) + { + return access::make(select(error, lanes, res)); + } + else + { + if (any_of(error)) [[unlikely]] + { + return replay_unary(v, [](const T x) + { + auto y {x}; + --y; + return y; + }); + } + + return access::make(res); + } +} + +// Every lane converts as T{static_cast(lane)} does: narrowing out of range +// throws std::domain_error whatever the policy, widening is always exact +template + requires (is_unsigned_element_v && is_unsigned_element_v) +constexpr auto convert_elements(adl_tag, std::type_identity, const simd::vec& v) -> simd::vec +{ + using from_basis = typename From::basis_type; + using to_basis = typename To::basis_type; + using result_type = simd::vec; + + const auto& lanes {access::data(v)}; + + if constexpr (sizeof(to_basis) < sizeof(from_basis)) + { + const auto error {lanes > storage_t{static_cast(std::numeric_limits::max())}}; + if (any_of(error)) [[unlikely]] + { + return replay_unary(v, [](const From x) { return To{static_cast(x)}; }); + } + } + + return access::make(static_cast>(lanes)); +} + +} // namespace boost::safe_numbers::detail::simd_impl + +namespace boost::safe_numbers::simd { + +// ------------------------------ +// Operators +// ------------------------------ + +#define BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_OPERATOR(OP_SYMBOL, OP_IMPL, NOTHROW) \ +template \ + requires detail::simd_impl::is_unsigned_element_v \ +[[nodiscard]] constexpr auto OP_SYMBOL(const vec& lhs, const vec& rhs) \ + noexcept(detail::NOTHROW()) -> vec \ +{ \ + return detail::simd_impl::OP_IMPL(lhs, rhs); \ +} + +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_OPERATOR(operator+, add_op, policy_is_nothrow_arith) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_OPERATOR(operator-, sub_op, policy_is_nothrow_arith) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_OPERATOR(operator*, mul_op, policy_is_nothrow_arith) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_OPERATOR(operator/, div_op, policy_is_nothrow_div) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_OPERATOR(operator%, mod_op, policy_is_nothrow_div) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_OPERATOR(operator<<, shl_op, policy_is_nothrow_arith) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_OPERATOR(operator>>, shr_op, policy_is_nothrow_arith) + +#undef BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_OPERATOR + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto operator&(const vec& lhs, const vec& rhs) noexcept -> vec +{ + using access = detail::simd_impl::access; + return access::make>(access::data(lhs) & access::data(rhs)); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto operator|(const vec& lhs, const vec& rhs) noexcept -> vec +{ + using access = detail::simd_impl::access; + return access::make>(access::data(lhs) | access::data(rhs)); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto operator^(const vec& lhs, const vec& rhs) noexcept -> vec +{ + using access = detail::simd_impl::access; + return access::make>(access::data(lhs) ^ access::data(rhs)); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto operator~(const vec& v) noexcept -> vec +{ + using access = detail::simd_impl::access; + return access::make>(~access::data(v)); +} + +template + requires detail::simd_impl::is_unsigned_element_v +constexpr auto operator-(const vec& v) noexcept -> vec +{ + static_assert(detail::dependent_false, "Unary minus is deliberately disabled for unsigned safe integers"); + return v; // LCOV_EXCL_LINE : deliberately unreachable +} + +// ------------------------------ +// Saturating, overflowing, checked, and strict families +// ------------------------------ + +#define BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_FAMILY(OP, OP_IMPL, KERNEL, SATURATING_NOEXCEPT) \ +template \ + requires detail::simd_impl::is_unsigned_element_v \ +[[nodiscard]] constexpr auto saturating_##OP(const vec& lhs, const vec& rhs) \ + noexcept(SATURATING_NOEXCEPT) -> vec \ +{ \ + return detail::simd_impl::OP_IMPL(lhs, rhs); \ +} \ + \ +template \ + requires detail::simd_impl::is_unsigned_element_v \ +[[nodiscard]] constexpr auto overflowing_##OP(const vec& lhs, const vec& rhs) noexcept \ + -> std::pair, typename vec::mask_type> \ +{ \ + using access = detail::simd_impl::access; \ + const auto lanes {detail::simd_impl::KERNEL(access::data(lhs), access::data(rhs))}; \ + return detail::simd_impl::as_overflowing>(lanes); \ +} \ + \ +template \ + requires detail::simd_impl::is_unsigned_element_v \ +[[nodiscard]] constexpr auto checked_##OP(const vec& lhs, const vec& rhs) noexcept \ + -> std::optional> \ +{ \ + using access = detail::simd_impl::access; \ + const auto lanes {detail::simd_impl::KERNEL(access::data(lhs), access::data(rhs))}; \ + return detail::simd_impl::as_checked>(lanes); \ +} \ + \ +template \ + requires detail::simd_impl::is_unsigned_element_v \ +[[nodiscard]] constexpr auto strict_##OP(const vec& lhs, const vec& rhs) noexcept -> vec \ +{ \ + return detail::simd_impl::OP_IMPL(lhs, rhs); \ +} + +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_FAMILY(add, add_op, add_lanes, true) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_FAMILY(sub, sub_op, sub_lanes, true) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_FAMILY(mul, mul_op, mul_lanes, true) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_FAMILY(shl, shl_op, shl_lanes, true) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_FAMILY(shr, shr_op, shr_lanes, true) + +#undef BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_FAMILY + +// Division and modulo throw std::domain_error on a zero divisor lane in every family +// except checked_* (std::nullopt) and strict_* (exit), as in the scalar types + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto saturating_div(const vec& lhs, const vec& rhs) -> vec +{ + return detail::simd_impl::div_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto saturating_mod(const vec& lhs, const vec& rhs) -> vec +{ + return detail::simd_impl::mod_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto overflowing_div(const vec& lhs, const vec& rhs) + -> std::pair, typename vec::mask_type> +{ + return detail::simd_impl::overflowing_div_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto overflowing_mod(const vec& lhs, const vec& rhs) + -> std::pair, typename vec::mask_type> +{ + return detail::simd_impl::overflowing_mod_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto checked_div(const vec& lhs, const vec& rhs) noexcept -> std::optional> +{ + return detail::simd_impl::checked_div_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto checked_mod(const vec& lhs, const vec& rhs) noexcept -> std::optional> +{ + return detail::simd_impl::checked_mod_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto strict_div(const vec& lhs, const vec& rhs) noexcept -> vec +{ + return detail::simd_impl::div_op(lhs, rhs); +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto strict_mod(const vec& lhs, const vec& rhs) noexcept -> vec +{ + return detail::simd_impl::mod_op(lhs, rhs); +} + +// ------------------------------ +// Widening +// ------------------------------ + +// The exact sum or product in lanes of twice the width, with the same policy. +// 64-bit lanes have no wider lane type. + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto widening_add(const vec& lhs, const vec& rhs) noexcept +{ + using basis_type = typename T::basis_type; + + static_assert(sizeof(basis_type) < sizeof(std::uint64_t), + "widening_add of u64 lanes is not supported: std::simd has no 128-bit lanes"); + + if constexpr (sizeof(basis_type) < sizeof(std::uint64_t)) + { + using access = detail::simd_impl::access; + using wide_basis = detail::promoted_type; + using wide_storage = detail::simd_impl::storage_t; + using result_type = vec, N>; + + return access::make(static_cast(access::data(lhs)) + static_cast(access::data(rhs))); + } + else + { + return lhs; // LCOV_EXCL_LINE : rejected above + } +} + +template + requires detail::simd_impl::is_unsigned_element_v +[[nodiscard]] constexpr auto widening_mul(const vec& lhs, const vec& rhs) noexcept +{ + using basis_type = typename T::basis_type; + + static_assert(sizeof(basis_type) < sizeof(std::uint64_t), + "widening_mul of u64 lanes is not supported: std::simd has no 128-bit lanes"); + + if constexpr (sizeof(basis_type) < sizeof(std::uint64_t)) + { + using access = detail::simd_impl::access; + using wide_basis = detail::promoted_type; + using wide_storage = detail::simd_impl::storage_t; + using result_type = vec, N>; + + return access::make(static_cast(access::data(lhs)) * static_cast(access::data(rhs))); + } + else + { + return lhs; // LCOV_EXCL_LINE : rejected above + } +} + +// ------------------------------ +// Generic policy-parameterized functions +// ------------------------------ + +#define BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_GENERIC(OP, OP_IMPL, NOEXCEPT_SPEC, WIDEN_BRANCH) \ +template \ + requires detail::simd_impl::is_unsigned_element_v \ +[[nodiscard]] constexpr auto OP(const vec& lhs, const vec& rhs) noexcept(NOEXCEPT_SPEC) \ +{ \ + if constexpr (Policy == overflow_policy::throw_exception) \ + { \ + return detail::simd_impl::OP_IMPL(lhs, rhs); \ + } \ + else if constexpr (Policy == overflow_policy::saturate) \ + { \ + return saturating_##OP(lhs, rhs); \ + } \ + else if constexpr (Policy == overflow_policy::overflow_tuple) \ + { \ + return overflowing_##OP(lhs, rhs); \ + } \ + else if constexpr (Policy == overflow_policy::checked) \ + { \ + return checked_##OP(lhs, rhs); \ + } \ + else if constexpr (Policy == overflow_policy::strict) \ + { \ + return strict_##OP(lhs, rhs); \ + } \ + WIDEN_BRANCH \ + else \ + { \ + static_assert(detail::dependent_false, "Policy is not supported for this operation"); \ + return lhs; \ + } \ +} + +#define BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN +#define BOOST_SAFE_NUMBERS_SIMD_WIDEN(OP) else if constexpr (Policy == overflow_policy::widen) { return widening_##OP(lhs, rhs); } + +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_GENERIC(add, add_op, Policy != overflow_policy::throw_exception, BOOST_SAFE_NUMBERS_SIMD_WIDEN(add)) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_GENERIC(sub, sub_op, Policy != overflow_policy::throw_exception, BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_GENERIC(mul, mul_op, Policy != overflow_policy::throw_exception, BOOST_SAFE_NUMBERS_SIMD_WIDEN(mul)) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_GENERIC(div, div_op, Policy == overflow_policy::checked || Policy == overflow_policy::strict, BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_GENERIC(mod, mod_op, Policy == overflow_policy::checked || Policy == overflow_policy::strict, BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_GENERIC(shl, shl_op, Policy != overflow_policy::throw_exception, BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN) +BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_GENERIC(shr, shr_op, Policy != overflow_policy::throw_exception, BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN) + +#undef BOOST_SAFE_NUMBERS_SIMD_WIDEN +#undef BOOST_SAFE_NUMBERS_SIMD_NO_WIDEN +#undef BOOST_SAFE_NUMBERS_SIMD_UNSIGNED_GENERIC + +} // namespace boost::safe_numbers::simd + +#endif // BOOST_SAFE_NUMBERS_DETAIL_SIMD_UNSIGNED_OPS_HPP diff --git a/include/boost/safe_numbers/detail/simd/vec.hpp b/include/boost/safe_numbers/detail/simd/vec.hpp new file mode 100644 index 00000000..68bd60ba --- /dev/null +++ b/include/boost/safe_numbers/detail/simd/vec.hpp @@ -0,0 +1,795 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#ifndef BOOST_SAFE_NUMBERS_DETAIL_SIMD_VEC_HPP +#define BOOST_SAFE_NUMBERS_DETAIL_SIMD_VEC_HPP + +#include +#include +#include +#include +#include + +#ifndef BOOST_SAFE_NUMBERS_BUILD_MODULE + +#include + +#endif // BOOST_SAFE_NUMBERS_BUILD_MODULE + +namespace boost::safe_numbers::simd { + +template +class vec; + +} // namespace boost::safe_numbers::simd + +namespace boost::safe_numbers::detail::simd_impl { + +// u8, u16, u32, u64 and i8, i16, i32, i64 in any policy form. Floating point +// elements are rejected until their lane operations exist. +template +inline constexpr bool is_unsigned_element_v {is_unsigned_library_type_v && !is_bounded_type_v && + !std::is_same_v, int128::uint128>}; + +template +inline constexpr bool is_signed_element_v {is_signed_library_type_v && !is_bounded_type_v && + !std::is_same_v, int128::int128>}; + +template +inline constexpr bool is_supported_element_v {is_unsigned_element_v || is_signed_element_v}; + +template +inline constexpr bool is_128_bit_element_v {std::is_same_v, int128::uint128> || + std::is_same_v, int128::int128>}; + +// The basis type of a supported element, and a placeholder otherwise so that the +// class static_asserts are the only diagnostics for an unsupported element +template +struct element_basis +{ + using type = std::uint8_t; +}; + +template + requires is_supported_element_v +struct element_basis +{ + using type = typename T::basis_type; +}; + +template +using element_basis_t = typename element_basis::type; + +template +consteval auto element_policy() noexcept +{ + if constexpr (is_supported_element_v) + { + return T::error_policy; + } + else + { + return overflow_policy::throw_exception; + } +} + +template +consteval auto native_size() noexcept -> int +{ + if constexpr (is_supported_element_v) + { + return native_lanes; + } + else + { + return 1; + } +} + +template +struct is_vec : std::false_type {}; + +template +struct is_vec> : std::true_type {}; + +template +inline constexpr bool is_vec_v {is_vec>::value}; + +template +concept generator_lane = std::invocable> && + std::is_same_v>>, T>; + +template +inline constexpr bool is_generator_for_v {false}; + +template +inline constexpr bool is_generator_for_v> {(generator_lane(I)> && ...)}; + +// Compile-time length of a range when its type carries one +template +struct static_extent : std::integral_constant {}; + +template +struct static_extent : std::integral_constant {}; + +template +struct static_extent> : std::integral_constant {}; + +template +struct static_extent> : std::integral_constant {}; + +template +inline constexpr std::size_t static_extent_v {static_extent>::value}; + +struct storage_tag {}; + +// Gives the operation headers the lane storage of a vec without making it public +struct access +{ + template + [[nodiscard]] static constexpr auto data(const V& v) noexcept -> const typename V::storage_type& + { + return v.data_; + } + + template + [[nodiscard]] static constexpr auto make(const typename V::storage_type& s) noexcept -> V + { + return V{storage_tag{}, s}; + } +}; + +// Cold error paths. They recompute every lane in order through the scalar +// operation, so the first lane that fails throws or exits exactly as the scalar +// loop would, and a user handler sees each failing lane with the scalar arguments. +template +BOOST_SAFE_NUMBERS_NOINLINE BOOST_SAFE_NUMBERS_COLD +constexpr auto replay_binary(const V& lhs, const V& rhs, F op) -> V +{ + using basis_type = typename V::basis_type; + + std::array res {}; + for (std::size_t i {}; i < res.size(); ++i) + { + const auto lane {static_cast(i)}; + res[i] = static_cast(op(lhs[lane], rhs[lane])); + } + + return V{res}; +} + +template +BOOST_SAFE_NUMBERS_NOINLINE BOOST_SAFE_NUMBERS_COLD +constexpr auto replay_unary(const V& v, F op) -> R +{ + using basis_type = typename R::basis_type; + + std::array res {}; + for (std::size_t i {}; i < res.size(); ++i) + { + res[i] = static_cast(op(v[static_cast(i)])); + } + + return R{res}; +} + +// Argument for operations that each element kind's header overloads (conversions, +// increment, decrement): it makes unqualified calls find those overloads by ADL +struct adl_tag {}; + +} // namespace boost::safe_numbers::detail::simd_impl + +namespace boost::safe_numbers::simd { + +// A fixed-size vector of safe numbers. Lane i of every operation equals the scalar +// operation on lane i, and an error reports the lowest failing lane exactly as the +// scalar loop over i = 0 ... N - 1 would. The error policy is the element's. +template ()> +class vec +{ + static_assert(detail::is_library_type_v, + "simd::vec requires a Boost.safe_numbers element type such as u32"); + + static_assert(!detail::is_bounded_type_v, + "simd::vec does not support bounded_uint, bounded_int, or bounded_float elements"); + + static_assert(!detail::simd_impl::is_128_bit_element_v, + "simd::vec does not support 128-bit elements (u128, i128): std::simd has no 128-bit lanes"); + + static_assert(detail::simd_impl::is_supported_element_v, + "simd::vec supports the unsigned types u8, u16, u32, and u64 and the signed types " + "i8, i16, i32, and i64 in any policy form"); + + static_assert(N >= 1, "simd::vec requires at least one lane"); + +public: + + using value_type = T; + using basis_type = detail::simd_impl::element_basis_t; + using storage_type = detail::simd_impl::storage_t; + using mask_type = detail::simd_impl::mask_t; + + static constexpr auto error_policy {detail::simd_impl::element_policy()}; + + static constexpr std::integral_constant size {}; + + // Loads and stores copy lanes through the basis type, which relies on this layout + static_assert(!detail::simd_impl::is_supported_element_v || + (std::is_trivially_copyable_v && std::is_standard_layout_v && sizeof(T) == sizeof(basis_type)), + "simd::vec element types must be layout compatible with their basis type"); + +private: + + storage_type data_ {}; + + friend struct detail::simd_impl::access; + + constexpr vec(detail::simd_impl::storage_tag, const storage_type& s) noexcept : data_ {s} {} + +public: + + // Zero in every lane, like the scalar types + constexpr vec() noexcept = default; + + // Broadcast. Only the exact element type is accepted, as in the scalar types. + template + requires std::is_same_v + explicit constexpr vec(const U x) noexcept : data_ {static_cast(x)} {} + + // Lane i is gen(std::integral_constant{}). The calls are unsequenced. + template + requires (!std::is_same_v, vec> && std::invocable>) + explicit constexpr vec(G&& gen) + : data_ {[&gen](const auto i) { return static_cast(gen(i)); }} + { + static_assert(detail::simd_impl::is_generator_for_v(N)>>, + "The simd::vec generator must return exactly the element type for every lane"); + } + + // Raw lane interop, available on every backend + explicit constexpr vec(const std::array(N)>& lanes) noexcept : data_ {detail::simd_impl::from_array(lanes)} {} + + [[nodiscard]] explicit constexpr operator std::array(N)>() const noexcept + { + return detail::simd_impl::to_array(data_); + } + + #ifdef BOOST_SAFE_NUMBERS_HAS_STD_SIMD + + explicit constexpr vec(const std::simd::vec& lanes) noexcept : data_ {lanes} {} + + [[nodiscard]] explicit constexpr operator std::simd::vec() const noexcept + { + return data_; + } + + #endif // BOOST_SAFE_NUMBERS_HAS_STD_SIMD + + // Converts every lane as the scalar conversion would; a lane out of the target + // range throws std::domain_error whatever the error policy + template + requires (!std::is_same_v) + explicit constexpr vec(const vec& other) : vec {convert_elements(detail::simd_impl::adl_tag {}, std::type_identity {}, other)} {} + + // Precondition: 0 <= i < N + [[nodiscard]] constexpr auto operator[](const int i) const noexcept -> T + { + return T{static_cast(data_[i])}; + } + + // Compound assignment computes the result first, so the operand is unchanged on error + template + constexpr auto operator+=(const U& rhs) noexcept(noexcept(std::declval() + rhs)) -> vec& + { + *this = *this + rhs; + return *this; + } + + template + constexpr auto operator-=(const U& rhs) noexcept(noexcept(std::declval() - rhs)) -> vec& + { + *this = *this - rhs; + return *this; + } + + template + constexpr auto operator*=(const U& rhs) noexcept(noexcept(std::declval() * rhs)) -> vec& + { + *this = *this * rhs; + return *this; + } + + template + constexpr auto operator/=(const U& rhs) noexcept(noexcept(std::declval() / rhs)) -> vec& + { + *this = *this / rhs; + return *this; + } + + template + constexpr auto operator%=(const U& rhs) noexcept(noexcept(std::declval() % rhs)) -> vec& + { + *this = *this % rhs; + return *this; + } + + template + constexpr auto operator&=(const U& rhs) noexcept(noexcept(std::declval() & rhs)) -> vec& + { + *this = *this & rhs; + return *this; + } + + template + constexpr auto operator|=(const U& rhs) noexcept(noexcept(std::declval() | rhs)) -> vec& + { + *this = *this | rhs; + return *this; + } + + template + constexpr auto operator^=(const U& rhs) noexcept(noexcept(std::declval() ^ rhs)) -> vec& + { + *this = *this ^ rhs; + return *this; + } + + template + constexpr auto operator<<=(const U& rhs) noexcept(noexcept(std::declval() << rhs)) -> vec& + { + *this = *this << rhs; + return *this; + } + + template + constexpr auto operator>>=(const U& rhs) noexcept(noexcept(std::declval() >> rhs)) -> vec& + { + *this = *this >> rhs; + return *this; + } + + // Each element kind's header provides increment and decrement + constexpr auto operator++() noexcept(detail::policy_is_nothrow_arith()) -> vec& + { + *this = increment(detail::simd_impl::adl_tag {}, *this); + return *this; + } + + constexpr auto operator++(int) noexcept(detail::policy_is_nothrow_arith()) -> vec + { + const auto old {*this}; + *this = increment(detail::simd_impl::adl_tag {}, *this); + return old; + } + + constexpr auto operator--() noexcept(detail::policy_is_nothrow_arith()) -> vec& + { + *this = decrement(detail::simd_impl::adl_tag {}, *this); + return *this; + } + + constexpr auto operator--(int) noexcept(detail::policy_is_nothrow_arith()) -> vec + { + const auto old {*this}; + *this = decrement(detail::simd_impl::adl_tag {}, *this); + return old; + } + + constexpr auto operator+() const noexcept -> vec { return *this; } +}; + +// ------------------------------ +// Mask reductions +// ------------------------------ + +// std::simd's own overloads on the std backend, overloads on the fallback mask otherwise +using detail::simd_impl::all_of; +using detail::simd_impl::any_of; +using detail::simd_impl::none_of; +using detail::simd_impl::reduce_count; +using detail::simd_impl::reduce_min_index; +using detail::simd_impl::reduce_max_index; + +// ------------------------------ +// Comparisons +// ------------------------------ + +template +[[nodiscard]] constexpr auto operator==(const vec& lhs, const vec& rhs) noexcept -> typename vec::mask_type +{ + using access = detail::simd_impl::access; + return access::data(lhs) == access::data(rhs); +} + +template +[[nodiscard]] constexpr auto operator!=(const vec& lhs, const vec& rhs) noexcept -> typename vec::mask_type +{ + using access = detail::simd_impl::access; + return access::data(lhs) != access::data(rhs); +} + +template +[[nodiscard]] constexpr auto operator<(const vec& lhs, const vec& rhs) noexcept -> typename vec::mask_type +{ + using access = detail::simd_impl::access; + return access::data(lhs) < access::data(rhs); +} + +template +[[nodiscard]] constexpr auto operator<=(const vec& lhs, const vec& rhs) noexcept -> typename vec::mask_type +{ + using access = detail::simd_impl::access; + return access::data(lhs) <= access::data(rhs); +} + +template +[[nodiscard]] constexpr auto operator>(const vec& lhs, const vec& rhs) noexcept -> typename vec::mask_type +{ + using access = detail::simd_impl::access; + return access::data(lhs) > access::data(rhs); +} + +template +[[nodiscard]] constexpr auto operator>=(const vec& lhs, const vec& rhs) noexcept -> typename vec::mask_type +{ + using access = detail::simd_impl::access; + return access::data(lhs) >= access::data(rhs); +} + +// ------------------------------ +// Broadcasting and rejected mixing +// ------------------------------ + +// vec op T and T op vec broadcast the element. Every other mix is a compile error, as +// in the scalar types: different element types (width, signedness, policy), different +// lane counts, and built-in or other non-element operands. +#define BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP(OP_NAME, OP_SYMBOL) \ +template \ + requires (!std::is_same_v || LN != RN) \ +constexpr auto OP_SYMBOL(const vec&, const vec&) \ +{ \ + if constexpr (LN != RN) \ + { \ + static_assert(detail::dependent_false, \ + "Can not perform " OP_NAME " between simd::vec objects with different numbers of lanes"); \ + } \ + else \ + { \ + static_assert(detail::dependent_false, \ + "Can not perform " OP_NAME " between simd::vec objects with different element types " \ + "(width, signedness, or overflow policy): convert explicitly first, which is only " \ + "possible between elements of the same signedness"); \ + } \ + \ + return vec{}; \ +} + +#define BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP(OP_NAME, OP_SYMBOL) \ +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP(OP_NAME, OP_SYMBOL) \ + \ +template \ +[[nodiscard]] constexpr auto OP_SYMBOL(const vec& lhs, const T& rhs) \ + noexcept(noexcept(OP_SYMBOL(lhs, lhs))) \ +{ \ + return OP_SYMBOL(lhs, vec{rhs}); \ +} \ + \ +template \ +[[nodiscard]] constexpr auto OP_SYMBOL(const T& lhs, const vec& rhs) \ + noexcept(noexcept(OP_SYMBOL(rhs, rhs))) \ +{ \ + return OP_SYMBOL(vec{lhs}, rhs); \ +} \ + \ +template \ + requires (!std::is_same_v && !detail::simd_impl::is_vec_v) \ +constexpr auto OP_SYMBOL(const vec&, const U&) \ +{ \ + static_assert(detail::dependent_false, \ + "Can not perform " OP_NAME " between a simd::vec and a type other than its element type"); \ + return vec{}; \ +} \ + \ +template \ + requires (!std::is_same_v && !detail::simd_impl::is_vec_v) \ +constexpr auto OP_SYMBOL(const U&, const vec&) \ +{ \ + static_assert(detail::dependent_false, \ + "Can not perform " OP_NAME " between a type other than the element type and a simd::vec"); \ + return vec{}; \ +} + +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("equality", operator==) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("inequality", operator!=) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("comparison", operator<) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("comparison", operator<=) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("comparison", operator>) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("comparison", operator>=) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("addition", operator+) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("subtraction", operator-) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("multiplication", operator*) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("division", operator/) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("modulo", operator%) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("bitwise and", operator&) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("bitwise or", operator|) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("bitwise xor", operator^) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("left shift", operator<<) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP("right shift", operator>>) + +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("saturating addition", saturating_add) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("saturating subtraction", saturating_sub) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("saturating multiplication", saturating_mul) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("saturating division", saturating_div) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("saturating modulo", saturating_mod) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("saturating left shift", saturating_shl) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("saturating right shift", saturating_shr) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("overflowing addition", overflowing_add) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("overflowing subtraction", overflowing_sub) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("overflowing multiplication", overflowing_mul) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("overflowing division", overflowing_div) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("overflowing modulo", overflowing_mod) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("overflowing left shift", overflowing_shl) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("overflowing right shift", overflowing_shr) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("checked addition", checked_add) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("checked subtraction", checked_sub) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("checked multiplication", checked_mul) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("checked division", checked_div) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("checked modulo", checked_mod) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("checked left shift", checked_shl) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("checked right shift", checked_shr) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("strict addition", strict_add) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("strict subtraction", strict_sub) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("strict multiplication", strict_mul) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("strict division", strict_div) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("strict modulo", strict_mod) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("strict left shift", strict_shl) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("strict right shift", strict_shr) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("widening addition", widening_add) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("widening multiplication", widening_mul) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("min", min) +BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP("max", max) + +#undef BOOST_SAFE_NUMBERS_SIMD_DEFINE_BROADCAST_OP +#undef BOOST_SAFE_NUMBERS_SIMD_DEFINE_MIXED_VEC_OP + +// ------------------------------ +// Select, min, max, clamp +// ------------------------------ + +template +[[nodiscard]] constexpr auto select(const typename vec::mask_type& m, const vec& lhs, const vec& rhs) noexcept -> vec +{ + using access = detail::simd_impl::access; + return access::make>(detail::simd_impl::select(m, access::data(lhs), access::data(rhs))); +} + +template +[[nodiscard]] constexpr auto min(const vec& lhs, const vec& rhs) noexcept -> vec +{ + using access = detail::simd_impl::access; + return access::make>(detail::simd_impl::min(access::data(lhs), access::data(rhs))); +} + +template +[[nodiscard]] constexpr auto max(const vec& lhs, const vec& rhs) noexcept -> vec +{ + using access = detail::simd_impl::access; + return access::make>(detail::simd_impl::max(access::data(lhs), access::data(rhs))); +} + +// Precondition: no lane of lo is greater than the same lane of hi +template +[[nodiscard]] constexpr auto clamp(const vec& v, const vec& lo, const vec& hi) noexcept -> vec +{ + return max(lo, min(hi, v)); +} + +// ------------------------------ +// Reductions +// ------------------------------ + +// A left fold in lane order with the element's own operation, so overflow is +// reported (or saturated) exactly as by the scalar loop +template > +[[nodiscard]] constexpr auto reduce(const vec& v, BinaryOperation op = {}) + noexcept(noexcept(op(std::declval(), std::declval()))) -> T +{ + auto res {v[0]}; + for (int i {1}; i < N; ++i) + { + res = op(res, v[i]); + } + + return res; +} + +template +[[nodiscard]] constexpr auto reduce_min(const vec& v) noexcept -> T +{ + return T{static_cast::basis_type>(detail::simd_impl::reduce_min(detail::simd_impl::access::data(v)))}; +} + +template +[[nodiscard]] constexpr auto reduce_max(const vec& v) noexcept -> T +{ + return T{static_cast::basis_type>(detail::simd_impl::reduce_max(detail::simd_impl::access::data(v)))}; +} + +// ------------------------------ +// Loads and stores +// ------------------------------ + +// Each lane is read through the element's conversion to its basis type, which is +// well defined and compiles to a single vector load. + +namespace impl { + +template +constexpr auto load_lanes(const P* const p, const int n) noexcept -> V +{ + using basis_type = typename V::basis_type; + using storage_type = typename V::storage_type; + + return detail::simd_impl::access::make(storage_type{[p, n](const auto i) + { + return static_cast(i) < n ? static_cast(p[static_cast(i)]) : basis_type{0}; + }}); +} + +template +constexpr auto load_all_lanes(const P* const p) noexcept -> V +{ + using basis_type = typename V::basis_type; + using storage_type = typename V::storage_type; + + return detail::simd_impl::access::make(storage_type{[p](const auto i) + { + return static_cast(p[static_cast(i)]); + }}); +} + +template +constexpr auto store_lanes(const V& v, P* const p, const int n) noexcept -> void +{ + using value_type = typename V::value_type; + + const auto& lanes {detail::simd_impl::access::data(v)}; + for (int i {}; i < n; ++i) + { + p[i] = value_type{lanes[i]}; + } +} + +// A contiguous sized range: std::array, std::vector, std::span, or a built-in array. +// Detected through std::data and std::size rather than , which some of the +// supported compilers can not parse. +template +concept contiguous_sized_range = requires (R& r) +{ + { std::data(r) } -> std::convertible_to; + std::size(r); +}; + +template +using range_element_t = std::remove_cv_t()))>>; + +template +inline constexpr bool is_loadable_range_v {contiguous_sized_range>}; + +template +consteval auto check_range_value() noexcept -> bool +{ + static_assert(std::is_same_v>, typename V::value_type>, + "simd loads and stores require a range of exactly the vector's element type; " + "move built-in values through std::array(N)> instead"); + return true; +} + +template +consteval auto check_iterator_value() noexcept -> bool +{ + static_assert(std::is_same_v, typename V::value_type>, + "simd loads and stores require iterators to exactly the vector's element type; " + "move built-in values through std::array(N)> instead"); + return true; +} + +template +consteval auto check_static_extent() noexcept -> bool +{ + constexpr auto extent {detail::simd_impl::static_extent_v}; + static_assert(extent == std::dynamic_extent || extent >= static_cast(V::size()), + "The range is shorter than the vector: use partial_load or partial_store"); + return true; +} + +template +constexpr auto clamp_count(const R n, const int lanes) noexcept -> int +{ + if constexpr (std::is_signed_v) + { + if (n < 0) + { + return 0; + } + } + + return n < static_cast(lanes) ? static_cast(n) : lanes; +} + +} // namespace impl + +// Precondition: the range holds at least V::size() elements +template + requires (detail::simd_impl::is_vec_v && impl::is_loadable_range_v) +[[nodiscard]] constexpr auto unchecked_load(R&& r) noexcept -> V +{ + static_assert(impl::check_range_value() && impl::check_static_extent()); + return impl::load_all_lanes(std::data(r)); +} + +// Precondition: [first, first + n) is valid and n >= V::size() +template + requires detail::simd_impl::is_vec_v +[[nodiscard]] constexpr auto unchecked_load(const It first, const std::iter_difference_t n) noexcept -> V +{ + static_assert(impl::check_iterator_value()); + static_cast(n); + return impl::load_all_lanes(std::to_address(first)); +} + +// Loads min(size, V::size()) elements and zero fills the remaining lanes +template + requires (detail::simd_impl::is_vec_v && impl::is_loadable_range_v) +[[nodiscard]] constexpr auto partial_load(R&& r) noexcept -> V +{ + static_assert(impl::check_range_value()); + return impl::load_lanes(std::data(r), impl::clamp_count(std::size(r), V::size())); +} + +template + requires detail::simd_impl::is_vec_v +[[nodiscard]] constexpr auto partial_load(const It first, const std::iter_difference_t n) noexcept -> V +{ + static_assert(impl::check_iterator_value()); + return impl::load_lanes(std::to_address(first), impl::clamp_count(n, V::size())); +} + +// Precondition: the range holds at least N elements +template + requires impl::is_loadable_range_v, R> +constexpr auto unchecked_store(const vec& v, R&& r) noexcept -> void +{ + static_assert(impl::check_range_value, R>() && impl::check_static_extent, R>()); + impl::store_lanes(v, std::data(r), N); +} + +// Precondition: [first, first + n) is valid and n >= N +template +constexpr auto unchecked_store(const vec& v, const It first, const std::iter_difference_t n) noexcept -> void +{ + static_assert(impl::check_iterator_value, It>()); + static_cast(n); + impl::store_lanes(v, std::to_address(first), N); +} + +// Stores min(size, N) lanes +template + requires impl::is_loadable_range_v, R> +constexpr auto partial_store(const vec& v, R&& r) noexcept -> void +{ + static_assert(impl::check_range_value, R>()); + impl::store_lanes(v, std::data(r), impl::clamp_count(std::size(r), N)); +} + +template +constexpr auto partial_store(const vec& v, const It first, const std::iter_difference_t n) noexcept -> void +{ + static_assert(impl::check_iterator_value, It>()); + impl::store_lanes(v, std::to_address(first), impl::clamp_count(n, N)); +} + +} // namespace boost::safe_numbers::simd + +#endif // BOOST_SAFE_NUMBERS_DETAIL_SIMD_VEC_HPP diff --git a/include/boost/safe_numbers/detail/unsigned_integer_basis.hpp b/include/boost/safe_numbers/detail/unsigned_integer_basis.hpp index 04481625..709ca9b0 100644 --- a/include/boost/safe_numbers/detail/unsigned_integer_basis.hpp +++ b/include/boost/safe_numbers/detail/unsigned_integer_basis.hpp @@ -2176,7 +2176,11 @@ struct shl_helper const auto raw_lhs {static_cast(lhs)}; const auto raw_rhs {static_cast(rhs)}; const auto lhs_width {static_cast(bit_width(raw_lhs))}; - const auto overflowed {lhs_width + raw_rhs >= static_cast(std::numeric_limits::digits)}; + constexpr auto digits {static_cast(std::numeric_limits::digits)}; + + // Test the count on its own first: lhs_width + raw_rhs wraps for counts near the + // maximum of u32, u64, and u128, which would let an out of range shift through + const auto overflowed {raw_rhs >= digits || lhs_width + raw_rhs >= digits}; // Left shift past the type width is an error under throw_exception and strict; // saturate/checked/overflow_tuple return a defined value, so they are excluded. @@ -2232,10 +2236,14 @@ struct shl_helper const auto raw_lhs {static_cast(lhs)}; const auto raw_rhs {static_cast(rhs)}; const auto lhs_width {static_cast(bit_width(raw_lhs))}; - const auto overflowed {lhs_width + raw_rhs >= static_cast(std::numeric_limits::digits)}; + constexpr auto digits {static_cast(std::numeric_limits::digits)}; + + // Test the count on its own first: lhs_width + raw_rhs wraps for counts near the + // maximum of u32, u64, and u128, which would let an out of range shift through + const auto overflowed {raw_rhs >= digits || lhs_width + raw_rhs >= digits}; // Guard against UB: shifting by >= digits is undefined behavior - if (raw_rhs >= static_cast(std::numeric_limits::digits)) + if (raw_rhs >= digits) { return std::make_pair(result_type{0U}, true); } @@ -2260,7 +2268,11 @@ struct shl_helper const auto raw_lhs {static_cast(lhs)}; const auto raw_rhs {static_cast(rhs)}; const auto lhs_width {static_cast(bit_width(raw_lhs))}; - const auto overflowed {lhs_width + raw_rhs >= static_cast(std::numeric_limits::digits)}; + constexpr auto digits {static_cast(std::numeric_limits::digits)}; + + // Test the count on its own first: lhs_width + raw_rhs wraps for counts near the + // maximum of u32, u64, and u128, which would let an out of range shift through + const auto overflowed {raw_rhs >= digits || lhs_width + raw_rhs >= digits}; return overflowed ? std::nullopt : std::make_optional(result_type{static_cast(raw_lhs << raw_rhs)}); } diff --git a/include/boost/safe_numbers/simd.hpp b/include/boost/safe_numbers/simd.hpp new file mode 100644 index 00000000..0e995e2e --- /dev/null +++ b/include/boost/safe_numbers/simd.hpp @@ -0,0 +1,19 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#ifndef BOOST_SAFE_NUMBERS_SIMD_HPP +#define BOOST_SAFE_NUMBERS_SIMD_HPP + +// boost::safe_numbers::simd::vec: N safe numbers of type T checked a whole +// vector at a time. Built on C++26 when the standard library provides it, +// and on a portable std::array backend otherwise, with the same interface. + +#include +#include +#include +#include +#include +#include + +#endif // BOOST_SAFE_NUMBERS_SIMD_HPP diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 42ddea8d..bf104265 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -43,10 +43,16 @@ if(HAVE_BOOST_TEST) else() + # The simd differential tests instantiate more sections than a default COFF object + # holds. GNU as needs -mbig-obj for that; LLVM switches to big objects on its own. + set(BOOST_SAFE_NUMBERS_TEST_BIGOBJ + $<$:/bigobj> + $<$,$,$>>:-Wa,-mbig-obj>) + if(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|amd64|i386|i686|x86" AND NOT MINGW) - boost_test_jamfile(FILE Jamfile LINK_LIBRARIES Boost::safe_numbers Boost::config Boost::multiprecision Boost::safe_numerics Boost::throw_exception Boost::exception Boost::stacktrace_from_exception) + boost_test_jamfile(FILE Jamfile LINK_LIBRARIES Boost::safe_numbers Boost::config Boost::multiprecision Boost::safe_numerics Boost::throw_exception Boost::exception Boost::stacktrace_from_exception COMPILE_OPTIONS ${BOOST_SAFE_NUMBERS_TEST_BIGOBJ}) else() - boost_test_jamfile(FILE Jamfile LINK_LIBRARIES Boost::safe_numbers Boost::config Boost::multiprecision Boost::safe_numerics Boost::throw_exception Boost::exception) + boost_test_jamfile(FILE Jamfile LINK_LIBRARIES Boost::safe_numbers Boost::config Boost::multiprecision Boost::safe_numerics Boost::throw_exception Boost::exception COMPILE_OPTIONS ${BOOST_SAFE_NUMBERS_TEST_BIGOBJ}) endif() endif() diff --git a/test/Jamfile b/test/Jamfile index bded866e..14be6140 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -59,6 +59,10 @@ project : requirements clang:-Wassign-enum msvc:on + # The simd differential tests instantiate more sections than a default COFF object holds + msvc:/bigobj + gcc,windows:"-Wa,-mbig-obj" + gcc,cygwin:"-Wa,-mbig-obj" clang:on gcc:on @@ -299,6 +303,39 @@ run test_bounded_float_limits.cpp ; run test_bounded_limits.cpp ; compile-fail compile_fail_bounded_float_mixed_ops.cpp ; +# simd::vec, from the opt-in header boost/safe_numbers/simd.hpp. Each run test also +# builds through a *_array wrapper that forces the portable std::array backend, so the +# gcc-16 C++26 job covers both the std::simd backend and the fallback. +run test_simd_unsigned.cpp ; +run test_simd_unsigned_array.cpp ; +run test_simd_u64_mul.cpp ; +run test_simd_u64_mul_array.cpp ; +run test_simd_load_store.cpp ; +run test_simd_load_store_array.cpp ; +run test_simd_unsigned_constexpr.cpp ; +run test_simd_unsigned_constexpr_array.cpp ; +run test_simd_backend_selected.cpp ; +run-fail test_simd_strict.cpp ; +compile-fail compile_fail_simd_mixed_width.cpp ; +compile-fail compile_fail_simd_mixed_size.cpp ; +compile-fail compile_fail_simd_mixed_policy.cpp ; +compile-fail compile_fail_simd_builtin.cpp ; +compile-fail compile_fail_simd_u128.cpp ; +compile-fail compile_fail_simd_bounded.cpp ; +compile-fail compile_fail_simd_unary_minus.cpp ; +run test_simd_signed.cpp ; +run test_simd_signed_array.cpp ; +run test_simd_i64_mul.cpp ; +run test_simd_i64_mul_array.cpp ; +run test_simd_signed_constexpr.cpp ; +run test_simd_signed_constexpr_array.cpp ; +run-fail test_simd_signed_strict.cpp ; +compile-fail compile_fail_simd_signed_bitwise.cpp ; +compile-fail compile_fail_simd_signed_shift.cpp ; +compile-fail compile_fail_simd_mixed_sign.cpp ; +compile-fail compile_fail_simd_sign_conversion.cpp ; +compile-fail compile_fail_simd_i128.cpp ; + # Signed free function tests run test_signed_charconv.cpp ; run test_signed_fmt_format.cpp ; @@ -367,6 +404,8 @@ compile compile_tests/compile_test_signed_integers.cpp : off ; compile compile_tests/compile_test_floats.cpp : off ; +compile compile_tests/compile_test_simd.cpp + : off ; # Run the examples run ../examples/basic_usage.cpp ; @@ -394,6 +433,8 @@ run ../examples/integer_utilities.cpp ; run ../examples/numeric.cpp ; run ../examples/std_numeric_usage.cpp ; run ../examples/floats.cpp ; +run ../examples/simd_unsigned.cpp ; +run ../examples/simd_signed.cpp ; run ../examples/cmath.cpp ; run ../examples/functional.cpp ; run ../examples/random.cpp ; diff --git a/test/benchmarks/CMakeLists.txt b/test/benchmarks/CMakeLists.txt index 510eb0a3..dbaf3a26 100644 --- a/test/benchmarks/CMakeLists.txt +++ b/test/benchmarks/CMakeLists.txt @@ -76,6 +76,7 @@ set(BOOST_SAFE_NUMBERS_BENCHMARK_TARGETS benchmark_signed_operations benchmark_float_operations benchmark_policy_operations + benchmark_simd_operations ) foreach(bench ${BOOST_SAFE_NUMBERS_BENCHMARK_TARGETS}) diff --git a/test/benchmarks/benchmark_simd_operations.cpp b/test/benchmarks/benchmark_simd_operations.cpp new file mode 100644 index 00000000..2ca5ee78 --- /dev/null +++ b/test/benchmarks/benchmark_simd_operations.cpp @@ -0,0 +1,295 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Streaming out[i] = a[i] op b[i] over arrays of each unsigned and signed width, comparing: +// builtin the raw scalar loop on the basis type (no checks) +// std::simd the raw C++26 vector loop (no checks; std::simd backend only) +// scalar safe the scalar safe type loop (one error branch per element) +// vec simd::vec with the throwing policy (one error branch per vector) +// vec sat simd::vec with saturating lanes (no error branch) +// vec ovf overflowing_* with the masks accumulated and tested once +// The inputs never overflow, so every throwing loop runs its hot path. Report timings +// only from native hardware. + +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace boost::safe_numbers; + +namespace { + +constexpr std::size_t element_count {4096U}; + +struct add_op +{ + template + static constexpr auto apply(const T& lhs, const T& rhs) { return lhs + rhs; } + + template + static constexpr auto overflowing(const T& lhs, const T& rhs) { return simd::overflowing_add(lhs, rhs); } + + template + static constexpr auto saturating(const T& lhs, const T& rhs) { return simd::saturating_add(lhs, rhs); } +}; + +struct sub_op +{ + template + static constexpr auto apply(const T& lhs, const T& rhs) { return lhs - rhs; } + + template + static constexpr auto overflowing(const T& lhs, const T& rhs) { return simd::overflowing_sub(lhs, rhs); } + + template + static constexpr auto saturating(const T& lhs, const T& rhs) { return simd::saturating_sub(lhs, rhs); } +}; + +struct mul_op +{ + template + static constexpr auto apply(const T& lhs, const T& rhs) { return lhs * rhs; } + + template + static constexpr auto overflowing(const T& lhs, const T& rhs) { return simd::overflowing_mul(lhs, rhs); } + + template + static constexpr auto saturating(const T& lhs, const T& rhs) { return simd::saturating_mul(lhs, rhs); } +}; + +// Builtin wrapping arithmetic with promotion handled, for the unchecked baselines +template +constexpr auto raw_apply(const B lhs, const B rhs) -> B +{ + using wide = std::conditional_t<(sizeof(B) < sizeof(unsigned)), unsigned, B>; + return static_cast(Op::apply(static_cast(lhs), static_cast(rhs))); +} + +// Operands that never overflow, for unsigned and signed basis types alike: positive, +// lhs >= rhs for subtraction, both below sqrt(max) for multiplication and below max / 2 +// for addition +template +struct inputs +{ + std::vector lhs; + std::vector rhs; + + inputs() + { + std::mt19937_64 gen {42U}; + constexpr auto half_digits {std::numeric_limits::digits / 2}; + const auto limit {static_cast((std::uint64_t{1} << half_digits) - 1U)}; + std::uniform_int_distribution dist {1U, limit}; + + for (std::size_t i {}; i < element_count; ++i) + { + const auto x {static_cast(dist(gen))}; + const auto y {static_cast(dist(gen))}; + lhs.push_back(x > y ? x : y); + rhs.push_back(x > y ? y : x); + } + } + + static auto get() -> const inputs& + { + static const inputs data; + return data; + } +}; + +template +auto to_safe(const std::vector& raw) -> std::vector +{ + std::vector res; + res.reserve(raw.size()); + for (const auto x : raw) + { + res.push_back(T{x}); + } + + return res; +} + +template +void builtin_loop(benchmark::State& state) +{ + const auto& data {inputs::get()}; + std::vector out(element_count); + + for (auto _ : state) + { + for (std::size_t i {}; i < element_count; ++i) + { + out[i] = raw_apply(data.lhs[i], data.rhs[i]); + } + + benchmark::DoNotOptimize(out.data()); + benchmark::ClobberMemory(); + } + + state.SetItemsProcessed(static_cast(state.iterations() * element_count)); +} + +#ifdef BOOST_SAFE_NUMBERS_HAS_STD_SIMD + +template +void std_simd_loop(benchmark::State& state) +{ + using V = std::simd::vec; + constexpr auto lanes {static_cast(V::size())}; + + const auto& data {inputs::get()}; + std::vector out(element_count); + + for (auto _ : state) + { + for (std::size_t i {}; i < element_count; i += lanes) + { + const auto a {std::simd::unchecked_load(data.lhs.data() + i, static_cast(lanes))}; + const auto b {std::simd::unchecked_load(data.rhs.data() + i, static_cast(lanes))}; + std::simd::unchecked_store(Op::apply(a, b), out.data() + i, static_cast(lanes)); + } + + benchmark::DoNotOptimize(out.data()); + benchmark::ClobberMemory(); + } + + state.SetItemsProcessed(static_cast(state.iterations() * element_count)); +} + +#endif + +template +void scalar_safe_loop(benchmark::State& state) +{ + const auto& data {inputs::get()}; + const auto lhs {to_safe(data.lhs)}; + const auto rhs {to_safe(data.rhs)}; + std::vector out(element_count); + + for (auto _ : state) + { + for (std::size_t i {}; i < element_count; ++i) + { + out[i] = Op::apply(lhs[i], rhs[i]); + } + + benchmark::DoNotOptimize(out.data()); + benchmark::ClobberMemory(); + } + + state.SetItemsProcessed(static_cast(state.iterations() * element_count)); +} + +enum class form +{ + throwing, + saturating, + overflowing +}; + +template +void vec_loop(benchmark::State& state) +{ + using V = simd::vec; + constexpr auto lanes {static_cast(V::size())}; + + const auto& data {inputs::get()}; + const auto lhs {to_safe(data.lhs)}; + const auto rhs {to_safe(data.rhs)}; + std::vector out(element_count); + + for (auto _ : state) + { + auto errors {typename V::mask_type{false}}; + + for (std::size_t i {}; i < element_count; i += lanes) + { + const auto a {simd::unchecked_load(lhs.begin() + static_cast(i), static_cast(lanes))}; + const auto b {simd::unchecked_load(rhs.begin() + static_cast(i), static_cast(lanes))}; + const auto dest {out.begin() + static_cast(i)}; + + if constexpr (Form == form::throwing) + { + simd::unchecked_store(Op::apply(a, b), dest, static_cast(lanes)); + } + else if constexpr (Form == form::saturating) + { + simd::unchecked_store(Op::saturating(a, b), dest, static_cast(lanes)); + } + else + { + const auto [value, overflowed] {Op::overflowing(a, b)}; + errors = errors || overflowed; + simd::unchecked_store(value, dest, static_cast(lanes)); + } + } + + if (any_of(errors)) + { + throw std::overflow_error("unexpected overflow in the benchmark inputs"); // LCOV_EXCL_LINE + } + + benchmark::DoNotOptimize(out.data()); + benchmark::ClobberMemory(); + } + + state.SetItemsProcessed(static_cast(state.iterations() * element_count)); +} + +} // namespace + +#ifdef BOOST_SAFE_NUMBERS_HAS_STD_SIMD +# define BOOST_SAFE_NUMBERS_SIMD_BENCH_STD(B, OP) BENCHMARK(std_simd_loop)->Name(#B " " #OP " std::simd"); +#else +# define BOOST_SAFE_NUMBERS_SIMD_BENCH_STD(B, OP) +#endif + +#define BOOST_SAFE_NUMBERS_SIMD_BENCH(T, B, OP) \ +BENCHMARK(builtin_loop)->Name(#T " " #OP " builtin"); \ +BOOST_SAFE_NUMBERS_SIMD_BENCH_STD(B, OP) \ +BENCHMARK(scalar_safe_loop)->Name(#T " " #OP " scalar safe"); \ +BENCHMARK(vec_loop)->Name(#T " " #OP " vec"); \ +BENCHMARK(vec_loop)->Name(#T " " #OP " vec sat"); \ +BENCHMARK(vec_loop)->Name(#T " " #OP " vec ovf"); + +BOOST_SAFE_NUMBERS_SIMD_BENCH(u8, std::uint8_t, add_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u8, std::uint8_t, sub_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u8, std::uint8_t, mul_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u16, std::uint16_t, add_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u16, std::uint16_t, sub_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u16, std::uint16_t, mul_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u32, std::uint32_t, add_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u32, std::uint32_t, sub_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u32, std::uint32_t, mul_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u64, std::uint64_t, add_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u64, std::uint64_t, sub_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(u64, std::uint64_t, mul_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i8, std::int8_t, add_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i8, std::int8_t, sub_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i8, std::int8_t, mul_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i16, std::int16_t, add_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i16, std::int16_t, sub_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i16, std::int16_t, mul_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i32, std::int32_t, add_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i32, std::int32_t, sub_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i32, std::int32_t, mul_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i64, std::int64_t, add_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i64, std::int64_t, sub_op) +BOOST_SAFE_NUMBERS_SIMD_BENCH(i64, std::int64_t, mul_op) + +BENCHMARK_MAIN(); diff --git a/test/compile_fail_simd_bounded.cpp b/test/compile_fail_simd_bounded.cpp new file mode 100644 index 00000000..9f710f45 --- /dev/null +++ b/test/compile_fail_simd_bounded.cpp @@ -0,0 +1,18 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec does not accept bounded element types + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec, 4> v {}; + static_cast(v); + + return 0; +} diff --git a/test/compile_fail_simd_builtin.cpp b/test/compile_fail_simd_builtin.cpp new file mode 100644 index 00000000..fc735f8c --- /dev/null +++ b/test/compile_fail_simd_builtin.cpp @@ -0,0 +1,19 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec arithmetic with a built-in operand must not compile + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec lhs {u32{1U}}; + + const auto res {lhs + 1U}; + + return static_cast(static_cast(res[0])); +} diff --git a/test/compile_fail_simd_i128.cpp b/test/compile_fail_simd_i128.cpp new file mode 100644 index 00000000..d037a778 --- /dev/null +++ b/test/compile_fail_simd_i128.cpp @@ -0,0 +1,17 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec has no 128-bit lanes + +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec v {}; + static_cast(v); + + return 0; +} diff --git a/test/compile_fail_simd_mixed_policy.cpp b/test/compile_fail_simd_mixed_policy.cpp new file mode 100644 index 00000000..4d6bb9c9 --- /dev/null +++ b/test/compile_fail_simd_mixed_policy.cpp @@ -0,0 +1,20 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec arithmetic between the same width with different overflow policies must not compile + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec lhs {u32{1U}}; + const simd::vec rhs {sat_u32{1U}}; + + const auto res {lhs + rhs}; + + return static_cast(static_cast(res[0])); +} diff --git a/test/compile_fail_simd_mixed_sign.cpp b/test/compile_fail_simd_mixed_sign.cpp new file mode 100644 index 00000000..a3321815 --- /dev/null +++ b/test/compile_fail_simd_mixed_sign.cpp @@ -0,0 +1,20 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec arithmetic between signed and unsigned elements of the same width must not compile + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec lhs {i32{1}}; + const simd::vec rhs {u32{1U}}; + + const auto res {lhs + rhs}; + + return static_cast(static_cast(res[0])); +} diff --git a/test/compile_fail_simd_mixed_size.cpp b/test/compile_fail_simd_mixed_size.cpp new file mode 100644 index 00000000..7f217f42 --- /dev/null +++ b/test/compile_fail_simd_mixed_size.cpp @@ -0,0 +1,20 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec arithmetic between different numbers of lanes must not compile + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec lhs {u32{1U}}; + const simd::vec rhs {u32{1U}}; + + const auto res {lhs + rhs}; + + return static_cast(static_cast(res[0])); +} diff --git a/test/compile_fail_simd_mixed_width.cpp b/test/compile_fail_simd_mixed_width.cpp new file mode 100644 index 00000000..af255b6d --- /dev/null +++ b/test/compile_fail_simd_mixed_width.cpp @@ -0,0 +1,20 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec arithmetic between different element widths must not compile + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec lhs {u32{1U}}; + const simd::vec rhs {u16{1U}}; + + const auto res {lhs + rhs}; + + return static_cast(static_cast(res[0])); +} diff --git a/test/compile_fail_simd_sign_conversion.cpp b/test/compile_fail_simd_sign_conversion.cpp new file mode 100644 index 00000000..e7918ffc --- /dev/null +++ b/test/compile_fail_simd_sign_conversion.cpp @@ -0,0 +1,19 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec does not convert between signed and unsigned elements, as the scalar types do not + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec v {u32{1U}}; + + const simd::vec res {v}; + + return static_cast(static_cast(res[0])); +} diff --git a/test/compile_fail_simd_signed_bitwise.cpp b/test/compile_fail_simd_signed_bitwise.cpp new file mode 100644 index 00000000..0860fe27 --- /dev/null +++ b/test/compile_fail_simd_signed_bitwise.cpp @@ -0,0 +1,20 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Bitwise operators are disabled for vectors of signed elements, as for the scalar types + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec lhs {i32{1}}; + const simd::vec rhs {i32{3}}; + + const auto res {lhs & rhs}; + + return static_cast(static_cast(res[0])); +} diff --git a/test/compile_fail_simd_signed_shift.cpp b/test/compile_fail_simd_signed_shift.cpp new file mode 100644 index 00000000..e742a5f1 --- /dev/null +++ b/test/compile_fail_simd_signed_shift.cpp @@ -0,0 +1,19 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Shift operators are disabled for vectors of signed elements, as for the scalar types + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec lhs {i32{1}}; + + const auto res {lhs << i32{1}}; + + return static_cast(static_cast(res[0])); +} diff --git a/test/compile_fail_simd_u128.cpp b/test/compile_fail_simd_u128.cpp new file mode 100644 index 00000000..24777863 --- /dev/null +++ b/test/compile_fail_simd_u128.cpp @@ -0,0 +1,18 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec has no 128-bit lanes + +#include + + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec v {}; + static_cast(v); + + return 0; +} diff --git a/test/compile_fail_simd_unary_minus.cpp b/test/compile_fail_simd_unary_minus.cpp new file mode 100644 index 00000000..1731f62a --- /dev/null +++ b/test/compile_fail_simd_unary_minus.cpp @@ -0,0 +1,19 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Unary minus is disabled for vectors of unsigned elements, as for the scalar types + +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec v {u32{1U}}; + + const auto res {-v}; + + return static_cast(static_cast(res[0])); +} diff --git a/test/compile_tests/compile_test_simd.cpp b/test/compile_tests/compile_test_simd.cpp new file mode 100644 index 00000000..9e4adae0 --- /dev/null +++ b/test/compile_tests/compile_test_simd.cpp @@ -0,0 +1,10 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#include + +int main() +{ + return 0; +} diff --git a/test/test_simd_backend_selected.cpp b/test/test_simd_backend_selected.cpp new file mode 100644 index 00000000..9a21251d --- /dev/null +++ b/test/test_simd_backend_selected.cpp @@ -0,0 +1,22 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Fails when GCC 16 or later builds C++26 for x86-64 but the std::simd backend was not +// selected, which would otherwise silently test only the fallback + +#include + +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 16 && defined(__x86_64__) && \ + __cplusplus > 202302L && !defined(BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND) + +# ifndef BOOST_SAFE_NUMBERS_HAS_STD_SIMD +# error "GCC 16 C++26 on x86-64 should provide , but the std::simd backend was not selected" +# endif + +#endif + +int main() +{ + return 0; +} diff --git a/test/test_simd_i64_mul.cpp b/test/test_simd_i64_mul.cpp new file mode 100644 index 00000000..f86f7541 --- /dev/null +++ b/test/test_simd_i64_mul.cpp @@ -0,0 +1,198 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// The 64-bit signed lane multiplication multiplies the magnitudes with the unsigned +// 32-bit split and then checks the magnitude against 2^63 - 1 or 2^63, depending on the +// sign of the product. This checks the overflow mask, the wrapped value, the saturated +// value, and the overflow or underflow classification lane by lane against the scalar +// i64 on the cases that exercise each boundary. + +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace boost::safe_numbers; + +namespace { + +constexpr auto i64_max {std::numeric_limits::max()}; +constexpr auto i64_min {std::numeric_limits::min()}; + +// 0 when the scalar loop does not throw, 1 for std::overflow_error, 2 for std::underflow_error +template +auto thrown(F f) -> int +{ + try + { + f(); + } + catch (const std::overflow_error&) + { + return 1; + } + catch (const std::underflow_error&) + { + return 2; + } + + return 0; +} + +// Converts through the unsigned type, so every bit pattern is a valid input +constexpr auto from_bits(const std::uint64_t x) noexcept -> std::int64_t +{ + return static_cast(x); +} + +template +void check_pairs(const std::vector>& pairs) +{ + using V = simd::vec; + using S = simd::vec; + + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + std::array(N)> lhs {}; + std::array(N)> rhs {}; + + for (std::size_t i {}; i < lhs.size(); ++i) + { + const auto& p {pairs[(first + i) % pairs.size()]}; + lhs[i] = i64{p.first}; + rhs[i] = i64{p.second}; + } + + const auto va {simd::unchecked_load(lhs)}; + const auto vb {simd::unchecked_load(rhs)}; + const auto [value, flags] {simd::overflowing_mul(va, vb)}; + const auto saturated {S{va} * S{vb}}; + + for (std::size_t i {}; i < lhs.size(); ++i) + { + const auto lane {static_cast(i)}; + const auto [expected, overflowed] {overflowing_mul(lhs[i], rhs[i])}; + + BOOST_TEST(flags[lane] == overflowed); + BOOST_TEST(value[lane] == expected); + BOOST_TEST(saturated[lane] == saturating_mul(sat_i64{static_cast(lhs[i])}, sat_i64{static_cast(rhs[i])})); + } + + // The vector throws what the scalar loop throws first, or nothing + const auto scalar {thrown([&] + { + for (std::size_t i {}; i < lhs.size(); ++i) + { + static_cast(lhs[i] * rhs[i]); + } + })}; + + BOOST_TEST_EQ(thrown([&] { static_cast(va * vb); }), scalar); + BOOST_TEST_EQ(simd::checked_mul(va, vb).has_value(), scalar == 0); + } +} + +auto make_pairs() -> std::vector> +{ + std::vector> res; + + // Every combination of interesting high and low halves, with both signs + constexpr std::array halves {0U, 1U, 2U, 0x7FFFFFFFU, 0x80000000U, 0xFFFFFFFEU, 0xFFFFFFFFU}; + std::vector values {i64_min, i64_min + 1, i64_max}; + for (const auto hi : halves) + { + for (const auto lo : halves) + { + const auto x {(hi << 32U) | lo}; + values.push_back(from_bits(x)); + values.push_back(from_bits(0U - x)); + } + } + + for (const auto x : values) + { + for (const auto y : values) + { + res.emplace_back(x, y); + } + } + + // Products of exactly min, which fit, against their negations, which do not + for (int k {}; k < 64; ++k) + { + const auto p {from_bits(std::uint64_t{1} << k)}; + const auto q {from_bits(std::uint64_t{1} << (63 - k))}; + const auto neg_q {from_bits(0U - (std::uint64_t{1} << (63 - k)))}; + + res.emplace_back(p, neg_q); + res.emplace_back(neg_q, p); + res.emplace_back(from_bits(0U - static_cast(p)), q); + res.emplace_back(p, q); + res.emplace_back(from_bits(0U - static_cast(p)), neg_q); + } + + // Exactly at each boundary: x * (max / x) fits and one more step away from zero does not, + // for both signs of the product; likewise x * (min / x) + std::mt19937_64 gen {1234U}; + for (int i {}; i < 4000; ++i) + { + auto x {from_bits(gen() >> (gen() % 64U))}; + if (x < 2) + { + continue; + } + + if (gen() % 2U == 0U) + { + x = -x; + } + + const auto to_max {i64_max / x}; + const auto to_min {i64_min / x}; + const auto step {x > 0 ? std::int64_t{1} : std::int64_t{-1}}; + + res.emplace_back(x, to_max); + res.emplace_back(x, to_max + step); + res.emplace_back(to_min, x); + res.emplace_back(to_min - step, x); + } + + // Plain random pairs, and small by large + for (int i {}; i < 2000; ++i) + { + res.emplace_back(from_bits(gen()), from_bits(gen())); + res.emplace_back(from_bits(gen() >> 31U), from_bits(gen() >> 31U) - (INT64_C(1) << 32)); + res.emplace_back(from_bits(gen()) >> 40, from_bits(gen())); + } + + return res; +} + +} // namespace + +int main() +{ + const auto pairs {make_pairs()}; + + check_pairs<1>(pairs); + check_pairs<2>(pairs); + check_pairs<3>(pairs); + check_pairs<4>(pairs); + check_pairs<8>(pairs); + + return boost::report_errors(); +} diff --git a/test/test_simd_i64_mul_array.cpp b/test/test_simd_i64_mul_array.cpp new file mode 100644 index 00000000..d299e877 --- /dev/null +++ b/test/test_simd_i64_mul_array.cpp @@ -0,0 +1,9 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Runs test_simd_i64_mul.cpp on the portable std::array backend, which is otherwise +// not exercised wherever is available + +#define BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND +#include "test_simd_i64_mul.cpp" diff --git a/test/test_simd_load_store.cpp b/test/test_simd_load_store.cpp new file mode 100644 index 00000000..566826cb --- /dev/null +++ b/test/test_simd_load_store.cpp @@ -0,0 +1,286 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Loads, stores, and the other lane-level interfaces of simd::vec: lane order, +// zero fill of partial loads, raw lane interop, select, min, max, clamp, and reductions + +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace boost::safe_numbers; + +template +void test_load_store() +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + std::array(N) + 3U> data {}; + for (std::size_t i {}; i < data.size(); ++i) + { + data[i] = T{static_cast(i * 3U + 1U)}; + } + + // Range, iterator, and span forms all read lanes in order + const auto from_range {simd::unchecked_load(data)}; + const auto from_iterator {simd::unchecked_load(data.begin() + 1, N)}; + const auto from_span {simd::unchecked_load(std::span{data})}; + const auto from_vector {simd::unchecked_load(std::vector(data.begin(), data.end()))}; + + for (int i {}; i < N; ++i) + { + const auto index {static_cast(i)}; + BOOST_TEST(from_range[i] == data[index]); + BOOST_TEST(from_iterator[i] == data[index + 1U]); + BOOST_TEST(from_span[i] == data[index]); + BOOST_TEST(from_vector[i] == data[index]); + } + + // Partial loads read min(size, N) elements and zero fill the rest + for (int count {}; count <= N + 1; ++count) + { + const auto partial {simd::partial_load(std::span{data.data(), static_cast(count)})}; + const auto partial_iterator {simd::partial_load(data.begin(), count)}; + for (int i {}; i < N; ++i) + { + const auto expected {i < count ? data[static_cast(i)] : T{static_cast(0U)}}; + BOOST_TEST(partial[i] == expected); + BOOST_TEST(partial_iterator[i] == expected); + } + } + + BOOST_TEST(all_of(simd::partial_load(data.begin(), -1) == V{})); + + // Stores write lanes in order; partial stores write min(size, N) lanes + std::array(N) + 2U> out {}; + simd::unchecked_store(from_range, out); + for (int i {}; i < N; ++i) + { + BOOST_TEST(out[static_cast(i)] == data[static_cast(i)]); + } + BOOST_TEST(out[static_cast(N)] == T{static_cast(0U)}); + + std::array(N) + 2U> out_iterator {}; + simd::unchecked_store(from_range, out_iterator.begin() + 1, N); + BOOST_TEST(out_iterator[0] == T{static_cast(0U)}); + BOOST_TEST(out_iterator[1] == data[0]); + + for (int count {}; count <= N + 1; ++count) + { + std::array(N) + 2U> partial_out {}; + simd::partial_store(from_range, std::span{partial_out.data(), static_cast(count)}); + + std::array(N) + 2U> partial_out_iterator {}; + simd::partial_store(from_range, partial_out_iterator.begin(), count); + + for (int i {}; i < N + 2; ++i) + { + const auto index {static_cast(i)}; + const auto expected {i < count && i < N ? data[index] : T{static_cast(0U)}}; + BOOST_TEST(partial_out[index] == expected); + BOOST_TEST(partial_out_iterator[index] == expected); + } + } +} + +template +void test_construction() +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + static_assert(std::is_same_v); + static_assert(std::is_same_v); + static_assert(V::size() == N); + static_assert(V::size == N); + static_assert(detail::policy_equals(overflow_policy::throw_exception) == + detail::policy_equals(overflow_policy::throw_exception)); + + // Value initialization is zero in every lane + const V zero {}; + for (int i {}; i < N; ++i) + { + BOOST_TEST(zero[i] == T{static_cast(0U)}); + } + + // Broadcast and generator + const V broadcast {T{static_cast(7U)}}; + const V generated {[](const auto i) { return T{static_cast(static_cast(i) + 10)}; }}; + for (int i {}; i < N; ++i) + { + BOOST_TEST(broadcast[i] == T{static_cast(7U)}); + BOOST_TEST(generated[i] == T{static_cast(i + 10)}); + } + + // Raw lane interop through std::array on every backend + std::array(N)> raw {}; + for (std::size_t i {}; i < raw.size(); ++i) + { + raw[i] = static_cast(i + 100U); + } + + using raw_array = std::array(N)>; + const V from_raw {raw}; + BOOST_TEST(static_cast(from_raw) == raw); + BOOST_TEST(all_of(from_raw == generated + V{T{static_cast(90U)}})); + + #ifdef BOOST_SAFE_NUMBERS_HAS_STD_SIMD + + // And through std::simd::vec when the standard backend is in use + using std_vec = std::simd::vec; + const auto std_lanes {static_cast(from_raw)}; + BOOST_TEST(all_of(V{std_lanes} == from_raw)); + + #endif +} + +template +void test_lane_algorithms() +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + constexpr auto max {std::numeric_limits::max()}; + const V ascending {[](const auto i) { return T{static_cast(static_cast(i) + 1)}; }}; + const V descending {[](const auto i) { return T{static_cast(N - static_cast(i))}; }}; + + // Comparisons, including the broadcast forms + const auto less {ascending < descending}; + for (int i {}; i < N; ++i) + { + BOOST_TEST_EQ(less[i], i + 1 < N - i); + BOOST_TEST_EQ((ascending <= descending)[i], i + 1 <= N - i); + BOOST_TEST_EQ((ascending > descending)[i], i + 1 > N - i); + BOOST_TEST_EQ((ascending >= descending)[i], i + 1 >= N - i); + BOOST_TEST_EQ((ascending == descending)[i], i + 1 == N - i); + BOOST_TEST_EQ((ascending != descending)[i], i + 1 != N - i); + } + + const auto one {T{static_cast(1U)}}; + BOOST_TEST((ascending == one)[0]); + BOOST_TEST((one == ascending)[0]); + BOOST_TEST(none_of(ascending < one)); + BOOST_TEST(all_of(one <= ascending)); + BOOST_TEST_EQ(reduce_count(ascending > one), N - 1); + BOOST_TEST(any_of(ascending != one) == (N > 1)); + + if constexpr (N > 1) + { + BOOST_TEST_EQ(reduce_min_index(ascending > one), 1); + BOOST_TEST_EQ(reduce_max_index(ascending > one), N - 1); + } + + // select, min, max, and clamp lane by lane + const auto picked {select(less, ascending, descending)}; + const auto low {simd::min(ascending, descending)}; + const auto high {simd::max(ascending, descending)}; + const auto clamped {simd::clamp(ascending, V{T{static_cast(2U)}}, V{T{static_cast(3U)}})}; + for (int i {}; i < N; ++i) + { + BOOST_TEST(picked[i] == (less[i] ? ascending[i] : descending[i])); + BOOST_TEST(low[i] == (ascending[i] < descending[i] ? ascending[i] : descending[i])); + BOOST_TEST(high[i] == (ascending[i] < descending[i] ? descending[i] : ascending[i])); + BOOST_TEST(clamped[i] == T{static_cast(i + 1 < 2 ? 2 : (i + 1 > 3 ? 3 : i + 1))}); + } + + // Reductions fold left in lane order with the element's operation. The sum of 1 ... N + // fits u8 up to 16 lanes, and wider native vectors (AVX2, AVX-512) have more. + if constexpr (N <= 16) + { + BOOST_TEST(simd::reduce(ascending) == T{static_cast(N * (N + 1) / 2)}); + } + if constexpr (N <= 5) + { + // N! fits every lane type + constexpr auto factorial {[] { int f {1}; for (int i {2}; i <= N; ++i) { f *= i; } return f; }()}; + BOOST_TEST(simd::reduce(ascending, [](const T x, const T y) { return x * y; }) == T{static_cast(factorial)}); + } + BOOST_TEST(simd::reduce_min(descending) == one); + BOOST_TEST(simd::reduce_max(descending) == T{static_cast(N)}); + + // A sum that overflows throws as the scalar loop does, and saturates under saturate + const V big {T{max}}; + if constexpr (N > 1 && detail::policy_equals(overflow_policy::throw_exception)) + { + BOOST_TEST_THROWS(static_cast(simd::reduce(big)), std::overflow_error); + + using S = detail::unsigned_integer_basis; + BOOST_TEST(simd::reduce(simd::vec{big}) == S{max}); + } + else if constexpr (N == 1) + { + BOOST_TEST(simd::reduce(big) == T{max}); + } + + // Bitwise operators + const auto all_ones {~V{}}; + BOOST_TEST(all_of(all_ones == V{T{max}})); + BOOST_TEST(all_of((ascending & all_ones) == ascending)); + BOOST_TEST(all_of((ascending | V{}) == ascending)); + BOOST_TEST(all_of((ascending ^ ascending) == V{})); + BOOST_TEST(all_of(+ascending == ascending)); + + // Widening returns exact results in lanes twice as wide + if constexpr (sizeof(basis_type) < sizeof(std::uint64_t)) + { + const auto wide_sum {simd::widening_add(big, big)}; + const auto wide_product {simd::widening_mul(big, big)}; + using wide_basis = typename decltype(wide_sum)::basis_type; + static_assert(sizeof(wide_basis) == 2U * sizeof(basis_type)); + + BOOST_TEST(wide_sum[0] == decltype(wide_sum[0]){static_cast(static_cast(max) * 2U)}); + BOOST_TEST(wide_product[0] == decltype(wide_product[0]){static_cast(static_cast(max) * max)}); + BOOST_TEST(all_of(simd::add(big, big) == wide_sum)); + BOOST_TEST(all_of(simd::mul(big, big) == wide_product)); + } +} + +template +void test_all() +{ + test_load_store(); + test_construction(); + test_lane_algorithms(); +} + +template +void test_widths() +{ + test_all(); + test_all(); + test_all(); + test_all::size()>(); + test_all(); +} + +int main() +{ + test_widths(); + test_widths(); + test_widths(); + test_widths(); + test_widths(); + + // Every lane of a narrowing conversion is checked + const simd::vec wide {[](const auto i) { return u32{static_cast(static_cast(i) * 100)}; }}; + BOOST_TEST_THROWS(static_cast(simd::vec{wide}), std::domain_error); + BOOST_TEST(all_of(simd::vec{wide} == simd::vec{[](const auto i) { return u16{static_cast(static_cast(i) * 100)}; }})); + + return boost::report_errors(); +} diff --git a/test/test_simd_load_store_array.cpp b/test/test_simd_load_store_array.cpp new file mode 100644 index 00000000..82b1e50f --- /dev/null +++ b/test/test_simd_load_store_array.cpp @@ -0,0 +1,9 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Runs test_simd_load_store.cpp on the portable std::array backend, which is otherwise +// not exercised wherever is available + +#define BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND +#include "test_simd_load_store.cpp" diff --git a/test/test_simd_signed.cpp b/test/test_simd_signed.cpp new file mode 100644 index 00000000..514f8575 --- /dev/null +++ b/test/test_simd_signed.cpp @@ -0,0 +1,782 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Differential test of simd::vec of signed elements against the scalar library. For every +// policy, lane i of a vector operation must equal the scalar operation on lane i, and an +// error must be reported exactly as the scalar loop over i = 0 ... N - 1 reports it: the +// same exception type (overflow, underflow, or domain) and message, or the same sequence +// of user handler calls. + +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace boost::safe_numbers; + +// ------------------------------ +// Handler that records every call +// ------------------------------ + +struct handler_call +{ + error_kind kind; + std::int64_t value; + std::string message; + + friend auto operator==(const handler_call&, const handler_call&) -> bool = default; +}; + +inline std::vector& handler_log() +{ + static std::vector log; + return log; +} + +// Logs the call and returns a value that differs from the fallback, so a lane patched +// by the handler can not be mistaken for the wrapped result +struct recording_handler +{ + template + auto on_error(const error_kind kind, const T value, const char* msg) const -> T + { + handler_log().push_back(handler_call{kind, static_cast(value), msg}); + return static_cast(value ^ static_cast(0x5A)); + } +}; + +// ------------------------------ +// Outcome capture +// ------------------------------ + +struct outcome +{ + int exception {0}; + std::string message; + std::vector lanes; + std::vector calls; + + friend auto operator==(const outcome&, const outcome&) -> bool = default; +}; + +template +auto capture(F f) -> outcome +{ + outcome res; + handler_log().clear(); + + try + { + res.lanes = f(); + } + catch (const std::overflow_error& e) + { + res.exception = 1; + res.message = e.what(); + } + catch (const std::underflow_error& e) + { + res.exception = 2; + res.message = e.what(); + } + catch (const std::domain_error& e) + { + res.exception = 3; + res.message = e.what(); + } + + res.calls = handler_log(); + return res; +} + +template +auto raw(const T x) -> std::int64_t +{ + return static_cast(static_cast(x)); +} + +template +auto lanes_of(const simd::vec& v) -> std::vector +{ + std::vector res; + for (int i {}; i < N; ++i) + { + res.push_back(raw(v[i])); + } + + return res; +} + +template +auto flags_of(const M& m, const int n) -> std::vector +{ + std::vector res; + for (int i {}; i < n; ++i) + { + res.push_back(m[i] ? 1 : 0); + } + + return res; +} + +// ------------------------------ +// Inputs +// ------------------------------ + +// Values on both sides of every error boundary: the limits, the divisors 0 and -1, +// powers of two, and the operands whose square crosses the limits +template +auto edge_values() -> std::vector +{ + constexpr auto max {std::numeric_limits::max()}; + constexpr auto min {std::numeric_limits::min()}; + constexpr auto digits {std::numeric_limits::digits}; + + std::vector wide {0, 1, -1, 2, -2, 3, -3, 7, -7}; + + wide.push_back(max); + wide.push_back(max - 1); + wide.push_back(max / 2); + wide.push_back(max / 2 + 1); + wide.push_back(min); + wide.push_back(min + 1); + wide.push_back(min + 2); + wide.push_back(min / 2); + wide.push_back(min / 2 - 1); + + for (int k {4}; k < digits; k += (digits > 32 ? 3 : 1)) + { + const auto p {std::int64_t{1} << k}; + for (const auto x : {p - 1, p, p + 1}) + { + wide.push_back(x); + wide.push_back(-x); + } + } + + // floor(sqrt(2^digits)) and one more: the squares on either side of max and min + constexpr std::array roots {11, 181, 46340, INT64_C(3037000499)}; + const auto root {roots[sizeof(B) == 1U ? 0U : sizeof(B) == 2U ? 1U : sizeof(B) == 4U ? 2U : 3U]}; + for (const auto x : {root, root + 1}) + { + wide.push_back(x); + wide.push_back(-x); + } + + if constexpr (digits == 63) + { + // The 32-bit split of the 64-bit multiplication + for (const auto x : {INT64_C(0xFFFFFFFF), INT64_C(0x100000000), INT64_C(0x100000001), INT64_C(0x7FFFFFFF00000000)}) + { + wide.push_back(x); + wide.push_back(-x); + } + } + + std::vector res; + for (const auto x : wide) + { + res.push_back(static_cast(x)); + } + + return res; +} + +// Exhaustive for i8 at one width, the edges crossed with themselves plus seeded random +// pairs everywhere else +template +auto make_pairs() -> std::vector> +{ + std::vector> res; + + if constexpr (Exhaustive && sizeof(B) == 1U) + { + for (int i {-128}; i < 128; ++i) + { + for (int j {-128}; j < 128; ++j) + { + res.emplace_back(static_cast(i), static_cast(j)); + } + } + } + else + { + const auto edges {edge_values()}; + for (const auto x : edges) + { + for (const auto y : edges) + { + res.emplace_back(x, y); + } + } + + std::mt19937_64 gen {42U}; + std::uniform_int_distribution dist {std::numeric_limits::min(), std::numeric_limits::max()}; + std::uniform_int_distribution small {-3, 3}; + for (int i {}; i < 500; ++i) + { + res.emplace_back(static_cast(dist(gen)), static_cast(dist(gen))); + res.emplace_back(static_cast(dist(gen)), static_cast(small(gen))); + } + } + + return res; +} + +// The full input set for the primary forms at N = 4, and every seventh pair elsewhere, +// which keeps the run time down while every form and width sees every kind of lane mix +template +auto pairs_for_width() -> std::vector> +{ + constexpr auto full {Full && N == 4}; + auto pairs {make_pairs()}; + + if constexpr (full) + { + return pairs; + } + else + { + std::vector> res; + for (std::size_t i {}; i < pairs.size(); i += 7U) + { + res.push_back(pairs[i]); + } + + return res; + } +} + +// Chunks the pairs into vectors of N lanes, wrapping around for the last chunk +template +auto chunk(const std::vector>& pairs, const std::size_t first) + -> std::pair(N)>, std::array(N)>> +{ + std::array(N)> lhs {}; + std::array(N)> rhs {}; + + for (std::size_t i {}; i < static_cast(N); ++i) + { + const auto& p {pairs[(first + i) % pairs.size()]}; + lhs[i] = T{p.first}; + rhs[i] = T{p.second}; + } + + return {lhs, rhs}; +} + +// ------------------------------ +// Checks +// ------------------------------ + +// Compares one pair of vectors with the scalar loop over the same lanes +template +auto same_as_scalar(const Op op, const std::array& lhs, + const std::array& rhs) -> bool +{ + const auto scalar {capture([&] + { + std::vector res; + for (std::size_t i {}; i < N; ++i) + { + res.push_back(raw(op(lhs[i], rhs[i]))); + } + + return res; + })}; + + const auto vector {capture([&] + { + return lanes_of(op(simd::unchecked_load(lhs), simd::unchecked_load(rhs))); + })}; + + return scalar == vector; +} + +template +void check_op(const char* name, const Op op) +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + const auto pairs {pairs_for_width()}; + int failures {}; + + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + const auto chunked {chunk(pairs, first)}; + + if (!BOOST_TEST((same_as_scalar(op, chunked.first, chunked.second))) && ++failures > 5) + { + // LCOV_EXCL_START + BOOST_ERROR(name); + return; + // LCOV_EXCL_STOP + } + } +} + +template +void check_overflowing(const char* name, const Op op) +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + const auto pairs {pairs_for_width()}; + int failures {}; + + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + // Named references rather than structured bindings, which lambdas can capture + // only from Clang 16 + const auto chunked {chunk(pairs, first)}; + const auto& lhs {chunked.first}; + const auto& rhs {chunked.second}; + + const auto scalar {capture([&] + { + std::vector values; + std::vector flags; + for (std::size_t i {}; i < static_cast(N); ++i) + { + const auto r {op(lhs[i], rhs[i])}; + values.push_back(raw(r.first)); + flags.push_back(r.second ? 1 : 0); + } + + values.insert(values.end(), flags.begin(), flags.end()); + return values; + })}; + + const auto vector {capture([&] + { + const auto r {op(simd::unchecked_load(lhs), simd::unchecked_load(rhs))}; + auto values {lanes_of(r.first)}; + const auto flags {flags_of(r.second, N)}; + values.insert(values.end(), flags.begin(), flags.end()); + return values; + })}; + + if (!BOOST_TEST(scalar == vector) && ++failures > 5) + { + // LCOV_EXCL_START + BOOST_ERROR(name); + return; + // LCOV_EXCL_STOP + } + } +} + +template +void check_checked(const char* name, const Op op) +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + const auto pairs {pairs_for_width()}; + int failures {}; + + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + const auto chunked {chunk(pairs, first)}; + const auto& lhs {chunked.first}; + const auto& rhs {chunked.second}; + + // nullopt when any lane is nullopt, otherwise every lane + std::vector scalar; + bool scalar_empty {false}; + for (std::size_t i {}; i < static_cast(N); ++i) + { + const auto r {op(lhs[i], rhs[i])}; + if (!r.has_value()) + { + scalar_empty = true; + break; + } + + scalar.push_back(raw(*r)); + } + + const auto r {op(simd::unchecked_load(lhs), simd::unchecked_load(rhs))}; + const auto ok {scalar_empty ? !r.has_value() : (r.has_value() && lanes_of(*r) == scalar)}; + + if (!BOOST_TEST(ok) && ++failures > 5) + { + // LCOV_EXCL_START + BOOST_ERROR(name); + return; + // LCOV_EXCL_STOP + } + } +} + +// ------------------------------ +// Drivers +// ------------------------------ + +template +void test_operators() +{ + check_op("add", [](const auto& x, const auto& y) { return x + y; }); + check_op("sub", [](const auto& x, const auto& y) { return x - y; }); + check_op("mul", [](const auto& x, const auto& y) { return x * y; }); + check_op("div", [](const auto& x, const auto& y) { return x / y; }); + check_op("mod", [](const auto& x, const auto& y) { return x % y; }); +} + +template +void test_free_functions() +{ + check_op("saturating_add", [](const auto& x, const auto& y) { return saturating_add(x, y); }); + check_op("saturating_sub", [](const auto& x, const auto& y) { return saturating_sub(x, y); }); + check_op("saturating_mul", [](const auto& x, const auto& y) { return saturating_mul(x, y); }); + check_op("saturating_div", [](const auto& x, const auto& y) { return saturating_div(x, y); }); + check_op("saturating_mod", [](const auto& x, const auto& y) { return saturating_mod(x, y); }); + + check_overflowing("overflowing_add", [](const auto& x, const auto& y) { return overflowing_add(x, y); }); + check_overflowing("overflowing_sub", [](const auto& x, const auto& y) { return overflowing_sub(x, y); }); + check_overflowing("overflowing_mul", [](const auto& x, const auto& y) { return overflowing_mul(x, y); }); + check_overflowing("overflowing_div", [](const auto& x, const auto& y) { return overflowing_div(x, y); }); + check_overflowing("overflowing_mod", [](const auto& x, const auto& y) { return overflowing_mod(x, y); }); + + check_checked("checked_add", [](const auto& x, const auto& y) { return checked_add(x, y); }); + check_checked("checked_sub", [](const auto& x, const auto& y) { return checked_sub(x, y); }); + check_checked("checked_mul", [](const auto& x, const auto& y) { return checked_mul(x, y); }); + check_checked("checked_div", [](const auto& x, const auto& y) { return checked_div(x, y); }); + check_checked("checked_mod", [](const auto& x, const auto& y) { return checked_mod(x, y); }); + + // The generic forms route to the same families + check_op("add", [](const auto& x, const auto& y) { return add(x, y); }); + check_op("mul", [](const auto& x, const auto& y) { return mul(x, y); }); + check_overflowing("sub", [](const auto& x, const auto& y) { return sub(x, y); }); + check_checked("div", [](const auto& x, const auto& y) { return div(x, y); }); + check_op("mod", [](const auto& x, const auto& y) { return mod(x, y); }); + + if constexpr (sizeof(typename T::basis_type) < sizeof(std::int64_t)) + { + check_op("widening_add", [](const auto& x, const auto& y) { return widening_add(x, y); }); + check_op("widening_mul", [](const auto& x, const auto& y) { return widening_mul(x, y); }); + check_op("mul", [](const auto& x, const auto& y) { return mul(x, y); }); + } +} + +// min / -1 and min % -1 next to ordinary lanes and zero divisors, in every lane position. +// The cross product rarely puts them in a vector without a zero divisor. +template +void test_min_by_minus_one() +{ + using B = typename T::basis_type; + using V = simd::vec; + + constexpr auto min {std::numeric_limits::min()}; + const std::array, 4> fillers {{{static_cast(7), static_cast(2)}, + {static_cast(-9), static_cast(4)}, + {min, static_cast(1)}, + {static_cast(5), static_cast(0)}}}; + + const auto div_op {[](const auto& x, const auto& y) { return x / y; }}; + const auto mod_op {[](const auto& x, const auto& y) { return x % y; }}; + const auto sat_div {[](const auto& x, const auto& y) { return saturating_div(x, y); }}; + const auto sat_mod {[](const auto& x, const auto& y) { return saturating_mod(x, y); }}; + + // Lane `special` divides min by -1. Lane `zero` (when it is not `special`) divides by + // zero, so the error order between the two kinds is pinned in both directions. + for (int special {}; special < N; ++special) + { + for (int zero {-1}; zero < N; ++zero) + { + if (zero == special) + { + continue; + } + + std::array(N)> lhs {}; + std::array(N)> rhs {}; + for (int i {}; i < N; ++i) + { + const auto& f {fillers[static_cast(i) % 3U]}; + auto p {i == special ? std::pair{min, static_cast(-1)} : f}; + if (i == zero) + { + p = fillers[3]; + } + + lhs[static_cast(i)] = T{p.first}; + rhs[static_cast(i)] = T{p.second}; + } + + BOOST_TEST((same_as_scalar(div_op, lhs, rhs))); + BOOST_TEST((same_as_scalar(mod_op, lhs, rhs))); + BOOST_TEST((same_as_scalar(sat_div, lhs, rhs))); + BOOST_TEST((same_as_scalar(sat_mod, lhs, rhs))); + + const auto a {simd::unchecked_load(lhs)}; + const auto b {simd::unchecked_load(rhs)}; + + if (zero < 0) + { + // The branch free forms: the wrapped values min and 0, flagged in one lane + const auto [quotient, div_flags] {simd::overflowing_div(a, b)}; + const auto [remainder, mod_flags] {simd::overflowing_mod(a, b)}; + BOOST_TEST_EQ(reduce_count(div_flags), 1); + BOOST_TEST_EQ(reduce_min_index(div_flags), special); + BOOST_TEST_EQ(reduce_count(mod_flags), 1); + BOOST_TEST(quotient[special] == T{min}); + BOOST_TEST(remainder[special] == T{static_cast(0)}); + + for (int i {}; i < N; ++i) + { + if (i != special) + { + BOOST_TEST(quotient[i] == saturating_div(lhs[static_cast(i)], rhs[static_cast(i)])); + BOOST_TEST(remainder[i] == saturating_mod(lhs[static_cast(i)], rhs[static_cast(i)])); + } + } + + BOOST_TEST(!simd::checked_div(a, b).has_value()); + BOOST_TEST(!simd::checked_mod(a, b).has_value()); + } + else + { + BOOST_TEST_THROWS(static_cast(simd::overflowing_div(a, b)), std::domain_error); + BOOST_TEST_THROWS(static_cast(simd::overflowing_mod(a, b)), std::domain_error); + } + } + } +} + +// Unary minus, increment, and decrement around the limits, compared with the scalar types +template +void test_unary() +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + constexpr auto max {std::numeric_limits::max()}; + constexpr auto min {std::numeric_limits::min()}; + const std::array values {static_cast(0), static_cast(1), static_cast(-1), + static_cast(max - 1), max, min, + static_cast(min + 1), static_cast(max / 2)}; + + for (std::size_t start {}; start < values.size(); ++start) + { + std::array(N)> lanes {}; + for (std::size_t i {}; i < lanes.size(); ++i) + { + lanes[i] = T{values[(start + i) % values.size()]}; + } + + const auto negate {[](const auto& x) { return -x; }}; + const auto pre_inc {[](auto x) { ++x; return x; }}; + const auto post_inc {[](auto x) { static_cast(x++); return x; }}; + const auto pre_dec {[](auto x) { --x; return x; }}; + const auto post_dec {[](auto x) { static_cast(x--); return x; }}; + const auto unary_plus {[](const auto& x) { return +x; }}; + + const auto check {[&](const auto op) + { + const auto scalar {capture([&] + { + std::vector res; + for (const auto lane : lanes) + { + res.push_back(raw(op(lane))); + } + + return res; + })}; + + const auto vector {capture([&] { return lanes_of(op(simd::unchecked_load(lanes))); })}; + BOOST_TEST(scalar == vector); + }}; + + check(negate); + check(pre_inc); + check(post_inc); + check(pre_dec); + check(post_dec); + check(unary_plus); + } + + // Post increment and decrement return the old vector + const V start {T{static_cast(-5)}}; + auto v {start}; + BOOST_TEST(all_of(v++ == start)); + BOOST_TEST(all_of(v == V{T{static_cast(-4)}})); + BOOST_TEST(all_of(v-- == V{T{static_cast(-4)}})); + BOOST_TEST(all_of(v == start)); +} + +// Compound assignment and the unary operators leave the operand unchanged when they throw +template +void test_strong_guarantee() +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + const V top {T{std::numeric_limits::max()}}; + auto v {top}; + + BOOST_TEST_THROWS(v += V{T{static_cast(1)}}, std::overflow_error); + BOOST_TEST(all_of(v == top)); + + BOOST_TEST_THROWS(++v, std::overflow_error); + BOOST_TEST(all_of(v == top)); + + BOOST_TEST_THROWS(v /= V{}, std::domain_error); + BOOST_TEST(all_of(v == top)); + + const V bottom {T{std::numeric_limits::min()}}; + auto w {bottom}; + + BOOST_TEST_THROWS(w -= T{static_cast(1)}, std::underflow_error); + BOOST_TEST(all_of(w == bottom)); + + BOOST_TEST_THROWS(--w, std::underflow_error); + BOOST_TEST(all_of(w == bottom)); + + BOOST_TEST_THROWS(w *= T{static_cast(2)}, std::underflow_error); + BOOST_TEST(all_of(w == bottom)); + + BOOST_TEST_THROWS(w /= T{static_cast(-1)}, std::overflow_error); + BOOST_TEST(all_of(w == bottom)); + + BOOST_TEST_THROWS(w %= T{static_cast(-1)}, std::overflow_error); + BOOST_TEST(all_of(w == bottom)); + + BOOST_TEST_THROWS(static_cast(-w), std::domain_error); + + // Successful compound assignment, including the broadcast forms + auto x {V{T{static_cast(6)}}}; + x -= T{static_cast(10)}; + x *= V{T{static_cast(3)}}; + x %= T{static_cast(5)}; + x += T{static_cast(-1)}; + x /= T{static_cast(-3)}; + BOOST_TEST(all_of(x == V{T{static_cast(1)}})); + BOOST_TEST(all_of(-x == T{static_cast(-1)})); +} + +// Narrowing conversions throw std::domain_error for an out of range lane, whatever the policy +template +void test_conversion() +{ + using from_basis = typename From::basis_type; + using to_basis = typename To::basis_type; + + const auto pairs {make_pairs()}; + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + const auto lanes {chunk(pairs, first).first}; + + const auto scalar {capture([&] + { + std::vector res; + for (const auto lane : lanes) + { + res.push_back(raw(To{static_cast(lane)})); + } + + return res; + })}; + + const auto vector {capture([&] { return lanes_of(simd::vec{simd::unchecked_load>(lanes)}); })}; + BOOST_TEST(scalar == vector); + } +} + +// Selection, ordering, and reductions follow the signed order +template +void test_ordering() +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + constexpr auto min {std::numeric_limits::min()}; + const V v {[](const auto i) { return T{static_cast(static_cast(i) % 2 == 0 ? -static_cast(i) - 1 : static_cast(i))}; }}; + const V lowest {T{min}}; + + BOOST_TEST(all_of(lowest <= v)); + BOOST_TEST(none_of(v < lowest)); + BOOST_TEST(reduce_min(v) == T{static_cast(-((N - 1) / 2 * 2) - 1)}); + BOOST_TEST(reduce_max(v) == (N > 1 ? T{static_cast(N % 2 == 0 ? N - 1 : N - 2)} : T{static_cast(-1)})); + BOOST_TEST(all_of(simd::min(v, V{}) <= V{})); + BOOST_TEST(all_of(simd::max(v, V{}) >= V{})); + BOOST_TEST(all_of(simd::clamp(v, V{T{static_cast(-1)}}, V{T{static_cast(1)}}) >= T{static_cast(-1)})); + BOOST_TEST(all_of(simd::select(v < V{}, -v, v) >= V{})); + BOOST_TEST(simd::reduce(V{T{static_cast(-1)}}) == T{static_cast(-N)}); +} + +template +void test_width() +{ + using T = detail::signed_integer_basis; + using S = detail::signed_integer_basis; + using H = detail::signed_integer_basis; + + // The exhaustive i8 set runs on the forms that do not throw, where it is cheap; they + // share the error masks with the throwing forms + test_operators(); + test_operators(); + test_operators(); + + test_free_functions(); + + test_min_by_minus_one(); + test_min_by_minus_one(); + test_min_by_minus_one(); + + test_unary(); + test_unary(); + test_unary(); + + test_strong_guarantee(); + test_ordering(); +} + +template +void test_type() +{ + test_width(); + test_width(); + test_width(); + test_width>::size()>(); + test_width(); +} + +int main() +{ + test_type(); + test_type(); + test_type(); + test_type(); + + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + + return boost::report_errors(); +} diff --git a/test/test_simd_signed_array.cpp b/test/test_simd_signed_array.cpp new file mode 100644 index 00000000..0de67cda --- /dev/null +++ b/test/test_simd_signed_array.cpp @@ -0,0 +1,9 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Runs test_simd_signed.cpp on the portable std::array backend, which is otherwise +// not exercised wherever is available + +#define BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND +#include "test_simd_signed.cpp" diff --git a/test/test_simd_signed_constexpr.cpp b/test/test_simd_signed_constexpr.cpp new file mode 100644 index 00000000..894b7d29 --- /dev/null +++ b/test/test_simd_signed_constexpr.cpp @@ -0,0 +1,158 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec of signed elements is usable in constant expressions on both backends. The +// constant evaluator rejects undefined behavior, so the edge lanes (min, max, min / -1) +// also prove that no lane computation overflows a signed lane. + +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif + +#include + +#include +#include +#include + +using namespace boost::safe_numbers; + +// -2, -1, 0, ..., 13, then repeating, so every lane fits i8 at the native AVX-512 width +template +constexpr auto ramp() -> simd::vec +{ + using basis_type = typename T::basis_type; + return simd::vec{[](const auto i) { return T{static_cast(static_cast(i) % 16 - 2)}; }}; +} + +// even, odd, even, odd, ... +template +constexpr auto alternating(const typename T::basis_type even, const typename T::basis_type odd) -> simd::vec +{ + return simd::vec{[even, odd](const auto i) { return T{static_cast(i) % 2 == 0 ? even : odd}; }}; +} + +template +constexpr auto check() -> bool +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + using sat_type = detail::signed_integer_basis; + using S = simd::vec; + + constexpr auto max {std::numeric_limits::max()}; + constexpr auto min {std::numeric_limits::min()}; + constexpr auto zero {static_cast(0)}; + const auto a {ramp()}; + const V three {T{static_cast(3)}}; + const V minus_one {T{static_cast(-1)}}; + + const auto sum {a + three}; + const auto difference {sum - three}; + const auto product {a * three}; + const auto quotient {product / three}; + const auto remainder {(a + T{static_cast(10)}) % three}; + const auto negated {-(-a)}; + + // Saturation is a defined value, so it stays a constant expression + const auto edges {alternating(min, max)}; + const auto sat_edges {alternating(min, max)}; + const S sat_minus_one {minus_one}; + const auto saturated_sum {sat_edges + sat_minus_one}; + const auto saturated_negation {-sat_edges}; + const auto saturated_quotient {sat_edges / sat_minus_one}; + const auto saturated_remainder {sat_edges % sat_minus_one}; + + const auto [wrapped, flags] {simd::overflowing_add(V{T{max}}, V{T{static_cast(1)}})}; + const auto [wrapped_quotient, quotient_flags] {simd::overflowing_div(V{T{min}}, minus_one)}; + const auto [wrapped_product, product_flags] {simd::overflowing_mul(edges, edges)}; + + auto incremented {a}; + ++incremented; + + auto decremented {S{V{T{min}}}}; + --decremented; + + // The strict_* functions and the generic forms agree with the operators when no lane fails + const auto shifted {a + T{static_cast(10)}}; + const auto strict_ok {all_of(simd::strict_add(a, three) == sum) && + all_of(simd::strict_sub(sum, three) == a) && + all_of(simd::strict_mul(a, three) == product) && + all_of(simd::strict_div(product, three) == quotient) && + all_of(simd::strict_mod(shifted, three) == remainder) && + all_of(simd::add(a, three) == sum) && + all_of(simd::sub(sum, three) == a) && + all_of(simd::mul(a, three) == product) && + all_of(simd::div(product, three) == quotient) && + all_of(simd::mod(shifted, three) == remainder)}; + + // Widening forms are exact in lanes of twice the width + auto widened_ok {true}; + if constexpr (sizeof(basis_type) < sizeof(std::int64_t)) + { + using wide_basis = detail::signed_promoted_type; + using W = detail::signed_integer_basis; + + const auto wide_sum {simd::add(V{T{min}}, V{T{min}})}; + const auto wide_product {simd::mul(V{T{min}}, V{T{min}})}; + widened_ok = wide_sum[0] == W{static_cast(2 * static_cast(min))} && + wide_product[0] == W{static_cast(static_cast(min) * static_cast(min))}; + } + + return strict_ok && widened_ok && + all_of(difference == a) && + all_of(quotient == a) && + all_of(negated == a) && + all_of(remainder >= V{}) && + all_of(saturated_sum == alternating(min, static_cast(max - 1))) && + all_of(saturated_negation == alternating(max, static_cast(-max))) && + all_of(saturated_quotient == alternating(max, static_cast(-max))) && + all_of(saturated_remainder == S{}) && + all_of(flags) && + all_of(wrapped == V{T{min}}) && + all_of(quotient_flags) && + all_of(wrapped_quotient == V{T{min}}) && + all_of(product_flags) && + all_of(wrapped_product == alternating(zero, static_cast(1))) && + all_of(decremented == S{V{T{min}}}) && + !simd::checked_mul(V{T{max}}, three).has_value() && + !simd::checked_div(V{T{min}}, minus_one).has_value() && + all_of(incremented == a + T{static_cast(1)}) && + none_of(a > a) && + reduce_count(a < V{}) == N / 16 * 2 + (N % 16 < 2 ? N % 16 : 2) && + simd::reduce_min(a) == T{static_cast(-2)} && + (N > 16 || simd::reduce(a) == T{static_cast(N * (N - 1) / 2 - 2 * N)}) && + static_cast(N)>>(a)[0] == static_cast(-2); +} + +template +constexpr auto check_widths() -> bool +{ + return check() && check() && check() && check() && check::size()>(); +} + +static_assert(check_widths()); +static_assert(check_widths()); +static_assert(check_widths()); +static_assert(check_widths()); + +// The 64-bit magnitude split in a constant expression: min * 1 and -1 * -max fit, +// min * -1, min * min, and 2^32 * 2^31 do not +constexpr auto i64_min {std::numeric_limits::min()}; +constexpr auto i64_max {std::numeric_limits::max()}; + +static_assert(none_of(simd::overflowing_mul(simd::vec{i64{i64_min}}, simd::vec{i64{1}}).second)); +static_assert(none_of(simd::overflowing_mul(simd::vec{i64{-1}}, simd::vec{i64{-i64_max}}).second)); +static_assert(none_of(simd::overflowing_mul(simd::vec{i64{INT64_C(-0x100000000)}}, simd::vec{i64{INT64_C(0x80000000)}}).second)); +static_assert(all_of(simd::overflowing_mul(simd::vec{i64{i64_min}}, simd::vec{i64{-1}}).second)); +static_assert(all_of(simd::overflowing_mul(simd::vec{i64{i64_min}}, simd::vec{i64{i64_min}}).second)); +static_assert(all_of(simd::overflowing_mul(simd::vec{i64{INT64_C(0x100000000)}}, simd::vec{i64{INT64_C(0x80000000)}}).second)); +static_assert(simd::overflowing_mul(simd::vec{i64{i64_min}}, simd::vec{i64{0}}).first[1] == i64{0}); + +int main() +{ + return 0; +} diff --git a/test/test_simd_signed_constexpr_array.cpp b/test/test_simd_signed_constexpr_array.cpp new file mode 100644 index 00000000..7d4f3da2 --- /dev/null +++ b/test/test_simd_signed_constexpr_array.cpp @@ -0,0 +1,9 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Runs test_simd_signed_constexpr.cpp on the portable std::array backend, which is +// otherwise not exercised wherever is available + +#define BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND +#include "test_simd_signed_constexpr.cpp" diff --git a/test/test_simd_signed_strict.cpp b/test/test_simd_signed_strict.cpp new file mode 100644 index 00000000..a1b03528 --- /dev/null +++ b/test/test_simd_signed_strict.cpp @@ -0,0 +1,29 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// A strict element type calls std::exit(EXIT_FAILURE) when any lane divides min by -1. +// It is marked as run-fail in the Jamfile. + +#include +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec lhs {[](const auto i) + { + return strict_i32{i == 2 ? std::numeric_limits::min() : static_cast(i)}; + }}; + + const simd::vec rhs {strict_i32{-1}}; + + // This should call std::exit(EXIT_FAILURE) + const auto res {lhs / rhs}; + + // Should never reach here + static_cast(res); + return 0; // LCOV_EXCL_LINE +} diff --git a/test/test_simd_strict.cpp b/test/test_simd_strict.cpp new file mode 100644 index 00000000..86424531 --- /dev/null +++ b/test/test_simd_strict.cpp @@ -0,0 +1,29 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// A strict element type calls std::exit(EXIT_FAILURE) when any lane overflows. +// It is marked as run-fail in the Jamfile. + +#include +#include +#include + +using namespace boost::safe_numbers; + +int main() +{ + const simd::vec lhs {[](const auto i) + { + return strict_u32{i == 2 ? std::numeric_limits::max() : static_cast(i)}; + }}; + + const simd::vec rhs {strict_u32{1U}}; + + // This should call std::exit(EXIT_FAILURE) + const auto res {lhs + rhs}; + + // Should never reach here + static_cast(res); + return 0; // LCOV_EXCL_LINE +} diff --git a/test/test_simd_u64_mul.cpp b/test/test_simd_u64_mul.cpp new file mode 100644 index 00000000..e1c76e49 --- /dev/null +++ b/test/test_simd_u64_mul.cpp @@ -0,0 +1,139 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// The 64-bit lane multiplication has no 128-bit lane to widen into, so it splits each +// operand into 32-bit halves. This checks the overflow mask lane by lane against the +// scalar overflowing_mul on the cases that exercise each term of the split. + +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace boost::safe_numbers; + +template +void check_pairs(const std::vector>& pairs) +{ + using V = simd::vec; + using S = simd::vec; + + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + std::array(N)> lhs {}; + std::array(N)> rhs {}; + bool any_overflow {false}; + + for (std::size_t i {}; i < lhs.size(); ++i) + { + const auto& p {pairs[(first + i) % pairs.size()]}; + lhs[i] = u64{p.first}; + rhs[i] = u64{p.second}; + } + + const auto va {simd::unchecked_load(lhs)}; + const auto vb {simd::unchecked_load(rhs)}; + const auto [value, flags] {simd::overflowing_mul(va, vb)}; + const auto saturated {S{va} * S{vb}}; + + for (std::size_t i {}; i < lhs.size(); ++i) + { + const auto lane {static_cast(i)}; + const auto [expected, overflowed] {overflowing_mul(lhs[i], rhs[i])}; + any_overflow = any_overflow || overflowed; + + BOOST_TEST(flags[lane] == overflowed); + BOOST_TEST(value[lane] == expected); + BOOST_TEST(saturated[lane] == saturating_mul(sat_u64{static_cast(lhs[i])}, sat_u64{static_cast(rhs[i])})); + } + + if (any_overflow) + { + BOOST_TEST_THROWS(static_cast(va * vb), std::overflow_error); + BOOST_TEST(!simd::checked_mul(va, vb).has_value()); + } + else + { + BOOST_TEST(all_of((va * vb) == value)); + BOOST_TEST(simd::checked_mul(va, vb).has_value()); + } + } +} + +auto make_pairs() -> std::vector> +{ + std::vector> res; + + // Every combination of interesting high and low halves + constexpr std::array halves {0U, 1U, 2U, 0x7FFFFFFFU, 0x80000000U, 0xFFFFFFFEU, 0xFFFFFFFFU}; + std::vector values; + for (const auto hi : halves) + { + for (const auto lo : halves) + { + values.push_back((hi << 32U) | lo); + } + } + + for (const auto x : values) + { + for (const auto y : values) + { + res.emplace_back(x, y); + } + } + + // Exactly at the boundary: x * (max / x) fits and x * (max / x + 1) does not. + // These reach the final carry term of the split. + constexpr auto max {std::numeric_limits::max()}; + std::mt19937_64 gen {1234U}; + for (int i {}; i < 4000; ++i) + { + const auto x {gen() >> (gen() % 64U)}; + if (x < 2U) + { + continue; + } + + const auto y {max / x}; + res.emplace_back(x, y); + res.emplace_back(y + 1U, x); + } + + // Both high halves zero but the cross term overflows, and plain random pairs + for (int i {}; i < 2000; ++i) + { + res.emplace_back(gen() & 0xFFFFFFFFU, gen()); + res.emplace_back(gen(), gen() >> 31U); + res.emplace_back(gen(), gen()); + } + + return res; +} + +int main() +{ + const auto pairs {make_pairs()}; + + check_pairs<1>(pairs); + check_pairs<2>(pairs); + check_pairs<3>(pairs); + check_pairs<4>(pairs); + check_pairs<8>(pairs); + + return boost::report_errors(); +} diff --git a/test/test_simd_u64_mul_array.cpp b/test/test_simd_u64_mul_array.cpp new file mode 100644 index 00000000..f2c57a23 --- /dev/null +++ b/test/test_simd_u64_mul_array.cpp @@ -0,0 +1,9 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Runs test_simd_u64_mul.cpp on the portable std::array backend, which is otherwise +// not exercised wherever is available + +#define BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND +#include "test_simd_u64_mul.cpp" diff --git a/test/test_simd_unsigned.cpp b/test/test_simd_unsigned.cpp new file mode 100644 index 00000000..7d82dd26 --- /dev/null +++ b/test/test_simd_unsigned.cpp @@ -0,0 +1,669 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Differential test of simd::vec against the scalar library. For every policy, lane i +// of a vector operation must equal the scalar operation on lane i, and an error must +// be reported exactly as the scalar loop over i = 0 ... N - 1 reports it: the same +// exception type and message, or the same sequence of user handler calls. + +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace boost::safe_numbers; + +// ------------------------------ +// Handler that records every call +// ------------------------------ + +struct handler_call +{ + error_kind kind; + std::uint64_t value; + std::string message; + + friend auto operator==(const handler_call&, const handler_call&) -> bool = default; +}; + +inline std::vector& handler_log() +{ + static std::vector log; + return log; +} + +// Logs the call and returns a value that differs from the fallback, so a lane patched +// by the handler can not be mistaken for the wrapped result +struct recording_handler +{ + template + auto on_error(const error_kind kind, const T value, const char* msg) const -> T + { + handler_log().push_back(handler_call{kind, static_cast(value), msg}); + return static_cast(value ^ static_cast(0x5AU)); + } +}; + +// ------------------------------ +// Outcome capture +// ------------------------------ + +struct outcome +{ + int exception {0}; + std::string message; + std::vector lanes; + std::vector calls; + + friend auto operator==(const outcome&, const outcome&) -> bool = default; +}; + +template +auto capture(F f) -> outcome +{ + outcome res; + handler_log().clear(); + + try + { + res.lanes = f(); + } + catch (const std::overflow_error& e) + { + res.exception = 1; + res.message = e.what(); + } + catch (const std::underflow_error& e) + { + res.exception = 2; + res.message = e.what(); + } + catch (const std::domain_error& e) + { + res.exception = 3; + res.message = e.what(); + } + + res.calls = handler_log(); + return res; +} + +template +auto raw(const T x) -> std::uint64_t +{ + return static_cast(static_cast(x)); +} + +template +auto lanes_of(const simd::vec& v) -> std::vector +{ + std::vector res; + for (int i {}; i < N; ++i) + { + res.push_back(raw(v[i])); + } + + return res; +} + +template +auto flags_of(const M& m, const int n) -> std::vector +{ + std::vector res; + for (int i {}; i < n; ++i) + { + res.push_back(m[i] ? 1U : 0U); + } + + return res; +} + +// ------------------------------ +// Inputs +// ------------------------------ + +template +auto edge_values() -> std::vector +{ + constexpr auto max {std::numeric_limits::max()}; + constexpr auto digits {std::numeric_limits::digits}; + + std::vector res; + + // Shift counts around the width, then the arithmetic edges + for (int i {}; i <= digits + 2; ++i) + { + res.push_back(static_cast(i)); + } + + res.push_back(static_cast(max / 2U)); + res.push_back(static_cast(max / 2U + 1U)); + res.push_back(static_cast(max - 1U)); + res.push_back(max); + + for (int k {4}; k < digits; k += (digits > 32 ? 3 : 1)) + { + const auto p {static_cast(static_cast(1U) << k)}; + res.push_back(static_cast(p - 1U)); + res.push_back(p); + res.push_back(static_cast(p + 1U)); + } + + if constexpr (digits == 64) + { + // The 32-bit split of the 64-bit multiplication + res.push_back(UINT64_C(0xFFFFFFFF)); + res.push_back(UINT64_C(0x100000000)); + res.push_back(UINT64_C(0x100000001)); + res.push_back(UINT64_C(0xFFFFFFFF00000000)); + res.push_back(UINT64_C(0x00000001FFFFFFFF)); + } + + return res; +} + +// Exhaustive for u8 at one width, the edges crossed with themselves plus seeded random +// pairs everywhere else +template +auto make_pairs() -> std::vector> +{ + std::vector> res; + + if constexpr (Exhaustive && sizeof(B) == 1U) + { + for (unsigned i {}; i < 256U; ++i) + { + for (unsigned j {}; j < 256U; ++j) + { + res.emplace_back(static_cast(i), static_cast(j)); + } + } + } + else + { + const auto edges {edge_values()}; + for (const auto x : edges) + { + for (const auto y : edges) + { + res.emplace_back(x, y); + } + } + + std::mt19937_64 gen {42U}; + std::uniform_int_distribution dist {0U, std::numeric_limits::max()}; + std::uniform_int_distribution small {0, std::numeric_limits::digits + 1}; + for (int i {}; i < 500; ++i) + { + res.emplace_back(static_cast(dist(gen)), static_cast(dist(gen))); + res.emplace_back(static_cast(dist(gen)), static_cast(small(gen))); + } + } + + return res; +} + +// The full input set for the primary forms at N = 4, and every seventh pair elsewhere, +// which keeps the run time down while every form and width sees every kind of lane mix +template +auto pairs_for_width() -> std::vector> +{ + constexpr auto full {Full && N == 4}; + auto pairs {make_pairs()}; + + if constexpr (full) + { + return pairs; + } + else + { + std::vector> res; + for (std::size_t i {}; i < pairs.size(); i += 7U) + { + res.push_back(pairs[i]); + } + + return res; + } +} + +// Chunks the pairs into vectors of N lanes, wrapping around for the last chunk +template +auto chunk(const std::vector>& pairs, const std::size_t first) + -> std::pair(N)>, std::array(N)>> +{ + std::array(N)> lhs {}; + std::array(N)> rhs {}; + + for (std::size_t i {}; i < static_cast(N); ++i) + { + const auto& p {pairs[(first + i) % pairs.size()]}; + lhs[i] = T{p.first}; + rhs[i] = T{p.second}; + } + + return {lhs, rhs}; +} + +// ------------------------------ +// Checks +// ------------------------------ + +template +void check_op(const char* name, const Op op) +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + const auto pairs {pairs_for_width()}; + int failures {}; + + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + // Named references rather than structured bindings, which lambdas can capture + // only from Clang 16 + const auto chunked {chunk(pairs, first)}; + const auto& lhs {chunked.first}; + const auto& rhs {chunked.second}; + + const auto scalar {capture([&] + { + std::vector res; + for (std::size_t i {}; i < static_cast(N); ++i) + { + res.push_back(raw(op(lhs[i], rhs[i]))); + } + + return res; + })}; + + const auto vector {capture([&] + { + return lanes_of(op(simd::unchecked_load(lhs), simd::unchecked_load(rhs))); + })}; + + if (!BOOST_TEST(scalar == vector) && ++failures > 5) + { + // LCOV_EXCL_START + BOOST_ERROR(name); + return; + // LCOV_EXCL_STOP + } + } +} + +template +void check_overflowing(const char* name, const Op op) +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + const auto pairs {pairs_for_width()}; + int failures {}; + + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + // Named references rather than structured bindings, which lambdas can capture + // only from Clang 16 + const auto chunked {chunk(pairs, first)}; + const auto& lhs {chunked.first}; + const auto& rhs {chunked.second}; + + const auto scalar {capture([&] + { + std::vector values; + std::vector flags; + for (std::size_t i {}; i < static_cast(N); ++i) + { + const auto r {op(lhs[i], rhs[i])}; + values.push_back(raw(r.first)); + flags.push_back(r.second ? 1U : 0U); + } + + values.insert(values.end(), flags.begin(), flags.end()); + return values; + })}; + + const auto vector {capture([&] + { + const auto r {op(simd::unchecked_load(lhs), simd::unchecked_load(rhs))}; + auto values {lanes_of(r.first)}; + const auto flags {flags_of(r.second, N)}; + values.insert(values.end(), flags.begin(), flags.end()); + return values; + })}; + + if (!BOOST_TEST(scalar == vector) && ++failures > 5) + { + // LCOV_EXCL_START + BOOST_ERROR(name); + return; + // LCOV_EXCL_STOP + } + } +} + +template +void check_checked(const char* name, const Op op) +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + const auto pairs {pairs_for_width()}; + int failures {}; + + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + // Named references rather than structured bindings, which lambdas can capture + // only from Clang 16 + const auto chunked {chunk(pairs, first)}; + const auto& lhs {chunked.first}; + const auto& rhs {chunked.second}; + + // nullopt when any lane is nullopt, otherwise every lane + std::vector scalar; + bool scalar_empty {false}; + for (std::size_t i {}; i < static_cast(N); ++i) + { + const auto r {op(lhs[i], rhs[i])}; + if (!r.has_value()) + { + scalar_empty = true; + break; + } + + scalar.push_back(raw(*r)); + } + + const auto r {op(simd::unchecked_load(lhs), simd::unchecked_load(rhs))}; + const auto ok {scalar_empty ? !r.has_value() : (r.has_value() && lanes_of(*r) == scalar)}; + + if (!BOOST_TEST(ok) && ++failures > 5) + { + // LCOV_EXCL_START + BOOST_ERROR(name); + return; + // LCOV_EXCL_STOP + } + } +} + +// ------------------------------ +// Drivers +// ------------------------------ + +template +void test_operators() +{ + check_op("add", [](const auto& x, const auto& y) { return x + y; }); + check_op("sub", [](const auto& x, const auto& y) { return x - y; }); + check_op("mul", [](const auto& x, const auto& y) { return x * y; }); + check_op("div", [](const auto& x, const auto& y) { return x / y; }); + check_op("mod", [](const auto& x, const auto& y) { return x % y; }); + check_op("shl", [](const auto& x, const auto& y) { return x << y; }); + check_op("shr", [](const auto& x, const auto& y) { return x >> y; }); + check_op("and", [](const auto& x, const auto& y) { return x & y; }); + check_op("or", [](const auto& x, const auto& y) { return x | y; }); + check_op("xor", [](const auto& x, const auto& y) { return x ^ y; }); +} + +template +void test_free_functions() +{ + check_op("saturating_add", [](const auto& x, const auto& y) { return saturating_add(x, y); }); + check_op("saturating_sub", [](const auto& x, const auto& y) { return saturating_sub(x, y); }); + check_op("saturating_mul", [](const auto& x, const auto& y) { return saturating_mul(x, y); }); + check_op("saturating_div", [](const auto& x, const auto& y) { return saturating_div(x, y); }); + check_op("saturating_mod", [](const auto& x, const auto& y) { return saturating_mod(x, y); }); + check_op("saturating_shl", [](const auto& x, const auto& y) { return saturating_shl(x, y); }); + check_op("saturating_shr", [](const auto& x, const auto& y) { return saturating_shr(x, y); }); + + check_overflowing("overflowing_add", [](const auto& x, const auto& y) { return overflowing_add(x, y); }); + check_overflowing("overflowing_sub", [](const auto& x, const auto& y) { return overflowing_sub(x, y); }); + check_overflowing("overflowing_mul", [](const auto& x, const auto& y) { return overflowing_mul(x, y); }); + check_overflowing("overflowing_div", [](const auto& x, const auto& y) { return overflowing_div(x, y); }); + check_overflowing("overflowing_mod", [](const auto& x, const auto& y) { return overflowing_mod(x, y); }); + check_overflowing("overflowing_shl", [](const auto& x, const auto& y) { return overflowing_shl(x, y); }); + check_overflowing("overflowing_shr", [](const auto& x, const auto& y) { return overflowing_shr(x, y); }); + + check_checked("checked_add", [](const auto& x, const auto& y) { return checked_add(x, y); }); + check_checked("checked_sub", [](const auto& x, const auto& y) { return checked_sub(x, y); }); + check_checked("checked_mul", [](const auto& x, const auto& y) { return checked_mul(x, y); }); + check_checked("checked_div", [](const auto& x, const auto& y) { return checked_div(x, y); }); + check_checked("checked_mod", [](const auto& x, const auto& y) { return checked_mod(x, y); }); + check_checked("checked_shl", [](const auto& x, const auto& y) { return checked_shl(x, y); }); + check_checked("checked_shr", [](const auto& x, const auto& y) { return checked_shr(x, y); }); + + // The generic forms route to the same families + check_op("add", [](const auto& x, const auto& y) { return add(x, y); }); + check_op("mul", [](const auto& x, const auto& y) { return mul(x, y); }); + check_overflowing("sub", [](const auto& x, const auto& y) { return sub(x, y); }); + check_checked("div", [](const auto& x, const auto& y) { return div(x, y); }); +} + +// Increment and decrement around the limits, compared with the scalar ++ and -- +template +void test_inc_dec() +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + constexpr auto max {std::numeric_limits::max()}; + const std::array values {0U, 1U, 2U, static_cast(max - 1U), max, static_cast(max / 2U)}; + + for (std::size_t start {}; start < values.size(); ++start) + { + std::array(N)> lanes {}; + for (std::size_t i {}; i < lanes.size(); ++i) + { + lanes[i] = T{values[(start + i) % values.size()]}; + } + + const auto pre_inc {[](auto x) { ++x; return x; }}; + const auto post_inc {[](auto x) { static_cast(x++); return x; }}; + const auto pre_dec {[](auto x) { --x; return x; }}; + const auto post_dec {[](auto x) { static_cast(x--); return x; }}; + + const auto check {[&](const auto op) + { + const auto scalar {capture([&] + { + std::vector res; + for (const auto lane : lanes) + { + res.push_back(raw(op(lane))); + } + + return res; + })}; + + const auto vector {capture([&] { return lanes_of(op(simd::unchecked_load(lanes))); })}; + BOOST_TEST(scalar == vector); + }}; + + check(pre_inc); + check(post_inc); + check(pre_dec); + check(post_dec); + } + + // Post increment and decrement return the old vector + const V start {T{static_cast(5U)}}; + auto v {start}; + BOOST_TEST(all_of(v++ == start)); + BOOST_TEST(all_of(v == V{T{static_cast(6U)}})); + BOOST_TEST(all_of(v-- == V{T{static_cast(6U)}})); + BOOST_TEST(all_of(v == start)); +} + +// Compound assignment leaves the operand unchanged when it throws +template +void test_strong_guarantee() +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + + const V original {T{std::numeric_limits::max()}}; + auto v {original}; + + BOOST_TEST_THROWS(v += V{T{static_cast(1U)}}, std::overflow_error); + BOOST_TEST(all_of(v == original)); + + BOOST_TEST_THROWS(++v, std::overflow_error); + BOOST_TEST(all_of(v == original)); + + BOOST_TEST_THROWS(v /= V{}, std::domain_error); + BOOST_TEST(all_of(v == original)); + + // Successful compound assignment, including the broadcast forms + auto w {V{T{static_cast(6U)}}}; + w -= T{static_cast(2U)}; + w *= V{T{static_cast(3U)}}; + w %= T{static_cast(7U)}; + w <<= T{static_cast(1U)}; + w >>= T{static_cast(1U)}; + w |= T{static_cast(8U)}; + w &= T{static_cast(12U)}; + w ^= T{static_cast(4U)}; + BOOST_TEST(all_of(w == V{T{static_cast(8U)}})); +} + +// Shift counts so large that bit_width(lhs) + count would wrap: every lane is an error, +// and a handler receives the wrapped value lhs << (count % digits) +template +void test_large_shift_counts() +{ + using T = detail::unsigned_integer_basis; + using S = detail::unsigned_integer_basis; + using H = detail::unsigned_integer_basis; + constexpr int N {4}; + + constexpr auto max {std::numeric_limits::max()}; + const simd::vec lhs {[](const auto i) { return T{static_cast(static_cast(i) + 1U)}; }}; + const simd::vec rhs {T{max}}; + + BOOST_TEST_THROWS(static_cast(lhs << rhs), std::overflow_error); + + const auto [value, flags] {simd::overflowing_shl(lhs, rhs)}; + BOOST_TEST(all_of(flags)); + BOOST_TEST(all_of(value == simd::vec{})); + + BOOST_TEST(!simd::checked_shl(lhs, rhs).has_value()); + BOOST_TEST(all_of(simd::saturating_shl(lhs, rhs) == simd::vec{T{max}})); + + const simd::vec sat_lhs {lhs}; + BOOST_TEST(all_of((sat_lhs << simd::vec{S{max}}) == simd::vec{S{max}})); + + handler_log().clear(); + const simd::vec handler_lhs {lhs}; + const auto patched {handler_lhs << simd::vec{H{max}}}; + BOOST_TEST_EQ(handler_log().size(), static_cast(N)); + + constexpr auto digits {static_cast(std::numeric_limits::digits)}; + for (int i {}; i < N; ++i) + { + const auto wrapped {static_cast(static_cast(i + 1) << (max % digits))}; + BOOST_TEST(handler_log()[static_cast(i)].kind == error_kind::overflow); + BOOST_TEST_EQ(handler_log()[static_cast(i)].value, static_cast(wrapped)); + BOOST_TEST(patched[i] == H{static_cast(wrapped ^ static_cast(0x5AU))}); + } +} + +// Narrowing conversions throw std::domain_error for an out of range lane, whatever the policy +template +void test_conversion() +{ + using from_basis = typename From::basis_type; + using to_basis = typename To::basis_type; + + const auto pairs {make_pairs()}; + for (std::size_t first {}; first < pairs.size(); first += static_cast(N)) + { + const auto lanes {chunk(pairs, first).first}; + + const auto scalar {capture([&] + { + std::vector res; + for (const auto lane : lanes) + { + res.push_back(raw(To{static_cast(lane)})); + } + + return res; + })}; + + const auto vector {capture([&] { return lanes_of(simd::vec{simd::unchecked_load>(lanes)}); })}; + BOOST_TEST(scalar == vector); + } +} + +template +void test_width() +{ + using T = detail::unsigned_integer_basis; + using S = detail::unsigned_integer_basis; + using H = detail::unsigned_integer_basis; + + // The exhaustive u8 set runs on the forms that do not throw, where it is cheap; they + // share the error masks with the throwing forms + test_operators(); + test_operators(); + test_operators(); + + test_free_functions(); + + test_inc_dec(); + test_inc_dec(); + test_inc_dec(); + + test_strong_guarantee(); +} + +template +void test_type() +{ + test_width(); + test_width(); + test_width(); + test_width>::size()>(); + test_width(); +} + +int main() +{ + test_type(); + test_type(); + test_type(); + test_type(); + + test_large_shift_counts(); + test_large_shift_counts(); + + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + test_conversion(); + + return boost::report_errors(); +} diff --git a/test/test_simd_unsigned_array.cpp b/test/test_simd_unsigned_array.cpp new file mode 100644 index 00000000..2b076a2f --- /dev/null +++ b/test/test_simd_unsigned_array.cpp @@ -0,0 +1,9 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Runs test_simd_unsigned.cpp on the portable std::array backend, which is otherwise +// not exercised wherever is available + +#define BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND +#include "test_simd_unsigned.cpp" diff --git a/test/test_simd_unsigned_constexpr.cpp b/test/test_simd_unsigned_constexpr.cpp new file mode 100644 index 00000000..e87c539f --- /dev/null +++ b/test/test_simd_unsigned_constexpr.cpp @@ -0,0 +1,89 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// simd::vec arithmetic and comparisons are usable in constant expressions on both backends + +// GCC 16's returns 32-byte vectors from internal helpers when AVX is not enabled, +// which -Wpsabi reports at the end of the translation unit even for plain std::simd code +#if defined(__GNUC__) && !defined(__clang__) +# pragma GCC diagnostic ignored "-Wpsabi" +#endif + +#include + +#include +#include +#include + +using namespace boost::safe_numbers; + +template +constexpr auto ramp() -> simd::vec +{ + using basis_type = typename T::basis_type; + // 1, 2, ..., 16, then repeating, so every lane fits u8 at the native AVX-512 width + return simd::vec{[](const auto i) { return T{static_cast(static_cast(i) % 16 + 1)}; }}; +} + +template +constexpr auto check() -> bool +{ + using basis_type = typename T::basis_type; + using V = simd::vec; + using S = simd::vec, N>; + + constexpr auto max {std::numeric_limits::max()}; + const auto a {ramp()}; + const V two {T{static_cast(2U)}}; + + const auto sum {a + two}; + const auto difference {sum - two}; + const auto product {a * two}; + const auto quotient {product / two}; + const auto remainder {a % two}; + const auto shifted {(a << T{static_cast(1U)}) >> T{static_cast(1U)}}; + + // Saturation is a defined value, so it stays a constant expression + const auto saturated {S{V{T{max}}} + S{two}}; + + const auto [wrapped, flags] {simd::overflowing_add(V{T{max}}, two)}; + + auto incremented {a}; + ++incremented; + + return all_of(difference == a) && + all_of(quotient == a) && + all_of(shifted == a) && + all_of(remainder < two) && + all_of(saturated == S{V{T{max}}}) && + all_of(flags) && + all_of(wrapped == V{T{static_cast(1U)}}) && + !simd::checked_mul(V{T{max}}, two).has_value() && + all_of(incremented == a + T{static_cast(1U)}) && + none_of(a > a) && + reduce_count(a == T{static_cast(1U)}) == (N + 15) / 16 && + (N > 16 || simd::reduce(a) == T{static_cast(N * (N + 1) / 2)}) && + simd::reduce_max(a) == T{static_cast(N < 16 ? N : 16)} && + static_cast(N)>>(a)[0] == 1U; +} + +template +constexpr auto check_widths() -> bool +{ + return check() && check() && check() && check() && check::size()>(); +} + +static_assert(check_widths()); +static_assert(check_widths()); +static_assert(check_widths()); +static_assert(check_widths()); + +// The 64-bit split multiplication in a constant expression +static_assert(none_of(simd::overflowing_mul(simd::vec{u64{UINT64_C(0xFFFFFFFF)}}, simd::vec{u64{UINT64_C(0x100000001)}}).second)); +static_assert(all_of(simd::overflowing_mul(simd::vec{u64{UINT64_C(0x100000000)}}, simd::vec{u64{UINT64_C(0x100000000)}}).second)); + +int main() +{ + return 0; +} diff --git a/test/test_simd_unsigned_constexpr_array.cpp b/test/test_simd_unsigned_constexpr_array.cpp new file mode 100644 index 00000000..940296ae --- /dev/null +++ b/test/test_simd_unsigned_constexpr_array.cpp @@ -0,0 +1,9 @@ +// Copyright 2026 Matt Borland +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +// Runs test_simd_unsigned_constexpr.cpp on the portable std::array backend, which is otherwise +// not exercised wherever is available + +#define BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND +#include "test_simd_unsigned_constexpr.cpp" diff --git a/test/test_unsigned_bitwise_ops.cpp b/test/test_unsigned_bitwise_ops.cpp index 1bf3cead..e77e24a0 100644 --- a/test/test_unsigned_bitwise_ops.cpp +++ b/test/test_unsigned_bitwise_ops.cpp @@ -243,6 +243,37 @@ void test_left_shift_failure() BOOST_TEST_THROWS(T{high_bit} << T{1}, std::overflow_error); } +// ============================================= +// Left Shift (<<) - Counts near the maximum +// ============================================= + +// bit_width(lhs) + rhs used to wrap for counts within digits of the maximum, which let +// an out of range (undefined) shift through without an error. Every one is an error. +template +void test_left_shift_huge_count() +{ + using basis_type = detail::underlying_type_t; + constexpr auto max {std::numeric_limits::max()}; + constexpr auto digits {static_cast(std::numeric_limits::digits)}; + + const basis_type lhs_values[] {static_cast(1U), static_cast(max / 2U), max}; + const basis_type rhs_values[] {max, static_cast(max - 1U), static_cast(max - digits + 1U)}; + + for (const auto lhs : lhs_values) + { + for (const auto rhs : rhs_values) + { + BOOST_TEST_THROWS(T{lhs} << T{rhs}, std::overflow_error); + BOOST_TEST(T{max} == saturating_shl(T{lhs}, T{rhs})); + BOOST_TEST(!checked_shl(T{lhs}, T{rhs}).has_value()); + + const auto res {overflowing_shl(T{lhs}, T{rhs})}; + BOOST_TEST(res.second); + BOOST_TEST(T{static_cast(0U)} == res.first); + } + } +} + // ============================================= // Right Shift (>>) - Success // ============================================= @@ -989,6 +1020,12 @@ int main() test_left_shift_failure(); test_left_shift_failure_u128(); + test_left_shift_huge_count(); + test_left_shift_huge_count(); + test_left_shift_huge_count(); + test_left_shift_huge_count(); + test_left_shift_huge_count(); + // Right shift - success test_right_shift_success(); test_right_shift_success();