Skip to content

Commit 66ed8fb

Browse files
committed
[InstCombine] Fix use after free
Make sure we only access cached nowrap flags.
1 parent b79007d commit 66ed8fb

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2092,30 +2092,31 @@ Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
20922092

20932093
// To avoid duplicating the offset arithmetic, rewrite the GEP to use the
20942094
// computed offset. This may erase the original GEP, so be sure to cache the
2095-
// inbounds flag before emitting the offset.
2095+
// nowrap flags before emitting the offset.
20962096
// TODO: We should probably do this even if there is only one GEP.
20972097
bool RewriteGEPs = GEP2 != nullptr;
20982098

20992099
// Emit the offset of the GEP and an intptr_t.
2100-
bool GEP1IsInBounds = GEP1->isInBounds();
2100+
GEPNoWrapFlags GEP1NW = GEP1->getNoWrapFlags();
21012101
Value *Result = EmitGEPOffset(GEP1, RewriteGEPs);
21022102

21032103
// If this is a single inbounds GEP and the original sub was nuw,
21042104
// then the final multiplication is also nuw.
21052105
if (auto *I = dyn_cast<Instruction>(Result))
2106-
if (IsNUW && !GEP2 && !Swapped && GEP1IsInBounds &&
2106+
if (IsNUW && !GEP2 && !Swapped && GEP1NW.isInBounds() &&
21072107
I->getOpcode() == Instruction::Mul)
21082108
I->setHasNoUnsignedWrap();
21092109

21102110
// If we have a 2nd GEP of the same base pointer, subtract the offsets.
21112111
// If both GEPs are inbounds, then the subtract does not have signed overflow.
21122112
// If both GEPs are nuw and the original sub is nuw, the new sub is also nuw.
21132113
if (GEP2) {
2114+
GEPNoWrapFlags GEP2NW = GEP2->getNoWrapFlags();
21142115
Value *Offset = EmitGEPOffset(GEP2, RewriteGEPs);
21152116
Result = Builder.CreateSub(Result, Offset, "gepdiff",
2116-
IsNUW && GEP1->hasNoUnsignedWrap() &&
2117-
GEP2->hasNoUnsignedWrap(),
2118-
GEP1IsInBounds && GEP2->isInBounds());
2117+
IsNUW && GEP1NW.hasNoUnsignedWrap() &&
2118+
GEP2NW.hasNoUnsignedWrap(),
2119+
GEP1NW.isInBounds() && GEP2NW.isInBounds());
21192120
}
21202121

21212122
// If we have p - gep(p, ...) then we have to negate the result.

0 commit comments

Comments
 (0)