dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
14.95k stars 4.65k forks source link

Avoid duplicating comparison instructions when it can be solved by just reordering the flag-setting instructions #105065

Open MineCake147E opened 1 month ago

MineCake147E commented 1 month ago

Description

When I was investigating the codegen of the method:

public static int C(int x, int y)
{
    var g = x > y ? 1 : 0;
    var l = x < y ? 1 : 0;
    return g - l;
}

The codegen looked like this:

xor eax, eax
cmp ecx, edx
setg al
setl cl
movzx ecx, cl
sub eax, ecx
ret

But when it's called multiple times in a single function, comparison instructions often gets duplicated like:

xor ecx, ecx
cmp eax, r8d
setg cl
xor r14d, r14d
cmp eax, r8d
setl r14b
sub ecx, r14d

cmp eax, r8d seems to be duplicated as xor r14d, r14d modifies the flag register. It should be better relocating the xor r14d, r14d before the cmp eax, r8d, like:

xor ecx, ecx
xor r14d, r14d
cmp eax, r8d
setg cl
setl r14b
sub ecx, r14d

Which should save an ALU executing it.

Configuration

SharpLab

Regression?

No

Data

Analysis

dotnet-policy-service[bot] commented 1 month ago

Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch See info in area-owners.md if you want to be subscribed.