Skip to content

Optimize boxing for pattern matching #1795

@EgorBo

Description

@EgorBo
int Test<T>(T obj)
{
    if (obj is int x)
        return x;
    return 0;
}

For int as T I expect this method to be just return obj, but instead I see:

    L0000: push rsi
    L0001: sub rsp, 0x20
    L0005: mov esi, ecx
    L0007: mov rcx, 0x7ffec353b1e8
    L0011: call 0x7fff23084690
    L0016: mov [rax+0x8], esi
    L0019: mov eax, [rax+0x8]
    L001c: add rsp, 0x20
    L0020: pop rsi
    L0021: ret

see sharplab.io

JIT already optimizes some patterns, e.g.

box
isinst
brtrue

but it doesn't optimize this (correct me if I am wrong)

box
isinst 
unbox.any

See

case CEE_ISINST:
// box + isinst + br_true/false
if (codeAddr + 1 + sizeof(mdToken) + 1 <= codeEndp)
{
const BYTE* nextCodeAddr = codeAddr + 1 + sizeof(mdToken);
switch (nextCodeAddr[0])
{
case CEE_BRTRUE:
case CEE_BRTRUE_S:
case CEE_BRFALSE:
case CEE_BRFALSE_S:
(I guess that switch should also handle CEE_UNBOX_ANY)

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions