[llvm] d26002a - [InstCombine] Fix use-after-free in OptimizePointerDifference()

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Thu Apr 25 20:05:22 PDT 2024


Author: Nikita Popov
Date: 2024-04-26T12:05:12+09:00
New Revision: d26002ac38ee1dea32053e7d12f1bb5dc420ac2d

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

LOG: [InstCombine] Fix use-after-free in OptimizePointerDifference()

EmitGEPOffset() may remove the old GEP, so be sure to cache the
inbounds flag beforehand.

Added: 
    

Modified: 
    llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
index a3775fa6f3693e..51ac77348ed9e3 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
@@ -2002,26 +2002,29 @@ Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
     return nullptr;
 
   // To avoid duplicating the offset arithmetic, rewrite the GEP to use the
-  // computed offset.
+  // computed offset. This may erase the original GEP, so be sure to cache the
+  // inbounds flag before emitting the offset.
   // TODO: We should probably do this even if there is only one GEP.
   bool RewriteGEPs = GEP2 != nullptr;
 
   // Emit the offset of the GEP and an intptr_t.
+  bool GEP1IsInBounds = GEP1->isInBounds();
   Value *Result = EmitGEPOffset(GEP1, RewriteGEPs);
 
   // If this is a single inbounds GEP and the original sub was nuw,
   // then the final multiplication is also nuw.
   if (auto *I = dyn_cast<Instruction>(Result))
-    if (IsNUW && !GEP2 && !Swapped && GEP1->isInBounds() &&
+    if (IsNUW && !GEP2 && !Swapped && GEP1IsInBounds &&
         I->getOpcode() == Instruction::Mul)
       I->setHasNoUnsignedWrap();
 
   // If we have a 2nd GEP of the same base pointer, subtract the offsets.
   // If both GEPs are inbounds, then the subtract does not have signed overflow.
   if (GEP2) {
+    bool GEP2IsInBounds = GEP2->isInBounds();
     Value *Offset = EmitGEPOffset(GEP2, RewriteGEPs);
     Result = Builder.CreateSub(Result, Offset, "gep
diff ", /* NUW */ false,
-                               GEP1->isInBounds() && GEP2->isInBounds());
+                               GEP1IsInBounds && GEP2IsInBounds);
   }
 
   // If we have p - gep(p, ...)  then we have to negate the result.


        


More information about the llvm-commits mailing list