JIT: CSE doesn't consider two comparisons with swapped operands equal

Open
#138,063 2 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
54/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
csharp
Domain
performance

Research direction

Start with the JIT common subexpression elimination logic and its tests; the issue does not name specific files or test entry points. Compare how the JIT represents a < b and b > a, then check whether equivalent comparisons are reused. Done means the swapped-operand case produces one comparison, with a regression test covering both forms.

Written by the indexing model from the issue text.

Description

area-CodeGen-coreclr untriaged

https://godbolt.org/z/TffET5sK4

Consider:

static void Good(int a, int b, bool* mem)
{
    // Successfully CSE'd!
    mem[0] = a < b;
    mem[1] = a < b;
}
Program:Good(int,int,ptr) (FullOpts):
       cmp      edi, esi
       setl     al
       movzx    eax, al
       mov      byte  ptr [rdx], al
       mov      byte  ptr [rdx+0x01], al
       ret      

Now, let's swap the operands. CSE no longer recognizes them as equal.

static void Failed(int a, int b, bool* mem)
{
    mem[0] = a < b;
    mem[1] = b > a;
}
Program:Failed(int,int,ptr) (FullOpts):
       cmp      edi, esi
       setl     al
       mov      byte  ptr [rdx], al
       cmp      esi, edi
       setg     al
       mov      byte  ptr [rdx+0x01], al
       ret      
Dominant language
C#
Stars
18.5k
Forks
5.8k
Avg merge
2d 18h
Merged PRs (30d)
588

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.