Skip to content

Commit

Permalink
util/libm: replace force_eval! by std::hint::black_box
Browse files Browse the repository at this point in the history
During an internal review of unsafe code at work, @cramertj noticed
that the the `force_eval!` can be replaced by `std::hint::black_box`,
removing the need for unsafe Rust.
  • Loading branch information
martinvonz committed Aug 27, 2024
1 parent b4c9bce commit c2bf48b
Showing 1 changed file with 8 additions and 28 deletions.
36 changes: 8 additions & 28 deletions src/util/libm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ pub(crate) trait Float {
fn fract(self) -> Self;
}

macro_rules! force_eval {
($e:expr) => {
core::ptr::read_volatile(&$e)
};
}

const TOINT64: f64 = 1. / f64::EPSILON;

impl Float for f64 {
Expand Down Expand Up @@ -58,9 +52,7 @@ impl Float for f64 {
};
// special case because of non-nearest rounding modes
if e < 0x3ff {
unsafe {
force_eval!(y);
}
std::hint::black_box(y);
return if (u >> 63) != 0 { -0. } else { 1. };
}
if y < 0. {
Expand All @@ -86,9 +78,7 @@ impl Float for f64 {
};
/* special case because of non-nearest rounding modes */
if e < 0x3ff {
unsafe {
force_eval!(y);
}
std::hint::black_box(y);
return if (ui >> 63) != 0 { -1. } else { 0. };
}
if y > 0. {
Expand Down Expand Up @@ -129,7 +119,7 @@ impl Float for f64 {
return x;
}
unsafe {
force_eval!(x + x1p120);
std::hint::black_box(x + x1p120);
}
i &= !m;
f64::from_bits(i)
Expand Down Expand Up @@ -162,17 +152,13 @@ impl Float for f32 {
if (ui & m) == 0 {
return x;
}
unsafe {
force_eval!(x + f32::from_bits(0x7b800000));
}
std::hint::black_box(x + f32::from_bits(0x7b800000));
if ui >> 31 == 0 {
ui += m;
}
ui &= !m;
} else {
unsafe {
force_eval!(x + f32::from_bits(0x7b800000));
}
std::hint::black_box(x + f32::from_bits(0x7b800000));
if ui >> 31 != 0 {
return -0.0;
} else if ui << 1 != 0 {
Expand All @@ -195,17 +181,13 @@ impl Float for f32 {
if (ui & m) == 0 {
return x;
}
unsafe {
force_eval!(x + f32::from_bits(0x7b800000));
}
std::hint::black_box(x + f32::from_bits(0x7b800000));
if ui >> 31 != 0 {
ui += m;
}
ui &= !m;
} else {
unsafe {
force_eval!(x + f32::from_bits(0x7b800000));
}
std::hint::black_box(x + f32::from_bits(0x7b800000));
if ui >> 31 == 0 {
ui = 0;
} else if ui << 1 != 0 {
Expand Down Expand Up @@ -245,9 +227,7 @@ impl Float for f32 {
if (i & m) == 0 {
return x;
}
unsafe {
force_eval!(x + x1p120);
}
std::hint::black_box(x + x1p120);
i &= !m;
f32::from_bits(i)
}
Expand Down

0 comments on commit c2bf48b

Please sign in to comment.