Index: llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp =================================================================== --- llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp +++ llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp @@ -1996,11 +1996,13 @@ // C-(X+C2) --> (C-C2)-X if (match(Op1, m_Add(m_Value(X), m_ImmConstant(C2)))) { - // c - c2 is overflow? - bool HasNSW = false; + // C-C2, C-(X+C2), (X+C2) never overflow=> (C-C2)-X never overflow BinaryOperator *Res = BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X); - Res->setHasNoSignedWrap(HasNSW); + auto *OBO1 = cast(Op1); + Res->setHasNoSignedWrap(I.hasNoSignedWrap() && + OBO1->hasNoUnsignedWrap() && + willNotOverflowSignedSub(C, C2, *Res)); return Res; } }