dotnet / dotnet/runtime

JIT: Two ways of writing the same conditional logic differ in codegen quality

Open
#120,424 3 comments 1 reaction 0 assignees View on GitHub
area-CodeGen-coreclr
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

I would expect `TestOptimal` and `Test` to compile to the same, yet the later has worse codegen.
https://godbolt.org/z/a77nY1oc4
```cs
void TestOptimal(bool fullyLeft, bool fullyRight, ref int rightCounter)
{
if (fullyRight || !fullyLeft)
{
rightCounter++;
}
}

void Test(bool fullyLeft, bool fullyRight, ref int rightCounter)
{
bool isStraddling = !fullyLeft && !fullyRight;
if (fullyRight)
{
rightCounter++;
}
else if (isStraddling)
{
rightCounter++;
}
}
```
```assembly
Program:TestOptimal(bool,bool,byref):this (FullOpts):
push rbp
mov rbp, rsp
test dl, dl
jne SHORT G_M14327_IG04
test sil, sil
jne SHORT G_M14327_IG05
G_M14327_IG04: ;; offset=0x000D
inc dword ptr [rcx]
G_M14327_IG05: ;; offset=0x000F
pop rbp
ret

Program:Test(bool,bool,byref):this (FullOpts):
push rbp
mov rbp, rsp
test sil, sil
je SHORT G_M22421_IG04
xor eax, eax
jmp SHORT G_M22421_IG05
G_M22421_IG04: ;; offset=0x000D
test dl, dl
sete al
movzx rax, al
G_M22421_IG05: ;; offset=0x0015
movzx rdx, dl
or eax, edx
jne SHORT G_M22421_IG07
G_M22421_IG06: ;; offset=0x001C
pop rbp
ret
G_M22421_IG07: ;; offset=0x001E
inc dword ptr [rcx]
jmp SHORT G_M22421_IG06
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.