This is an archive of the discontinued LLVM Phabricator instance.

[InstCombine] convert mul by negative-pow2 to negate and shift
ClosedPublic

Authored by spatel on Sep 11 2022, 5:26 AM.

Details

Summary

This is an unusual canonicalization because we create an extra instruction, but it's very likely better for analysis and codegen (similar reasoning as D133399).

InstCombine::Negator aggressively creates this kind of multiply from subtract and shift, so this is partly reversing a transform in the motivating case from issue #57576.

We may want to limit Negator more to prevent creating multiplies like this. We've seen regressions from that, but no wins AFAIK.

I don't know how to create a fully general proof for this kind of transform in Alive2, but here's an example with bitwidths similar to one of the regression tests:
https://alive2.llvm.org/ce/z/J3jTjR

Diff Detail

Event Timeline

spatel created this revision.Sep 11 2022, 5:26 AM
Herald added a project: Restricted Project. · View Herald TranscriptSep 11 2022, 5:26 AM
spatel requested review of this revision.Sep 11 2022, 5:26 AM
Herald added a project: Restricted Project. · View Herald TranscriptSep 11 2022, 5:26 AM
spatel updated this revision to Diff 460117.Sep 14 2022, 11:06 AM

Patch updated:
No code changes, but rebased after:
73919a87e9a6f8cfa6
...so the motivating test is reduced to remove the multiply and a wide add. We need some other fold to recognize that the wide sub can be narrowed.

RKSimon accepted this revision.Sep 20 2022, 9:46 AM

No objections, but I'm a little worried that the negator will put up a fight and convert this back again.....

This revision is now accepted and ready to land.Sep 20 2022, 9:46 AM

No objections, but I'm a little worried that the negator will put up a fight and convert this back again.....

Yes - I want to believe that the zext protects us from getting into an infinite loop (we shouldn't widen the sub unless it allows removing some other instructions), but it's hard to guarantee that there isn't some loophole.

Can we revert the problematic negator change first?

Can we revert the problematic negator change first?

Yes. There doesn't appear to be any fallout based on regression tests, but I'd do that in 2 pieces to reduce risk. Step 1 would be:
D134310

spatel added a comment.Oct 2 2022, 9:20 AM

We inverted the general negator transform with:
ee0bf6472291
...and I haven't seen any complaints after ~10 days. That also partly resolved the diff for issue #57576. This patch still reduces the IR in that example without changing codegen.

Negator will still create a mul from a shl+negate, but it's less likely that we'll conflict with the proposal here, so I think it's safe to give this a try now.