[llvm] 0996791 - [CodeGenPrepare] Fix signed overflow (#141487)

via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 3 00:27:28 PDT 2025


Author: mikael-nilsson-arm
Date: 2025-06-03T09:27:25+02:00
New Revision: 09967917e72a3c8f02138cc0906644c0db719fbc

URL: https://github.com/llvm/llvm-project/commit/09967917e72a3c8f02138cc0906644c0db719fbc
DIFF: https://github.com/llvm/llvm-project/commit/09967917e72a3c8f02138cc0906644c0db719fbc.diff

LOG: [CodeGenPrepare] Fix signed overflow (#141487)

The signed addition could overflow which is undefined behavior, now the
code checks for it.

Added: 
    

Modified: 
    llvm/lib/CodeGen/CodeGenPrepare.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp
index 52263026d6cea..822ed6283117c 100644
--- a/llvm/lib/CodeGen/CodeGenPrepare.cpp
+++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp
@@ -5447,11 +5447,17 @@ bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
       TPT.getRestorationPoint();
   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
     if (CI->getValue().isSignedIntN(64)) {
-      // Fold in immediates if legal for the target.
-      AddrMode.BaseOffs += CI->getSExtValue();
-      if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
-        return true;
-      AddrMode.BaseOffs -= CI->getSExtValue();
+      // Check if the addition would result in a signed overflow.
+      int64_t Result;
+      bool Overflow =
+          AddOverflow(AddrMode.BaseOffs, CI->getSExtValue(), Result);
+      if (!Overflow) {
+        // Fold in immediates if legal for the target.
+        AddrMode.BaseOffs = Result;
+        if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
+          return true;
+        AddrMode.BaseOffs -= CI->getSExtValue();
+      }
     }
   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
     // If this is a global variable, try to fold it into the addressing mode.


        


More information about the llvm-commits mailing list