@@ -2002,26 +2002,29 @@ Value *InstCombinerImpl::OptimizePointerDifference(Value *LHS, Value *RHS,
20022002 return nullptr ;
20032003
20042004 // 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.
20062007 // TODO: We should probably do this even if there is only one GEP.
20072008 bool RewriteGEPs = GEP2 != nullptr ;
20082009
20092010 // Emit the offset of the GEP and an intptr_t.
2011+ bool GEP1IsInBounds = GEP1->isInBounds ();
20102012 Value *Result = EmitGEPOffset (GEP1, RewriteGEPs);
20112013
20122014 // If this is a single inbounds GEP and the original sub was nuw,
20132015 // then the final multiplication is also nuw.
20142016 if (auto *I = dyn_cast<Instruction>(Result))
2015- if (IsNUW && !GEP2 && !Swapped && GEP1-> isInBounds () &&
2017+ if (IsNUW && !GEP2 && !Swapped && GEP1IsInBounds &&
20162018 I->getOpcode () == Instruction::Mul)
20172019 I->setHasNoUnsignedWrap ();
20182020
20192021 // If we have a 2nd GEP of the same base pointer, subtract the offsets.
20202022 // If both GEPs are inbounds, then the subtract does not have signed overflow.
20212023 if (GEP2) {
2024+ bool GEP2IsInBounds = GEP2->isInBounds ();
20222025 Value *Offset = EmitGEPOffset (GEP2, RewriteGEPs);
20232026 Result = Builder.CreateSub (Result, Offset, " gepdiff" , /* NUW */ false ,
2024- GEP1-> isInBounds () && GEP2-> isInBounds () );
2027+ GEP1IsInBounds && GEP2IsInBounds );
20252028 }
20262029
20272030 // If we have p - gep(p, ...) then we have to negate the result.
0 commit comments