Skip to content

IL and asm differences from pattern matching vs comparisons #123858

@stephentoub

Description

@stephentoub

This:

        private static bool IsLetterCategory(UnicodeCategory uc)
        {
            return uc == UnicodeCategory.UppercaseLetter
                 || uc == UnicodeCategory.LowercaseLetter
                 || uc == UnicodeCategory.TitlecaseLetter
                 || uc == UnicodeCategory.ModifierLetter
                 || uc == UnicodeCategory.OtherLetter;
        }

results in this IL:

        IL_0000: ldarg.0
        IL_0001: brfalse.s IL_0014

        IL_0003: ldarg.0
        IL_0004: ldc.i4.1
        IL_0005: beq.s IL_0014

        IL_0007: ldarg.0
        IL_0008: ldc.i4.2
        IL_0009: beq.s IL_0014

        IL_000b: ldarg.0
        IL_000c: ldc.i4.3
        IL_000d: beq.s IL_0014

        IL_000f: ldarg.0
        IL_0010: ldc.i4.4
        IL_0011: ceq
        IL_0013: ret

        IL_0014: ldc.i4.1
        IL_0015: ret

and this asm:

    L0000: cmp ecx, 3
    L0003: jbe short L000f
    L0005: cmp ecx, 4
    L0008: sete al
    L000b: movzx eax, al
    L000e: ret
    L000f: mov eax, 1
    L0014: ret

In contrast, Roslyn compiles this pattern matching:

    private static bool IsLetterCategory(UnicodeCategory uc)
    {
        return uc is UnicodeCategory.UppercaseLetter
             or UnicodeCategory.LowercaseLetter
             or UnicodeCategory.TitlecaseLetter
             or UnicodeCategory.ModifierLetter
             or UnicodeCategory.OtherLetter;
    }

down to:

        IL_0000: ldarg.0
        IL_0001: ldc.i4.4
        IL_0002: bgt.un.s IL_0008

        IL_0004: ldc.i4.1
        IL_0005: stloc.0
        IL_0006: br.s IL_000a

        IL_0008: ldc.i4.0
        IL_0009: stloc.0

        IL_000a: ldloc.0
        IL_000b: ret

resulting in the branchless asm:

    L0000: cmp ecx, 4
    L0003: setbe al
    L0006: movzx eax, al
    L0009: ret

It'd be nice if the syntactical choice didn't result in these differences.

cc: @EgorBo

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIhelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions