[flang-commits] [PATCH] D109922: [flang] Correct overflow detection in folding of real->integer conversions

Peter Klausler via Phabricator via flang-commits flang-commits at lists.llvm.org
Thu Sep 16 13:45:20 PDT 2021


klausler created this revision.
klausler added a reviewer: jeanPerier.
klausler requested review of this revision.

INT, NINT, FLOOR, and CEILING were failing to report overflow as an
error while folding operations with constant operands.


https://reviews.llvm.org/D109922

Files:
  flang/include/flang/Evaluate/real.h


Index: flang/include/flang/Evaluate/real.h
===================================================================
--- flang/include/flang/Evaluate/real.h
+++ flang/include/flang/Evaluate/real.h
@@ -221,21 +221,26 @@
       return result;
     }
     ValueWithRealFlags<Real> intPart{ToWholeNumber(mode)};
-    int exponent{intPart.value.Exponent()};
-    result.flags.set(
-        RealFlag::Overflow, exponent >= exponentBias + result.value.bits);
     result.flags |= intPart.flags;
-    int shift{
-        exponent - exponentBias - binaryPrecision + 1}; // positive -> left
-    result.value =
-        result.value.ConvertUnsigned(intPart.value.GetFraction().SHIFTR(-shift))
-            .value.SHIFTL(shift);
+    int exponent{intPart.value.Exponent()};
+    // shift positive -> left shift, negative -> right shift
+    int shift{exponent - exponentBias - binaryPrecision + 1};
+    // Apply any right shift before moving to the result type
+    auto rshifted{intPart.value.GetFraction().SHIFTR(-shift)};
+    auto converted{result.value.ConvertUnsigned(rshifted)};
+    if (converted.overflow) {
+      result.flags.set(RealFlag::Overflow);
+    }
+    result.value = converted.value.SHIFTL(shift);
+    if (converted.value.CompareUnsigned(result.value.SHIFTR(shift)) !=
+        Ordering::Equal) {
+      result.flags.set(RealFlag::Overflow);
+    }
     if (IsSignBitSet()) {
-      auto negated{result.value.Negate()};
-      result.value = negated.value;
-      if (negated.overflow) {
-        result.flags.set(RealFlag::Overflow);
-      }
+      result.value = result.value.Negate().value;
+    }
+    if (IsSignBitSet() != result.value.IsNegative()) {
+      result.flags.set(RealFlag::Overflow);
     }
     if (result.flags.test(RealFlag::Overflow)) {
       result.value =


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D109922.373058.patch
Type: text/x-patch
Size: 1789 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/flang-commits/attachments/20210916/cb47c91b/attachment-0001.bin>


More information about the flang-commits mailing list