This is an archive of the discontinued LLVM Phabricator instance.

[ValueTracking] recognize sub X, (X -nsw Y) as not overflowing
ClosedPublic

Authored by spatel on Jun 14 2022, 8:41 AM.

Details

Summary

This extends a similar pattern from D125500. If we know that operand 1 of a subtract is itself a non-overflowing subtract from operand 0, then the final/outer subtract is also non-overflowing:
https://alive2.llvm.org/ce/z/Bqan8v

InstCombine uses this analysis to trigger a narrowing optimization, so that is what the first changed test shows.

The last test models the motivating case from issue #48013. In that example, we determine 'nsw' on the first sub from the srem, then we determine that the 2nd sub can be narrowed, and that leads to eliminating both subtracts.

This works for unsigned sub too, but I left that out to keep the patch minimal. If this looks ok, I will follow up with that change. There are also several missing subtract narrowing optimizations demonstrated in the tests above the diffs shown here - those should be handled in InstCombine with another set of patches.

Diff Detail

Event Timeline

spatel created this revision.Jun 14 2022, 8:41 AM
Herald added a project: Restricted Project. · View Herald TranscriptJun 14 2022, 8:41 AM
spatel requested review of this revision.Jun 14 2022, 8:41 AM
Herald added a project: Restricted Project. · View Herald TranscriptJun 14 2022, 8:41 AM
nikic accepted this revision.Jun 14 2022, 9:10 AM

LGTM

This revision is now accepted and ready to land.Jun 14 2022, 9:10 AM
This revision was landed with ongoing or failed builds.Jun 14 2022, 11:53 AM
This revision was automatically updated to reflect the committed changes.