Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/amalgamate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,14 @@ jobs:
steps:
- uses: actions/checkout@v6

# Boost.Int128 is inlined into the single header since no Boost release before 1.93 ships it.
# Its develop branch is used because that is what safe_numbers develop is tested against.
# It is cloned outside deps/ so the smoke test proves the header does not need it on the include path.
- name: Fetch Boost.Int128
run: git clone --depth 1 --branch develop --quiet https://github.com/boostorg/int128.git "${RUNNER_TEMP}/int128"

- name: Regenerate the single header
run: python3 extra/amalgamate.py
run: python3 extra/amalgamate.py --int128-include "${RUNNER_TEMP}/int128/include"

# The single header still needs these Boost libraries, as on Compiler Explorer.
# Released (master) versions are used so the smoke test matches what users get.
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ jobs:
name: Run Boost.CI
uses: boostorg/boost-ci/.github/workflows/reusable.yml@master
with:
timeout: 180 # Minutes per job (Boost.CI default is 120)
exclude_compiler: 'clang-3.5,clang-3.6,clang-3.7,clang-3.8,clang-3.9,clang-4.0,clang-5.0,clang-6.0,clang-7,
clang-8,clang-9,clang-10,clang-11,clang-12,
gcc-4.7,gcc-4.8,gcc-4.9,gcc-5,gcc-6,gcc-7,gcc-8,gcc-9,gcc-10'
Expand Down
8 changes: 4 additions & 4 deletions doc/modules/ROOT/pages/api_reference.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -456,16 +456,16 @@ These wrap the standard `<cmath>` functions for the floating-point types `f32` a
| 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
| The scalar free function families (`add`, `sub`, `mul`, `div`, `mod`, and for unsigned elements `shl`, `shr`) applied lane by lane; floating point elements have only `overflowing_add`, `overflowing_sub`, `overflowing_mul`, and `overflowing_div`, as for the scalar types

| xref:simd.adoc[`widening_add`, `widening_mul`]
| Exact results in lanes twice as wide
| Exact results in lanes twice as wide (integer elements)

| xref:simd.adoc[`add<Policy>`, `sub<Policy>`, `mul<Policy>`, `div<Policy>`, `mod<Policy>`, `shl<Policy>`, `shr<Policy>`]
| Vector operations with the policy chosen at the call site (`shl` and `shr` for unsigned elements only)
| Vector operations with the policy chosen at the call site (integer elements; `shl` and `shr` for unsigned elements only)

| xref:simd.adoc[`select`, `min`, `max`, `clamp`]
| Lane by lane selection and ordering
| Lane by lane selection and ordering, following `std::min`, `std::max`, and `std::clamp` for every lane

| xref:simd.adoc[`reduce`, `reduce_min`, `reduce_max`]
| Reductions; `reduce` folds left in lane order with the element's operation
Expand Down
100 changes: 87 additions & 13 deletions doc/modules/ROOT/pages/simd.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,23 @@ The header is opt-in and is not part of the convenience header `<boost/safe_numb
#include <boost/safe_numbers/simd.hpp>
----

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<H>`, and so on).
This release supports the unsigned element types `u8`, `u16`, `u32`, `u64`, the signed element types `i8`, `i16`, `i32`, `i64`, the floating point element types `f32` and `f64`, and their policy forms (`sat_u32`, `strict_i64`, `basic_i32<H>`, `sat_f32`, `basic_f64<H>`, 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.
* `saturate` integer elements clamp every failing lane, branch free. Division and modulo by zero still throw `std::domain_error`, as in the scalar types. `saturate` floating point elements (`sat_f32`, `sat_f64`) are raw IEEE 754 arithmetic with no check at all, 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.
Neither exists for floating point elements, because the scalar `f32` and `f64` deliberately provide neither.

== Backends

Expand Down Expand Up @@ -70,6 +71,10 @@ On the `std::simd` backend (GCC 16, x86-64, `-O2`), checked addition, subtractio
With AVX-512, GCC 16's `<simd>` 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.

GCC 16's `<simd>` also skips the blend in `select` when one arm is a compile time constant equal to zero, but it tests that with `==`, so an arm of `-0.0` lanes comes back as `+0.0`.
The same happens in `min`, `max`, `clamp`, `reduce_min`, and `reduce_max`, which select internally.
`simd::vec` therefore selects floating point lanes by their bit patterns, in unsigned lanes of the same size, which takes the same number of blend instructions.

NOTE: GCC 16's `<simd>` 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).

Expand Down Expand Up @@ -119,18 +124,20 @@ public:
// 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
// Compound assignment for + - * / %, and for unsigned elements & | ^ << >>, with a vec or a T.
// Integer elements only.
template <typename U> constexpr vec& operator+=(const U& rhs);
// ...

// Integer elements only
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
// Arithmetic: + - * / with the element's error policy, and % for integer elements
// Unsigned elements only: << >> and the bitwise & | ^ ~
// Signed elements only: unary -
// Comparisons: == != < <= > >= return mask_type
Expand All @@ -141,23 +148,25 @@ template <typename T, int N> constexpr vec<T, N> saturating_add(const vec<T, N>&
template <typename T, int N> constexpr std::pair<vec<T, N>, typename vec<T, N>::mask_type> overflowing_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr std::optional<vec<T, N>> checked_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> strict_add(const vec<T, N>&, const vec<T, N>&) noexcept;
// ... and likewise for sub, mul, div, mod, and for unsigned elements shl, shr
// ... and likewise for sub, mul, div, mod, and for unsigned elements shl, shr.
// Floating point elements have only overflowing_add, overflowing_sub, overflowing_mul, and overflowing_div.

// Exact results in lanes twice as wide (8, 16, and 32-bit lanes)
// Exact results in lanes twice as wide (8, 16, and 32-bit integer lanes)
template <typename T, int N> constexpr auto widening_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr auto widening_mul(const vec<T, N>&, const vec<T, N>&) noexcept;

// Policy chosen at the call site
// Policy chosen at the call site (integer elements)
template <overflow_policy Policy, typename T, int N> constexpr auto add(const vec<T, N>&, const vec<T, N>&);
// ... and likewise sub, mul, div, mod, and for unsigned elements shl, shr

// Lane algorithms
// Lane algorithms: lane i of min, max, and clamp is std::min, std::max, and std::clamp of lane i
template <typename T, int N> constexpr vec<T, N> select(const typename vec<T, N>::mask_type&, const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> min(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> max(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> clamp(const vec<T, N>& v, const vec<T, N>& lo, const vec<T, N>& hi) noexcept;

// Reductions: reduce folds left in lane order with the element's operation
// Reductions: reduce folds left in lane order with the element's operation.
// For floating point elements, reduce_min and reduce_max require that no lane is NaN.
template <typename T, int N, typename BinaryOperation = std::plus<>> constexpr T reduce(const vec<T, N>&, BinaryOperation = {});
template <typename T, int N> constexpr T reduce_min(const vec<T, N>&) noexcept;
template <typename T, int N> constexpr T reduce_max(const vec<T, N>&) noexcept;
Expand Down Expand Up @@ -188,10 +197,10 @@ template <typename T, int N, typename It> constexpr void partial_store(const vec
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<u32, 4> + vec<u16, 4>`), mixed signedness (`vec<i32, 4> + vec<u32, 4>`), mixed policies (`vec<u32, 4> + vec<sat_u32, 4>`), mixed lane counts (`vec<u32, 4> + vec<u32, 8>`), and built-in operands (`v + 1U`) are compile time errors with a `static_assert` message.
* Mixed widths (`vec<u32, 4> + vec<u16, 4>`, `vec<f32, 4> + vec<f64, 4>`), mixed signedness (`vec<i32, 4> + vec<u32, 4>`), mixed policies (`vec<u32, 4> + vec<sat_u32, 4>`), mixed lane counts (`vec<u32, 4> + vec<u32, 8>`), 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.
* Unary minus is rejected for unsigned elements, and the bitwise and shift operators for signed elements, as for the scalar types. Floating point elements reject every operation the scalar `f32` and `f64` do not provide, listed under <<Floating Point Operations>>.
* The converting constructor converts between widths and policies of one signedness only, and between the policies of one floating point width. The scalar types never convert between signed and unsigned, between `f32` and `f64`, or between integers and floating point, 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.

Expand Down Expand Up @@ -287,6 +296,51 @@ Signed lane arithmetic would be undefined behavior on overflow, so every lane co
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`.

== Floating Point Operations

[cols="1,2,2", options="header"]
|===
| Operation | Error lanes | Error under `throw_exception`

| `+`, `-`, `*`, `/`
| The result is `+inf`, other than from division by zero
| `std::overflow_error`

| `+`, `-`, `*`, `/`
| The result is `-inf`, other than from division by zero
| `std::underflow_error`

| `+`, `-`, `*`, `/`
| The result is NaN: a NaN operand, or an invalid operation such as `inf - inf`, `0 * inf`, `0 / 0`, or a signaling NaN operand
| `std::domain_error`

| `/`
| A finite nonzero dividend divided by zero
| `std::domain_error`
|===

The scalar `f32` and `f64` report an error exactly when the IEEE 754 result is not finite, and classify the cause only to choose the exception and message.
The vector computes every lane with the IEEE 754 operation, which is never undefined behavior, and its error mask is the lanes outside `[lowest, max]`: one pair of comparisons that is false for both infinities and for NaN.
When any lane is set, the scalar operator replays the lanes in order, so the lowest failing lane classifies the error exactly as the scalar type does, and a user defined handler receives the scalar arguments (`error_kind::overflow`, `underflow`, `nan_operation`, `invalid_operation`, or `divide_by_zero`, with the raw IEEE 754 result) for every failing lane.

`sat_f32` and `sat_f64` lanes are raw IEEE 754 arithmetic: they never compute a mask, never throw, and their operators are `noexcept`.
`overflowing_add`, `overflowing_sub`, `overflowing_mul`, and `overflowing_div` return the raw lanes and the mask of the lanes the operator would have reported, for every policy, and are the only free function family, as for the scalar types.

The surface mirrors the scalar types exactly.
There is no `%`, compound assignment, `++`, `--`, unary `+` or `-`, bitwise or shift operator, and no `saturating_*`, `checked_*`, `strict_*`, `widening_*`, or generic `add<Policy>` family, and each of the operators is a `static_assert` with a message.
There is also no `strict_f32`, because `strict` is an integer policy.

Comparisons are IEEE 754 comparisons: a NaN lane compares unequal to everything, and `-0.0` equals `+0.0`.
Lane `i` of `min`, `max`, and `clamp` is `std::min`, `std::max`, and `std::clamp` of lane `i`, so ties and NaN lanes resolve as they do for the scalar types: `min(a, b)` and `max(a, b)` return `a` when the lanes are unordered or equal (for example `-0.0` and `+0.0`), and `clamp` leaves a NaN lane NaN.
GCC 16's `std::simd::min` returns `b` in those lanes, so these are not forwarded to it.
`reduce_min` and `reduce_max` require that no lane is NaN, and when both zeros are the extreme value, which of them is returned is unspecified.

Conversions between the policies of one width (`vec<f32, N>` to `vec<sat_f32, N>` and back) copy every lane unchanged, including infinities and NaNs, as `sat_f32{static_cast<float>(x)}` does for a scalar.

NOTE: On x87 targets (`FLT_EVAL_METHOD` 2, such as 32-bit x86 without SSE2 math), values pass through 80-bit registers.
Copying a signaling NaN through them quiets it, so a failing lane may report `Operation with NAN` where the scalar operation on the original value reports `Invalid operation` (both are `std::domain_error`).
With GCC's `-fexcess-precision=fast`, the scalar types classify the unrounded 80-bit result, so a result just beyond `max` that rounds to `max` may throw for the scalar types but not for the vector lanes, which are rounded before they are checked.

== Deferred Checking

The `overflowing_*` functions never branch on the error, so a loop can accumulate the masks and test them once at the end:
Expand Down Expand Up @@ -349,11 +403,31 @@ lanes where min / -1 overflowed: 4 (wrapped quotient -2147483648)
----
====

.This https://github.com/boostorg/safe_numbers/blob/develop/examples/simd_float.cpp[example] demonstrates floating point vector arithmetic, where a lane that overflows to infinity or divides by zero is reported as the scalar `f32` reports it, together with the overflowing form, raw IEEE 754 `sat_f32` lanes, and the lane algorithms.
====
[source, c++]
----
include::example$simd_float.cpp[tags=**;!exclude]
----

Output:
----
Error: Overflow detected in f32 multiplication
lane 0: 3
lane 1: -9
lane 2: inf (not finite)
lane 3: 4
Error: Division by zero detected in f32 division
saturated: inf -2.25 1.5e+38 2.66667
clamped: 1 -1 1 1
largest reading: 3e+38
----
====

== 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 `<simd>`.
Expand Down
84 changes: 84 additions & 0 deletions examples/simd_float.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// 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 <simd> 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 <boost/safe_numbers/simd.hpp>
#include <boost/safe_numbers/iostream.hpp>
#include <array>
#include <iostream>
#include <stdexcept>

int main()
{
using namespace boost::safe_numbers;
using vec4 = simd::vec<f32, 4>;

// Sensor readings and the gains to apply to them
const std::array<f32, 4> readings {f32{1.5f}, f32{-2.25f}, f32{3.0e38f}, f32{8.0f}};
const std::array<f32, 4> gains {f32{2.0f}, f32{4.0f}, f32{10.0f}, f32{0.5f}};

const auto r {simd::unchecked_load<vec4>(readings)};
const auto g {simd::unchecked_load<vec4>(gains)};

// Lane 2 overflows to infinity, so the vector throws exactly what the scalar f32 throws
try
{
const auto scaled {r * g};
static_cast<void>(scaled);
}
catch (const std::overflow_error& e)
{
std::cout << "Error: " << e.what() << '\n';
}

// overflowing_mul returns the raw IEEE 754 lanes and a mask of the lanes that are not finite
const auto [raw, failed] {simd::overflowing_mul(r, g)};
for (int i {}; i < vec4::size(); ++i)
{
std::cout << "lane " << i << ": " << raw[i] << (failed[i] ? " (not finite)" : "") << '\n';
}

// Division by a zero lane is reported as such, as for the scalar types
const vec4 divisors {[](const auto i) { return f32{static_cast<float>(static_cast<int>(i))}; }};
try
{
const auto quotients {r / divisors};
static_cast<void>(quotients);
}
catch (const std::domain_error& e)
{
std::cout << "Error: " << e.what() << '\n';
}

// sat_f32 lanes are raw IEEE 754 arithmetic: no checks and no exceptions
using sat_vec4 = simd::vec<sat_f32, 4>;
const auto ieee {sat_vec4{r} / sat_vec4{divisors}};
std::cout << "saturated:";
for (int i {}; i < sat_vec4::size(); ++i)
{
std::cout << ' ' << ieee[i];
}
std::cout << '\n';

// Lane algorithms follow std::min, std::max, and std::clamp lane by lane
const auto limited {simd::clamp(r, vec4{f32{-1.0f}}, vec4{f32{1.0f}})};
std::cout << "clamped:";
for (int i {}; i < vec4::size(); ++i)
{
std::cout << ' ' << limited[i];
}
std::cout << "\nlargest reading: " << simd::reduce_max(r) << '\n';

// As for the scalar f32, there is no operator%, compound assignment, or unary minus:
// r % g; // static_assert: There is no operator% for floating point safe types

return 0;
}
Loading
Loading