Skip to content

[JIT] X64 - Recognize patterns to emit bts, btc, btr instructions #81512

Description

@TIHan

@tannergooding and I were having a discussion and these examples were brought up.

public class C {
    static uint SetBit(int position, uint bits)
    {
        return bits | (1u << position);
    }

    static uint ToggleBit(int position, uint bits)
    {
        return bits ^ (1u << position);
    }

    static uint ResetBit(int position, uint bits)
    {
        return bits & ~(1u << position);
    }
}

These examples currently emit:

C.SetBit(Int32, UInt32)
    L0000: mov eax, 1
    L0005: shlx eax, eax, ecx
    L000a: or eax, edx
    L000c: ret

C.ToggleBit(Int32, UInt32)
    L0000: mov eax, 1
    L0005: shlx eax, eax, ecx
    L000a: xor eax, edx
    L000c: ret

C.ResetBit(Int32, UInt32)
    L0000: mov eax, 1
    L0005: shlx eax, eax, ecx
    L000a: andn eax, eax, edx
    L000f: ret

They could emit:

SetBit(int, unsigned int):                            # @SetBit(int, unsigned int)
        mov     eax, ecx
        bts     eax, edx
        ret
ToggleBit(int, unsigned int):                         # @ToggleBit(int, unsigned int)
        mov     eax, ecx
        btc     eax, edx
        ret
ResetBit(int, unsigned int):                          # @ResetBit(int, unsigned int)
        mov     eax, ecx
        btr     eax, edx
        ret

In XARCH LIR, we have a GT_BT already, we can just add three more GT_BTS, GT_BTC, GT_BTR and recognize the patterns above to transform to those ops in lowering.

Related: #27382

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIin-prThere is an active PR which will close this issue when it is mergedtenet-performancePerformance related issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions