dotnet/runtime

JIT doesn't fold constant multiplication to single instruction

Open

#91.824 geöffnet am 8. Sept. 2023

Auf GitHub ansehen
 (5 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)C# (5.445 Forks)batch import
Priority:3area-CodeGen-coreclrhelp wantedtenet-performance

Repository-Metriken

Stars
 (17.886 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 12T 11h) (661 gemergte PRs in 30 T)

Beschreibung

Description

Consider the following code:

int A(int i)
{
    return i * 4 * 8;
}

int B(int i)
{
    return i * (4 * 8);
}

These two functions should result in identical results.

But the JIT output slightly different code for each:

Program.<<Main>$>g__A|0_0(Int32)
    L0000: mov eax, ecx
    L0002: shl eax, 2
    L0005: shl eax, 3
    L0008: ret

Program.<<Main>$>g__B|0_1(Int32)
    L0000: mov eax, ecx
    L0002: shl eax, 5
    L0005: ret

This is on: ; Core CLR 7.0.823.31807 on x64

Analysis

Given that multiplication is communicative, and that this is a power of two operation, I would expect the JIT to fold them to the 2nd version, without the parenthesis.

The first version takes two instructions instead of 1.

Contributor Guide