1 #include "fp-testing.h" 2 #include "llvm/Support/Errno.h" 3 #include <cstdio> 4 #include <cstdlib> 5 #include <cstring> 6 7 using Fortran::common::RoundingMode; 8 using Fortran::evaluate::RealFlag; 9 10 ScopedHostFloatingPointEnvironment::ScopedHostFloatingPointEnvironment( 11 #if __x86_64__ 12 bool treatSubnormalOperandsAsZero, bool flushSubnormalResultsToZero 13 #else 14 bool, bool 15 #endif 16 ) { 17 errno = 0; 18 if (feholdexcept(&originalFenv_) != 0) { 19 std::fprintf(stderr, "feholdexcept() failed: %s\n", 20 llvm::sys::StrError(errno).c_str()); 21 std::abort(); 22 } 23 if (fegetenv(¤tFenv_) != 0) { 24 std::fprintf( 25 stderr, "fegetenv() failed: %s\n", llvm::sys::StrError(errno).c_str()); 26 std::abort(); 27 } 28 #if __x86_64__ 29 if (treatSubnormalOperandsAsZero) { 30 currentFenv_.__mxcsr |= 0x0040; 31 } else { 32 currentFenv_.__mxcsr &= ~0x0040; 33 } 34 if (flushSubnormalResultsToZero) { 35 currentFenv_.__mxcsr |= 0x8000; 36 } else { 37 currentFenv_.__mxcsr &= ~0x8000; 38 } 39 #else 40 // TODO others 41 #endif 42 errno = 0; 43 if (fesetenv(¤tFenv_) != 0) { 44 std::fprintf( 45 stderr, "fesetenv() failed: %s\n", llvm::sys::StrError(errno).c_str()); 46 std::abort(); 47 } 48 } 49 50 ScopedHostFloatingPointEnvironment::~ScopedHostFloatingPointEnvironment() { 51 errno = 0; 52 if (fesetenv(&originalFenv_) != 0) { 53 std::fprintf( 54 stderr, "fesetenv() failed: %s\n", llvm::sys::StrError(errno).c_str()); 55 std::abort(); 56 } 57 } 58 59 void ScopedHostFloatingPointEnvironment::ClearFlags() const { 60 feclearexcept(FE_ALL_EXCEPT); 61 } 62 63 RealFlags ScopedHostFloatingPointEnvironment::CurrentFlags() { 64 int exceptions = fetestexcept(FE_ALL_EXCEPT); 65 RealFlags flags; 66 if (exceptions & FE_INVALID) { 67 flags.set(RealFlag::InvalidArgument); 68 } 69 if (exceptions & FE_DIVBYZERO) { 70 flags.set(RealFlag::DivideByZero); 71 } 72 if (exceptions & FE_OVERFLOW) { 73 flags.set(RealFlag::Overflow); 74 } 75 if (exceptions & FE_UNDERFLOW) { 76 flags.set(RealFlag::Underflow); 77 } 78 if (exceptions & FE_INEXACT) { 79 flags.set(RealFlag::Inexact); 80 } 81 return flags; 82 } 83 84 void ScopedHostFloatingPointEnvironment::SetRounding(Rounding rounding) { 85 switch (rounding.mode) { 86 case RoundingMode::TiesToEven: 87 fesetround(FE_TONEAREST); 88 break; 89 case RoundingMode::ToZero: 90 fesetround(FE_TOWARDZERO); 91 break; 92 case RoundingMode::Up: 93 fesetround(FE_UPWARD); 94 break; 95 case RoundingMode::Down: 96 fesetround(FE_DOWNWARD); 97 break; 98 case RoundingMode::TiesAwayFromZero: 99 std::fprintf(stderr, "SetRounding: TiesAwayFromZero not available"); 100 std::abort(); 101 break; 102 } 103 } 104