This is an archive of the discontinued LLVM Phabricator instance.

[InstCombine] reduce right-shift-of-left-shifted constant via demanded bits
ClosedPublic

Authored by spatel on Jun 6 2022, 8:49 AM.

Details

Summary

If we don't demand high bits (zeros) and it is valid to pre-shift a constant:
(C2 << X) >> C1 --> (C2 >> C1) << X

https://alive2.llvm.org/ce/z/P3dWDW

There are a variety of related patterns, but I haven't found a single solution that gets all of the motivating examples - so pulling this piece out of D126617 along with more tests.

We should also handle the case where we shift-right followed by shift-left, but I'll make that a follow-on patch assuming this one is ok. It seems likely that we would want to add this to the SDAG version of the code too to keep it on par with IR.

Diff Detail

Event Timeline

spatel created this revision.Jun 6 2022, 8:49 AM
Herald added a project: Restricted Project. · View Herald TranscriptJun 6 2022, 8:49 AM
spatel requested review of this revision.Jun 6 2022, 8:49 AM
Herald added a project: Restricted Project. · View Herald TranscriptJun 6 2022, 8:49 AM
spatel edited the summary of this revision. (Show Details)Jun 6 2022, 8:49 AM
RKSimon added inline comments.Jun 6 2022, 9:20 AM
llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
640

Why limit this to (scalar) constants instead of using KnownBits::countMinTrailingZeros?

spatel marked an inline comment as done.Jun 6 2022, 12:41 PM
spatel added inline comments.
llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
640

Mainly because that was always part of the motivating examples. :)

If we use known bits here, then the new lshr is potentially not constant-folded away. We could do that, but then we would need to limit the match with one-use.

I don't have a strong preference. We could make it another small follow-on if that seems like a better transform.

bcl5980 added inline comments.Jun 6 2022, 8:25 PM
llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.cpp
640

Maybe we can try to match Constant instead of APInt then computeKnownBits for it. It can help to detect vector constant also.

spatel updated this revision to Diff 434809.Jun 7 2022, 7:26 AM
spatel marked 2 inline comments as done.

Adjusted code to allow non-uniform (non-splat) vector constants on the shifted (inner) constant.

The Alive2 proof is updated to match the new logic:
https://alive2.llvm.org/ce/z/P3dWDW

spatel edited the summary of this revision. (Show Details)Jun 7 2022, 7:28 AM
bcl5980 accepted this revision.Jun 7 2022, 8:46 AM

LGTM.

This revision is now accepted and ready to land.Jun 7 2022, 8:46 AM
RKSimon accepted this revision.Jun 7 2022, 9:06 AM

LGTM - cheers

This revision was landed with ongoing or failed builds.Jun 7 2022, 10:30 AM
This revision was automatically updated to reflect the committed changes.