This is an archive of the discontinued LLVM Phabricator instance.

[X86] Prevent infinite loop in SelectionDAG when lowering negations
ClosedPublic

Authored by momo5502 on Jul 6 2023, 12:39 AM.

Details

Summary

In certain cases, lowering negations can cause an infinite loop in SelectionDAG on X86.

The following snippet shows that behaviour:
https://godbolt.org/z/5hP45T4hY

What happens is that ADD(XOR(..., -1), 1) is detected as the two's complement and transformed into SUB(0, ...)
However, immediates can not be encoded as the LHS of a SUB on X86.
Therefore it is transformed back into an ADD/XOR pair, which is then again transformed into a SUB and so on.

In that specific case, I still think it is valid to display this as a SUB(0,...) , because it should eventually be lowered as a NEG.
Which seems better than an ADD/XOR pair.

Adding an exception to the X86 specific handling for SUBs with 0 LHS operand fixes this infinite loop.

Diff Detail

Event Timeline

momo5502 created this revision.Jul 6 2023, 12:39 AM
Herald added a project: Restricted Project. · View Herald TranscriptJul 6 2023, 12:39 AM
momo5502 requested review of this revision.Jul 6 2023, 12:39 AM
Herald added a project: Restricted Project. · View Herald TranscriptJul 6 2023, 12:39 AM
RKSimon added inline comments.Jul 6 2023, 3:41 AM
llvm/test/CodeGen/X86/select-neg.ll
17

Can this not be reduced any further?

momo5502 added inline comments.Jul 6 2023, 4:17 AM
llvm/test/CodeGen/X86/select-neg.ll
17

I'm afraid not. The ADD and the first XOR are needed for sure.
I think the second XOR and the PtrToInt is needed as that bug only gets triggered due to a reassociation step that switches the two XORs.

SelectionDAG loops between 3 states:

  1. SUB -> ADD
  2. XOR reassociation
  3. ADD -> SUB

I was not able to trigger the infinte loop without ressociation step inbetween and I was not able to trigger that reassociation without the PtrToInt.

However, I extracted and reduced that bug from a 1.5k line LL file, so I was pretty happy with a 5 instruction sample :D

RKSimon accepted this revision.Jul 6 2023, 5:04 AM

cheers - lgtm

This revision is now accepted and ready to land.Jul 6 2023, 5:04 AM
momo5502 marked an inline comment as done.Jul 6 2023, 5:13 AM

cheers - lgtm

Thank you very much. I don't have commit permissions. Can you please commit for me using the following details:
Maurice Heumann <maurice.heumann@wibu.com>

Is there anything missing for this to be committed?

Sorry @momo5502 I just missed this..... Will get it pushed later today