Runtime: JIT: Optimize boxing(x) == boxing(y) to false.

Created on 23 Nov 2019  ·  3Comments  ·  Source: dotnet/runtime

static bool Generic<T1, T2>(T1 a, T2 b)
{
    return (object)a == (object)b;
}

static bool Test()
{
    return Generic(42, 3.14);
}

Codegen for Test:

; Method Program:Test():bool
G_M11853_IG01:
       push     rsi
       sub      rsp, 32
       vzeroupper 
G_M11853_IG02:
       mov      rcx, 0xD1FFAB1E
       call     CORINFO_HELP_NEWSFAST
       mov      rsi, rax
       mov      dword ptr [rsi+8], 42
       mov      rcx, 0xD1FFAB1E
       call     CORINFO_HELP_NEWSFAST
       vmovsd   xmm0, qword ptr [reloc @RWD00]
       vmovsd   qword ptr [rax+8], xmm0
       cmp      rsi, rax
       sete     al
       movzx    rax, al
G_M11853_IG03:
       add      rsp, 32
       pop      rsi
       ret      
RWD00  dq   40091EB851EB851Fh

```
--* EQ\NE int
+--* BOX ref
| --* LCL_VAR ref V03 tmp1
--* BOX ref
--* LCL_VAR ref V04 tmp2

Expected codegen:
```asm
; Method Program:Test():bool
       xor      eax, eax  ; return false 
       ret     

Not sure if people actually use this pattern though. But should be a simple fix because CoreCLR already optimizes boxing for similar cases (e.g. boxing(x) == null to false etc, see https://github.com/mono/mono/issues/17858 for links).

category:cq
theme:optimization
skill-level:intermediate
cost:medium

area-CodeGen-coreclr optimization

Most helpful comment

@jkotas I made a quick prototype and the jit-diff found a few kb diff for BCL, e.g. https://github.com/dotnet/corefx/blob/master/src/System.Data.Common/src/System/Data/RbTree.cs#L1581

UPD: well, it seems it's pmi was ddosing it and won't happen in real world.

All 3 comments

Not sure if people actually use this pattern though

There is no point for adding optimizations for patterns than never show up in real world code....

@jkotas I made a quick prototype and the jit-diff found a few kb diff for BCL, e.g. https://github.com/dotnet/corefx/blob/master/src/System.Data.Common/src/System/Data/RbTree.cs#L1581

UPD: well, it seems it's pmi was ddosing it and won't happen in real world.

Given the expectation that this doesn't occur in real-world code, I'm going to close this until we see a real-world motivating example.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yahorsi picture yahorsi  ·  3Comments

jchannon picture jchannon  ·  3Comments

GitAntoinee picture GitAntoinee  ·  3Comments

btecu picture btecu  ·  3Comments

bencz picture bencz  ·  3Comments