[flang-commits] [flang] [flang][runtime] Add special-case faster path to real MOD/MODULO (PR #79625)

Peter Klausler via flang-commits flang-commits at lists.llvm.org
Fri Jan 26 09:50:10 PST 2024


https://github.com/klausler created https://github.com/llvm/llvm-project/pull/79625

When a real-valued reference to the MOD/MODULO intrinsic functions has operands that are exact integers, use the fast exact integer algorithm rather than calling std::fmod.

>From 12214599bd252ac354ee1f31e638805df6df9fa0 Mon Sep 17 00:00:00 2001
From: Peter Klausler <pklausler at nvidia.com>
Date: Fri, 26 Jan 2024 09:44:32 -0800
Subject: [PATCH] [flang][runtime] Add special-case faster path to real
 MOD/MODULO

When a real-valued reference to the MOD/MODULO intrinsic functions
has operands that are exact integers, use the fast exact integer
algorithm rather than calling std::fmod.
---
 flang/runtime/numeric.cpp | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/flang/runtime/numeric.cpp b/flang/runtime/numeric.cpp
index df73502bee5fed0..8e512aff1ea1d36 100644
--- a/flang/runtime/numeric.cpp
+++ b/flang/runtime/numeric.cpp
@@ -144,7 +144,18 @@ inline RT_API_ATTRS T RealMod(
     return std::numeric_limits<T>::quiet_NaN();
   } else if (std::isinf(p)) {
     return a;
-  } else if constexpr (std::is_same_v<T, float> || std::is_same_v<T, double> ||
+  }
+  if (auto aInt{static_cast<std::int64_t>(a)}; a == aInt) {
+    if (auto pInt{static_cast<std::int64_t>(p)}; p == pInt) {
+      // Fast exact case for integer operands
+      auto mod{aInt - (aInt / pInt) * pInt};
+      if (IS_MODULO && (aInt > 0) != (pInt > 0)) {
+        mod += pInt;
+      }
+      return static_cast<T>(mod);
+    }
+  }
+  if constexpr (std::is_same_v<T, float> || std::is_same_v<T, double> ||
       std::is_same_v<T, long double>) {
     // std::fmod() semantics on signed operands seems to match
     // the requirements of MOD().  MODULO() needs adjustment.



More information about the flang-commits mailing list