dotnet / dotnet/runtime

JIT: A case of needing `JitOptRepeat=3` for constant folding and conditional move

Open
#124,700 7 comments 0 reactions 0 assignees View on GitHub
area-CodeGen-coreclr help wanted optimization
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

Consider this (https://godbolt.org/z/7b4qsdKTa):
```cs
static int Unoptimized(int a, int b)
{
int num = 0;

if (a == b)
{
num += 3;
}
if (a == b)
{
num++;
}
if (a == b)
{
num++;
}

return num;
}
```
which compiles into:
```assembly
G_M13546_IG02: ;; offset=0x0000
xor eax, eax
cmp ecx, edx
jne SHORT G_M13546_IG04
;; size=6 bbWeight=1 PerfScore 1.50

G_M13546_IG03: ;; offset=0x0006
mov eax, 3
inc eax
inc eax
;; size=9 bbWeight=0.50 PerfScore 0.38
```
As can be seen the `mov + inc + inc` chain is not constant folded. Having `JitOptRepeat=2` fixes that:
```assembly
G_M13546_IG02: ;; offset=0x0000
xor eax, eax
cmp ecx, edx
jne SHORT G_M13546_IG04
;; size=6 bbWeight=1 PerfScore 1.50

G_M13546_IG03: ;; offset=0x0006
mov eax, 5
;; size=5 bbWeight=0.50 PerfScore 0.12
```
However, there is still a jump. To get a conditional move we need `JitOptRepeat=3`:
```assembly
G_M13546_IG02: ;; offset=0x0000
xor eax, eax
mov r8d, 5
cmp ecx, edx
cmove eax, r8d
;; size=14 bbWeight=1 PerfScore 1.00
```

The codegen is now equivalent to `return (a == b) ? 5 : 0;`

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.