@@ -2002,26 +2002,29 @@ Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
2002
2002
return nullptr ;
2003
2003
2004
2004
// To avoid duplicating the offset arithmetic, rewrite the GEP to use the
2005
- // computed offset.
2005
+ // computed offset. This may erase the original GEP, so be sure to cache the
2006
+ // inbounds flag before emitting the offset.
2006
2007
// TODO: We should probably do this even if there is only one GEP.
2007
2008
bool RewriteGEPs = GEP2 != nullptr ;
2008
2009
2009
2010
// Emit the offset of the GEP and an intptr_t.
2011
+ bool GEP1IsInBounds = GEP1->isInBounds ();
2010
2012
Value *Result = EmitGEPOffset (GEP1, RewriteGEPs);
2011
2013
2012
2014
// If this is a single inbounds GEP and the original sub was nuw,
2013
2015
// then the final multiplication is also nuw.
2014
2016
if (auto *I = dyn_cast<Instruction>(Result))
2015
- if (IsNUW && !GEP2 && !Swapped && GEP1-> isInBounds () &&
2017
+ if (IsNUW && !GEP2 && !Swapped && GEP1IsInBounds &&
2016
2018
I->getOpcode () == Instruction::Mul)
2017
2019
I->setHasNoUnsignedWrap ();
2018
2020
2019
2021
// If we have a 2nd GEP of the same base pointer, subtract the offsets.
2020
2022
// If both GEPs are inbounds, then the subtract does not have signed overflow.
2021
2023
if (GEP2) {
2024
+ bool GEP2IsInBounds = GEP2->isInBounds ();
2022
2025
Value *Offset = EmitGEPOffset (GEP2, RewriteGEPs);
2023
2026
Result = Builder.CreateSub (Result, Offset, " gepdiff" , /* NUW */ false ,
2024
- GEP1-> isInBounds () && GEP2-> isInBounds () );
2027
+ GEP1IsInBounds && GEP2IsInBounds );
2025
2028
}
2026
2029
2027
2030
// If we have p - gep(p, ...) then we have to negate the result.
0 commit comments