[flang-commits] [flang] [flang] Do not invoke undefined behaviour when parsing format expressions (PR #147539)

David Spickett via flang-commits flang-commits at lists.llvm.org
Tue Jul 8 07:42:30 PDT 2025


================
@@ -214,16 +215,18 @@ template <typename CHAR> void FormatValidator<CHAR>::NextToken() {
   case '7':
   case '8':
   case '9': {
-    int64_t lastValue;
     const CHAR *lastCursor;
     integerValue_ = 0;
     bool overflow{false};
     do {
-      lastValue = integerValue_;
       lastCursor = cursor_;
-      integerValue_ = 10 * integerValue_ + c - '0';
-      if (lastValue > integerValue_) {
-        overflow = true;
+      if (LLVM_LIKELY(!overflow)) {
+        overflow = llvm::MulOverflow(
+            static_cast<int64_t>(10), integerValue_, integerValue_);
+      }
+      if (LLVM_LIKELY(!overflow)) {
+        overflow = llvm::AddOverflow(
+            integerValue_, static_cast<int64_t>(c - '0'), integerValue_);
----------------
DavidSpickett wrote:

You could write this as `if (overflow = MulOverflow(...); !overflow) { overflow =`, or `overflow = MulOverflow(...) || AddOverflow`.

However when I tried those I forgot that we actually want to latch overflow, if its ever set to true it must stay true. So I think this multiple if is cumbersome but the most clear way to write it.

https://github.com/llvm/llvm-project/pull/147539


More information about the flang-commits mailing list