1use std::ops::Neg;
2
3use rand::RngExt;
4use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, Semantics, SingleS};
5use rustc_apfloat::{Float, FloatConvert};
6use rustc_middle::ty::{self, FloatTy, ScalarInt};
7
8use crate::*;
9
10pub trait ToHost {
12 type HostFloat;
13 fn to_host(self) -> Self::HostFloat;
14}
15
16pub trait ToSoft {
18 type SoftFloat;
19 fn to_soft(self) -> Self::SoftFloat;
20}
21
22impl ToHost for rustc_apfloat::ieee::Double {
23 type HostFloat = f64;
24
25 fn to_host(self) -> Self::HostFloat {
26 f64::from_bits(self.to_bits().try_into().unwrap())
27 }
28}
29
30impl ToSoft for f64 {
31 type SoftFloat = rustc_apfloat::ieee::Double;
32
33 fn to_soft(self) -> Self::SoftFloat {
34 Float::from_bits(self.to_bits().into())
35 }
36}
37
38impl ToHost for rustc_apfloat::ieee::Single {
39 type HostFloat = f32;
40
41 fn to_host(self) -> Self::HostFloat {
42 f32::from_bits(self.to_bits().try_into().unwrap())
43 }
44}
45
46impl ToSoft for f32 {
47 type SoftFloat = rustc_apfloat::ieee::Single;
48
49 fn to_soft(self) -> Self::SoftFloat {
50 Float::from_bits(self.to_bits().into())
51 }
52}
53
54impl ToHost for rustc_apfloat::ieee::Half {
55 type HostFloat = f16;
56
57 fn to_host(self) -> Self::HostFloat {
58 f16::from_bits(self.to_bits().try_into().unwrap())
59 }
60}
61
62impl ToSoft for f16 {
63 type SoftFloat = rustc_apfloat::ieee::Half;
64
65 fn to_soft(self) -> Self::SoftFloat {
66 Float::from_bits(self.to_bits().into())
67 }
68}
69
70pub(crate) fn apply_random_float_error<F: rustc_apfloat::Float>(
72 ecx: &mut crate::MiriInterpCx<'_>,
73 val: F,
74 err_scale: i32,
75) -> F {
76 if !ecx.machine.float_nondet
77 || matches!(ecx.machine.float_rounding_error, FloatRoundingErrorMode::None)
78 || val.is_zero()
80 || !val.is_finite()
82 {
83 return val;
84 }
85 let rng = ecx.machine.rng.get_mut();
86
87 let r = F::from_u128(match ecx.machine.float_rounding_error {
92 FloatRoundingErrorMode::Random => rng.random_range(0..(1 << F::PRECISION)),
93 FloatRoundingErrorMode::Max => (1 << F::PRECISION) - 1, FloatRoundingErrorMode::None => unreachable!(),
95 })
96 .value;
97 let err = r.scalbn(err_scale.strict_sub(F::PRECISION.try_into().unwrap()));
100 let err = if rng.random() { -err } else { err };
102 (val + (val * err).value).value
105}
106
107pub(crate) fn apply_random_float_error_ulp<F: rustc_apfloat::Float>(
109 ecx: &mut crate::MiriInterpCx<'_>,
110 val: F,
111 max_error: u32,
112) -> F {
113 if !ecx.machine.float_nondet
117 || matches!(ecx.machine.float_rounding_error, FloatRoundingErrorMode::None)
118 || val.is_zero()
121 || !val.is_finite()
123 {
124 return val;
125 }
126 let rng = ecx.machine.rng.get_mut();
127
128 let max_error = i64::from(max_error);
129 let error = match ecx.machine.float_rounding_error {
130 FloatRoundingErrorMode::Random => rng.random_range(-max_error..=max_error),
131 FloatRoundingErrorMode::Max =>
132 if rng.random() {
133 max_error
134 } else {
135 -max_error
136 },
137 FloatRoundingErrorMode::None => unreachable!(),
138 };
139 let ulp = (((val.next_up().value - val).value + (val - val.next_down().value).value).value
141 / F::from_u128(2).value)
142 .value;
143 (val + (ulp * F::from_i128(error.into()).value).value).value
145}
146
147pub(crate) fn apply_random_float_error_to_imm<'tcx>(
150 ecx: &mut MiriInterpCx<'tcx>,
151 val: ImmTy<'tcx>,
152 max_error: u32,
153) -> InterpResult<'tcx, ImmTy<'tcx>> {
154 let scalar = val.to_scalar_int()?;
155 let res: ScalarInt = match val.layout.ty.kind() {
156 ty::Float(FloatTy::F16) =>
157 apply_random_float_error_ulp(ecx, scalar.to_f16(), max_error).into(),
158 ty::Float(FloatTy::F32) =>
159 apply_random_float_error_ulp(ecx, scalar.to_f32(), max_error).into(),
160 ty::Float(FloatTy::F64) =>
161 apply_random_float_error_ulp(ecx, scalar.to_f64(), max_error).into(),
162 ty::Float(FloatTy::F128) =>
163 apply_random_float_error_ulp(ecx, scalar.to_f128(), max_error).into(),
164 _ => bug!("intrinsic called with non-float input type"),
165 };
166
167 interp_ok(ImmTy::from_scalar_int(res, val.layout))
168}
169
170fn strip_float_suffix(intrinsic_name: &str) -> &str {
175 let name = intrinsic_name
176 .strip_suffix("f16")
177 .or_else(|| intrinsic_name.strip_suffix("f32"))
178 .or_else(|| intrinsic_name.strip_suffix("f64"))
179 .or_else(|| intrinsic_name.strip_suffix("f128"))
180 .unwrap_or(intrinsic_name);
181
182 if name == "erf" { name } else { name.strip_suffix("f").unwrap_or(name) }
183}
184
185pub(crate) fn clamp_float_value<S: Semantics>(
190 intrinsic_name: &str,
191 val: IeeeFloat<S>,
192) -> IeeeFloat<S>
193where
194 IeeeFloat<S>: IeeeExt,
195{
196 let zero = IeeeFloat::<S>::ZERO;
197 let one = IeeeFloat::<S>::one();
198 let two = IeeeFloat::<S>::two();
199 let pi = IeeeFloat::<S>::pi();
200 let pi_over_2 = (pi / two).value;
201
202 match strip_float_suffix(intrinsic_name) {
203 "sin" | "cos" | "tanh" => val.clamp(one.neg(), one),
205
206 "exp" | "exp2" => val.maximum(zero),
208
209 "cosh" => val.maximum(one),
211
212 "acos" => val.clamp(zero, pi),
214
215 "asin" => val.clamp(pi_over_2.neg(), pi_over_2),
217
218 "atan" => val.clamp(pi_over_2.neg(), pi_over_2),
220
221 "erf" => val.clamp(one.neg(), one),
223
224 "erfc" => val.clamp(zero, two),
226
227 "atan2" => val.clamp(pi.neg(), pi),
229
230 _ => val,
231 }
232}
233
234pub(crate) fn fixed_float_value<S: Semantics>(
269 ecx: &mut MiriInterpCx<'_>,
270 intrinsic_name: &str,
271 args: &[IeeeFloat<S>],
272) -> Option<IeeeFloat<S>>
273where
274 IeeeFloat<S>: IeeeExt,
275{
276 let ecx = ecx.eval_context_mut();
277 let one = IeeeFloat::<S>::one();
278 let two = IeeeFloat::<S>::two();
279 let three = IeeeFloat::<S>::three();
280 let pi = IeeeFloat::<S>::pi();
281 let pi_over_2 = (pi / two).value;
282 let pi_over_4 = (pi_over_2 / two).value;
283
284 Some(match (strip_float_suffix(intrinsic_name), args) {
285 ("cos" | "cosh", [input]) if input.is_zero() => one,
287
288 ("exp" | "exp2", [input]) if input.is_zero() => one,
290
291 ("tanh", [input]) if input.is_infinite() => one.copy_sign(*input),
293
294 ("atan", [input]) if input.is_infinite() => pi_over_2.copy_sign(*input),
296
297 ("erf", [input]) if input.is_infinite() => one.copy_sign(*input),
299
300 ("erfc", [input]) if input.is_neg_infinity() => (one + one).value,
302
303 ("_hypot" | "hypot", [x, y]) if !x.is_nan() && y.is_zero() => x.abs(),
306
307 ("atan2", [x, y]) if x.is_nan() || y.is_nan() => return None,
310
311 ("atan2", [x, y]) if (x.is_zero() && y.is_negative()) => pi.copy_sign(*x),
314
315 ("atan2", [x, y]) if (!x.is_zero() && !x.is_infinite()) && y.is_neg_infinity() =>
317 pi.copy_sign(*x),
318
319 ("atan2", [x, y]) if !x.is_zero() && y.is_zero() => pi_over_2.copy_sign(*x),
322
323 ("atan2", [x, y]) if x.is_infinite() && y.is_neg_infinity() =>
325 (pi_over_4 * three).value.copy_sign(*x),
326
327 ("atan2", [x, y]) if x.is_infinite() && y.is_pos_infinity() => pi_over_4.copy_sign(*x),
329
330 ("atan2", [x, y]) if x.is_infinite() && !y.is_infinite() => pi_over_2.copy_sign(*x),
332
333 ("pow", [base, exp]) if *base == -one && exp.is_infinite() => one,
335
336 ("pow", [base, exp]) if *base == one => {
338 let rng = ecx.machine.rng.get_mut();
339 let return_nan = exp.is_signaling() && ecx.machine.float_nondet && rng.random();
343 if return_nan { ecx.generate_nan(args) } else { one }
344 }
345
346 ("pow", [base, exp]) if exp.is_zero() => {
348 let rng = ecx.machine.rng.get_mut();
349 let return_nan = base.is_signaling() && ecx.machine.float_nondet && rng.random();
353 if return_nan { ecx.generate_nan(args) } else { one }
354 }
355
356 _ => return None,
359 })
360}
361
362pub(crate) fn fixed_powi_value<S: Semantics>(
365 ecx: &mut MiriInterpCx<'_>,
366 base: IeeeFloat<S>,
367 exp: i32,
368) -> Option<IeeeFloat<S>>
369where
370 IeeeFloat<S>: IeeeExt,
371{
372 match exp {
373 0 => {
374 let one = IeeeFloat::<S>::one();
375 let rng = ecx.machine.rng.get_mut();
376 let return_nan = base.is_signaling() && ecx.machine.float_nondet && rng.random();
379 Some(if return_nan { ecx.generate_nan(&[base]) } else { one })
380 }
381
382 _ => None,
383 }
384}
385
386pub(crate) fn sqrt<F: Float>(x: F) -> F {
387 match x.category() {
388 rustc_apfloat::Category::Zero => x,
390 rustc_apfloat::Category::NaN => x,
392 _ if x.is_negative() => F::NAN,
394 rustc_apfloat::Category::Infinity => F::INFINITY,
396 rustc_apfloat::Category::Normal => {
397 let prec = i32::try_from(F::PRECISION).unwrap() - 1;
399
400 let mut exp = x.ilogb();
404 let mut mant = x.scalbn(prec - exp).to_u128(128).value;
405
406 if exp % 2 != 0 {
407 exp -= 1;
409 mant <<= 1;
410 }
411
412 let mut res = 0u128;
419 let mut rem = mant << 1;
423 let mut s = 0u128;
425 let mut d = 1u128 << (prec + 1);
427
428 while d != 0 {
437 let t = s + d;
440 if rem >= t {
441 res += d;
443 s += d + d;
444 rem -= t;
445 }
446 rem <<= 1;
448 d >>= 1;
450 }
451
452 res = (res + 1) >> 1;
461
462 F::from_u128(res).value.scalbn(exp / 2 - prec)
464 }
465 }
466}
467
468pub fn sqrt_op<'tcx, F: Float + FloatConvert<F> + Into<Scalar>>(
469 ecx: &mut MiriInterpCx<'tcx>,
470 f: &OpTy<'tcx>,
471 dest: &PlaceTy<'tcx>,
472) -> InterpResult<'tcx> {
473 let f: F = ecx.read_scalar(f)?.to_float()?;
474 let res = math::sqrt(f);
476 let res = ecx.adjust_nan(res, &[f]);
477 ecx.write_scalar(res, dest)
478}
479
480pub trait HostFloatOperation {
481 fn host_sin(self) -> Self;
482 fn host_cos(self) -> Self;
483 fn host_exp(self) -> Self;
484 fn host_exp2(self) -> Self;
485 fn host_log(self) -> Self;
486 fn host_log10(self) -> Self;
487 fn host_log2(self) -> Self;
488 fn host_powf(self, y: Self) -> Self;
489 fn host_powi(self, y: i32) -> Self;
490}
491
492macro_rules! impl_float_host_operations {
493 ($ty:ty) => {
494 impl HostFloatOperation for $ty {
495 fn host_sin(self) -> Self {
496 self.to_host().sin().to_soft()
497 }
498 fn host_cos(self) -> Self {
499 self.to_host().cos().to_soft()
500 }
501 fn host_exp(self) -> Self {
502 self.to_host().exp().to_soft()
503 }
504 fn host_exp2(self) -> Self {
505 self.to_host().exp2().to_soft()
506 }
507 fn host_log(self) -> Self {
508 self.to_host().ln().to_soft()
509 }
510 fn host_log10(self) -> Self {
511 self.to_host().log10().to_soft()
512 }
513 fn host_log2(self) -> Self {
514 self.to_host().log2().to_soft()
515 }
516 fn host_powf(self, y: Self) -> Self {
517 self.to_host().powf(y.to_host()).to_soft()
518 }
519 fn host_powi(self, y: i32) -> Self {
520 self.to_host().powi(y).to_soft()
521 }
522 }
523 };
524}
525
526impl_float_host_operations!(IeeeFloat<HalfS>);
527impl_float_host_operations!(IeeeFloat<SingleS>);
528impl_float_host_operations!(IeeeFloat<DoubleS>);
529
530#[derive(Debug, Clone, Copy)]
531pub enum HostUnaryFloatOp {
532 Sin,
533 Cos,
534 Exp,
535 Exp2,
536 Log,
537 Log10,
538 Log2,
539}
540
541pub fn host_unary_float_op<'tcx, S: Semantics>(
542 ecx: &mut MiriInterpCx<'tcx>,
543 f: &OpTy<'tcx>,
544 op: HostUnaryFloatOp,
545 dest: &PlaceTy<'tcx>,
546) -> InterpResult<'tcx>
547where
548 IeeeFloat<S>: HostFloatOperation + IeeeExt + Float + Into<Scalar>,
549{
550 use HostFloatOperation;
551
552 let f: IeeeFloat<S> = ecx.read_scalar(f)?.to_float()?;
553
554 let name = match op {
556 HostUnaryFloatOp::Sin => "sin",
557 HostUnaryFloatOp::Cos => "cos",
558 HostUnaryFloatOp::Exp => "exp",
559 HostUnaryFloatOp::Exp2 => "exp2",
560 HostUnaryFloatOp::Log => "log",
561 HostUnaryFloatOp::Log10 => "log10",
562 HostUnaryFloatOp::Log2 => "log2",
563 };
564 let res = math::fixed_float_value(ecx, name, &[f]).unwrap_or_else(|| {
565 let res = match op {
568 HostUnaryFloatOp::Sin => f.host_sin(),
569 HostUnaryFloatOp::Cos => f.host_cos(),
570 HostUnaryFloatOp::Exp => f.host_exp(),
571 HostUnaryFloatOp::Exp2 => f.host_exp2(),
572 HostUnaryFloatOp::Log => f.host_log(),
573 HostUnaryFloatOp::Log10 => f.host_log10(),
574 HostUnaryFloatOp::Log2 => f.host_log2(),
575 };
576
577 let res = math::apply_random_float_error_ulp(ecx, res, 4);
580
581 math::clamp_float_value(name, res)
584 });
585
586 let res = ecx.adjust_nan(res, &[f]);
587 ecx.write_scalar(res, dest)?;
588 interp_ok(())
589}
590
591pub trait IeeeExt: rustc_apfloat::Float {
593 #[inline]
596 fn one() -> Self {
597 Self::from_u128(1).value
598 }
599
600 #[inline]
601 fn two() -> Self {
602 Self::from_u128(2).value
603 }
604
605 #[inline]
606 fn three() -> Self {
607 Self::from_u128(3).value
608 }
609
610 fn pi() -> Self;
611
612 #[inline]
613 fn clamp(self, min: Self, max: Self) -> Self {
614 self.maximum(min).minimum(max)
615 }
616}
617
618macro_rules! impl_ieee_pi {
619 ($float_ty:ident, $semantic:ty) => {
620 impl IeeeExt for IeeeFloat<$semantic> {
621 #[inline]
622 fn pi() -> Self {
623 Self::from_bits(core::$float_ty::consts::PI.to_bits().into())
625 }
626 }
627 };
628}
629
630impl_ieee_pi!(f16, HalfS);
631impl_ieee_pi!(f32, SingleS);
632impl_ieee_pi!(f64, DoubleS);
633
634#[cfg(test)]
635mod tests {
636 use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, QuadS, SingleS};
637
638 use super::sqrt;
639
640 #[test]
641 fn test_sqrt() {
642 #[track_caller]
643 fn test<S: rustc_apfloat::ieee::Semantics>(x: &str, expected: &str) {
644 let x: IeeeFloat<S> = x.parse().unwrap();
645 let expected: IeeeFloat<S> = expected.parse().unwrap();
646 let result = sqrt(x);
647 assert_eq!(result, expected);
648 }
649
650 fn exact_tests<S: rustc_apfloat::ieee::Semantics>() {
651 test::<S>("0", "0");
652 test::<S>("1", "1");
653 test::<S>("1.5625", "1.25");
654 test::<S>("2.25", "1.5");
655 test::<S>("4", "2");
656 test::<S>("5.0625", "2.25");
657 test::<S>("9", "3");
658 test::<S>("16", "4");
659 test::<S>("25", "5");
660 test::<S>("36", "6");
661 test::<S>("49", "7");
662 test::<S>("64", "8");
663 test::<S>("81", "9");
664 test::<S>("100", "10");
665
666 test::<S>("0.5625", "0.75");
667 test::<S>("0.25", "0.5");
668 test::<S>("0.0625", "0.25");
669 test::<S>("0.00390625", "0.0625");
670 }
671
672 exact_tests::<HalfS>();
673 exact_tests::<SingleS>();
674 exact_tests::<DoubleS>();
675 exact_tests::<QuadS>();
676
677 test::<SingleS>("2", "1.4142135");
678 test::<DoubleS>("2", "1.4142135623730951");
679
680 test::<SingleS>("1.1", "1.0488088");
681 test::<DoubleS>("1.1", "1.0488088481701516");
682
683 test::<SingleS>("2.2", "1.4832398");
684 test::<DoubleS>("2.2", "1.4832396974191326");
685
686 test::<SingleS>("1.22101e-40", "1.10499205e-20");
687 test::<DoubleS>("1.22101e-310", "1.1049932126488395e-155");
688
689 test::<SingleS>("3.4028235e38", "1.8446743e19");
690 test::<DoubleS>("1.7976931348623157e308", "1.3407807929942596e154");
691 }
692}