This is an archive of the discontinued LLVM Phabricator instance.

[InstCombine] try to fold rem with constant dividend and select-of-constants divisor
ClosedPublic

Authored by spatel on Dec 6 2021, 11:26 AM.

Details

Summary

We avoid this fold in the more general cases where we use FoldOpIntoSelect. That's because -- unlike most binary opcodes -- 'rem' can't usually be speculated with a variable divisor since it can have immediate UB. But in the case where both arms of the select are constants, we can safely evaluate both sides and eliminate 'rem' completely.

This should fix:
https://llvm.org/PR52102

I think we have the same optimization gap for 'div', but I need to add/run tests to make sure, so I'll do that as a follow-up if this is ok. We already handle the case where the dividend is a select and the divisor is constant - that's just above the diff in this patch.

Diff Detail

Event Timeline

spatel created this revision.Dec 6 2021, 11:26 AM
spatel requested review of this revision.Dec 6 2021, 11:26 AM
Herald added a project: Restricted Project. · View Herald TranscriptDec 6 2021, 11:26 AM

Seems reasonable to me, Roman and Nikita are more active in InstCombine then I am lately so I'll let them look too.

Note: I drafted the equivalent patch for div opcodes, and it's exactly the same code/tests with s/rem/div/. No existing regression tests are affected.

lebedev.ri accepted this revision.Dec 7 2021, 11:44 AM

Could you please add this test: https://godbolt.org/z/WvYxnejnc (it should not optimize to unreachable/undef/poison)

LGTM, but this reminds me of D71561 that got stuck (sorry, that was not my intention),
similar generalization could be applied here i believe.

This revision is now accepted and ready to land.Dec 7 2021, 11:44 AM

Could you please add this test: https://godbolt.org/z/WvYxnejnc (it should not optimize to unreachable/undef/poison)

Sure - added "0 select arm" tests for all 4 opcodes:
51d3cb0ab15d

LGTM, but this reminds me of D71561 that got stuck (sorry, that was not my intention),
similar generalization could be applied here i believe.

I forgot about that patch...will try to revisit if I have time.

This revision was landed with ongoing or failed builds.Dec 7 2021, 12:51 PM
This revision was automatically updated to reflect the committed changes.