Skip to content

impl std::simd::StdFloat #219

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 31, 2021
Merged
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@

members = [
"crates/core_simd",
"crates/std_float",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this crate maybe be called std_simd? It only has the extra float stuff for now, but it could end up with something unexpected.

Copy link
Member Author

@workingjubilee workingjubilee Dec 24, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not necessarily obvious we would want to keep anything else we include in std in the same crate (since, notionally, this one ought to be Doomed) and we'd likely have to adjust the paths for inclusion anyways (to use the more complicated scheme). It's fine to rename it if something does come up.

"crates/test_helpers",
]
3 changes: 3 additions & 0 deletions crates/core_simd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,6 @@ features = ["alloc"]

[dev-dependencies.test_helpers]
path = "../test_helpers"

[dev-dependencies]
std_float = { path = "../std_float/", features = ["as_crate"] }
10 changes: 5 additions & 5 deletions crates/core_simd/examples/nbody.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#![cfg_attr(feature = "std", feature(portable_simd))]
#![feature(portable_simd)]
extern crate std_float;

/// Benchmarks game nbody code
/// Taken from the `packed_simd` crate
/// Run this benchmark with `cargo test --example nbody`
#[cfg(feature = "std")]
mod nbody {
use core_simd::*;
use core_simd::simd::*;
#[allow(unused)] // False positive?
use std_float::StdFloat;

use std::f64::consts::PI;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
Expand Down Expand Up @@ -167,7 +169,6 @@ mod nbody {
}
}

#[cfg(feature = "std")]
#[cfg(test)]
mod tests {
// Good enough for demonstration purposes, not going for strictness here.
Expand All @@ -184,7 +185,6 @@ mod tests {
}

fn main() {
#[cfg(feature = "std")]
{
let (energy_before, energy_after) = nbody::run(1000);
println!("Energy before: {}", energy_before);
Expand Down
26 changes: 0 additions & 26 deletions crates/core_simd/src/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,29 +87,3 @@ extern "platform-intrinsic" {
#[allow(unused)]
pub(crate) fn simd_select_bitmask<M, T>(m: M, a: T, b: T) -> T;
}

#[cfg(feature = "std")]
mod std {
extern "platform-intrinsic" {
// ceil
pub(crate) fn simd_ceil<T>(x: T) -> T;

// floor
pub(crate) fn simd_floor<T>(x: T) -> T;

// round
pub(crate) fn simd_round<T>(x: T) -> T;

// trunc
pub(crate) fn simd_trunc<T>(x: T) -> T;

// fsqrt
pub(crate) fn simd_fsqrt<T>(x: T) -> T;

// fma
pub(crate) fn simd_fma<T>(x: T, y: T, z: T) -> T;
}
}

#[cfg(feature = "std")]
pub(crate) use crate::simd::intrinsics::std::*;
41 changes: 0 additions & 41 deletions crates/core_simd/src/round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,47 +5,6 @@ macro_rules! implement {
{
$type:ty, $int_type:ty
} => {
#[cfg(feature = "std")]
impl<const LANES: usize> Simd<$type, LANES>
where
LaneCount<LANES>: SupportedLaneCount,
{
/// Returns the smallest integer greater than or equal to each lane.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
pub fn ceil(self) -> Self {
unsafe { intrinsics::simd_ceil(self) }
}

/// Returns the largest integer value less than or equal to each lane.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
pub fn floor(self) -> Self {
unsafe { intrinsics::simd_floor(self) }
}

/// Rounds to the nearest integer value. Ties round toward zero.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
pub fn round(self) -> Self {
unsafe { intrinsics::simd_round(self) }
}

/// Returns the floating point's integer value, with its fractional part removed.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
pub fn trunc(self) -> Self {
unsafe { intrinsics::simd_trunc(self) }
}

/// Returns the floating point's fractional value, with its integer part removed.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
pub fn fract(self) -> Self {
self - self.trunc()
}
}

impl<const LANES: usize> Simd<$type, LANES>
where
LaneCount<LANES>: SupportedLaneCount,
Expand Down
23 changes: 0 additions & 23 deletions crates/core_simd/src/vector/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,29 +38,6 @@ macro_rules! impl_float_vector {
unsafe { intrinsics::simd_fabs(self) }
}

/// Fused multiply-add. Computes `(self * a) + b` with only one rounding error,
/// yielding a more accurate result than an unfused multiply-add.
///
/// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
/// architecture has a dedicated `fma` CPU instruction. However, this is not always
/// true, and will be heavily dependent on designing algorithms with specific target
/// hardware in mind.
#[cfg(feature = "std")]
#[inline]
#[must_use = "method returns a new vector and does not mutate the original value"]
pub fn mul_add(self, a: Self, b: Self) -> Self {
unsafe { intrinsics::simd_fma(self, a, b) }
}

/// Produces a vector where every lane has the square root value
/// of the equivalently-indexed lane in `self`
#[inline]
#[must_use = "method returns a new vector and does not mutate the original value"]
#[cfg(feature = "std")]
pub fn sqrt(self) -> Self {
unsafe { intrinsics::simd_fsqrt(self) }
}

/// Takes the reciprocal (inverse) of each lane, `1/x`.
#[inline]
#[must_use = "method returns a new vector and does not mutate the original value"]
Expand Down
2 changes: 2 additions & 0 deletions crates/core_simd/tests/ops_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,8 @@ macro_rules! impl_float_tests {

#[cfg(feature = "std")]
mod std {
use std_float::StdFloat;

use super::*;
test_helpers::test_lanes! {
fn sqrt<const LANES: usize>() {
Expand Down
2 changes: 2 additions & 0 deletions crates/core_simd/tests/round.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
macro_rules! float_rounding_test {
{ $scalar:tt, $int_scalar:tt } => {
mod $scalar {
use std_float::StdFloat;

type Vector<const LANES: usize> = core_simd::Simd<$scalar, LANES>;
type Scalar = $scalar;
type IntScalar = $int_scalar;
Expand Down
13 changes: 13 additions & 0 deletions crates/std_float/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "std_float"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
core_simd = { path = "../core_simd" }

[features]
default = ["as_crate"]
as_crate = []
165 changes: 165 additions & 0 deletions crates/std_float/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
#![cfg_attr(feature = "as_crate", no_std)] // We are std!
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this different than the lib.rs/mod.rs shenanigans in core_simd?

Copy link
Member Author

@workingjubilee workingjubilee Dec 24, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it's just a single file we can just name it easily, and it doesn't cause any "dancing".

But when it's not "actually a crate", it's not allowed to set #![no_std]. I could probably adjust things more to be less complicated in this case (truly build as a crate and just reimport from std?) but I followed the same model as with core_simd so as to minimize any possible dependency issues in the Rust build system, as I would rather explore that as cleanup afterwards. I guess the question here is whether this will ever depend on something else inside std. If so: yes, we definitely need it to be included this way. If not, then it can just be its own entire thing.

#![cfg_attr(
feature = "as_crate",
feature(platform_intrinsics),
feature(portable_simd)
)]
#[cfg(not(feature = "as_crate"))]
use core::simd;
#[cfg(feature = "as_crate")]
use core_simd::simd;

use simd::{LaneCount, Simd, SupportedLaneCount};

#[cfg(feature = "as_crate")]
mod experimental {
pub trait Sealed {}
}

#[cfg(feature = "as_crate")]
use experimental as sealed;

use crate::sealed::Sealed;

// "platform intrinsics" are essentially "codegen intrinsics"
// each of these may be scalarized and lowered to a libm call
extern "platform-intrinsic" {
// ceil
fn simd_ceil<T>(x: T) -> T;

// floor
fn simd_floor<T>(x: T) -> T;

// round
fn simd_round<T>(x: T) -> T;

// trunc
fn simd_trunc<T>(x: T) -> T;

// fsqrt
fn simd_fsqrt<T>(x: T) -> T;

// fma
fn simd_fma<T>(x: T, y: T, z: T) -> T;
}

/// This trait provides a possibly-temporary implementation of float functions
/// that may, in the absence of hardware support, canonicalize to calling an
/// operating system's `math.h` dynamically-loaded library (also known as a
/// shared object). As these conditionally require runtime support, they
/// should only appear in binaries built assuming OS support: `std`.
///
/// However, there is no reason SIMD types, in general, need OS support,
/// as for many architectures an embedded binary may simply configure that
/// support itself. This means these types must be visible in `core`
/// but have these functions available in `std`.
///
/// [`f32`] and [`f64`] achieve a similar trick by using "lang items", but
/// due to compiler limitations, it is harder to implement this approach for
/// abstract data types like [`Simd`]. From that need, this trait is born.
///
/// It is possible this trait will be replaced in some manner in the future,
/// when either the compiler or its supporting runtime functions are improved.
/// For now this trait is available to permit experimentation with SIMD float
/// operations that may lack hardware support, such as `mul_add`.
pub trait StdFloat: Sealed + Sized {
/// Fused multiply-add. Computes `(self * a) + b` with only one rounding error,
/// yielding a more accurate result than an unfused multiply-add.
///
/// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
/// architecture has a dedicated `fma` CPU instruction. However, this is not always
/// true, and will be heavily dependent on designing algorithms with specific target
/// hardware in mind.
#[inline]
#[must_use = "method returns a new vector and does not mutate the original value"]
fn mul_add(self, a: Self, b: Self) -> Self {
unsafe { simd_fma(self, a, b) }
}

/// Produces a vector where every lane has the square root value
/// of the equivalently-indexed lane in `self`
#[inline]
#[must_use = "method returns a new vector and does not mutate the original value"]
fn sqrt(self) -> Self {
unsafe { simd_fsqrt(self) }
}

/// Returns the smallest integer greater than or equal to each lane.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
fn ceil(self) -> Self {
unsafe { simd_ceil(self) }
}

/// Returns the largest integer value less than or equal to each lane.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
fn floor(self) -> Self {
unsafe { simd_floor(self) }
}

/// Rounds to the nearest integer value. Ties round toward zero.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
fn round(self) -> Self {
unsafe { simd_round(self) }
}

/// Returns the floating point's integer value, with its fractional part removed.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
fn trunc(self) -> Self {
unsafe { simd_trunc(self) }
}

/// Returns the floating point's fractional value, with its integer part removed.
#[must_use = "method returns a new vector and does not mutate the original value"]
fn fract(self) -> Self;
}

impl<const N: usize> Sealed for Simd<f32, N> where LaneCount<N>: SupportedLaneCount {}
impl<const N: usize> Sealed for Simd<f64, N> where LaneCount<N>: SupportedLaneCount {}

// We can safely just use all the defaults.
impl<const N: usize> StdFloat for Simd<f32, N>
where
LaneCount<N>: SupportedLaneCount,
{
/// Returns the floating point's fractional value, with its integer part removed.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
fn fract(self) -> Self {
self - self.trunc()
}
}

impl<const N: usize> StdFloat for Simd<f64, N>
where
LaneCount<N>: SupportedLaneCount,
{
/// Returns the floating point's fractional value, with its integer part removed.
#[must_use = "method returns a new vector and does not mutate the original value"]
#[inline]
fn fract(self) -> Self {
self - self.trunc()
}
}

#[cfg(test)]
mod tests {
use super::*;
use simd::*;

#[test]
fn everything_works() {
let x = f32x4::from_array([0.1, 0.5, 0.6, -1.5]);
let x2 = x + x;
let _xc = x.ceil();
let _xf = x.floor();
let _xr = x.round();
let _xt = x.trunc();
let _xfma = x.mul_add(x, x);
let _xsqrt = x.sqrt();
let _ = x2.abs() * x2;
}
}