Index: llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp =================================================================== --- llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp +++ llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp @@ -238,6 +238,9 @@ // `sub` is always negatible. // However, only do this either if the old `sub` doesn't stick around, or // it was subtracting from a constant. Otherwise, this isn't profitable. + if (I->hasNoSignedWrap()) + return Builder.CreateNSWSub(I->getOperand(1), I->getOperand(0), + I->getName() + ".neg"); return Builder.CreateSub(I->getOperand(1), I->getOperand(0), I->getName() + ".neg"); } Index: llvm/test/Transforms/InstCombine/nsw.ll =================================================================== --- llvm/test/Transforms/InstCombine/nsw.ll +++ llvm/test/Transforms/InstCombine/nsw.ll @@ -140,3 +140,23 @@ %t3 = mul %shuf, %xx ret %t3 } + +define i32 @neg_sub_nsw(i32 %a, i32 %b) { +; CHECK-LABEL: @neg_sub_nsw( +; CHECK-NEXT: [[C_NEG:%.*]] = sub nsw i32 [[B:%.*]], [[A:%.*]] +; CHECK-NEXT: ret i32 [[C_NEG]] +; + %c = sub nsw i32 %a, %b + %d = sub i32 0, %c + ret i32 %d +} + +define i32 @neg_sub(i32 %a, i32 %b) { +; CHECK-LABEL: @neg_sub( +; CHECK-NEXT: [[C_NEG:%.*]] = sub i32 [[B:%.*]], [[A:%.*]] +; CHECK-NEXT: ret i32 [[C_NEG]] +; + %c = sub i32 %a, %b + %d = sub i32 0, %c + ret i32 %d +}