Registry Mirror
Skip to content

JIT: fold unreachable cases for switch #65368

Closed

Description

@EgorBo
static void Foo() => Bar(5);

static void Bar(int i)
{
    switch (i)
    {
        case 0:
            Console.WriteLine();
            break;
        case 1:
            Console.WriteLine();
            break;
        case 2:
            Console.WriteLine();
            break;
        case 3:
            Console.WriteLine();
            break;
        case 4:
            Console.WriteLine();
            break;
        case 5:
            // no-op
            break;
    }
}

After Bar is inlined into Foo we should get:

; Method Program:Foo()
       C3                   ret      
; Total bytes of code: 1

and we do lower it to exactly this already! The problem that it seems the importer is not able to do it early and materializes all trees:
image

so these calls (unreachable cases) live till some late phase (PHASE Optimize layout to be precise). If we fix it we might improve throughput for some methods.

It's actually quite important for this method:

    static bool Equals(ReadOnlySpan<char> a, ReadOnlySpan<char> b) => 
        a.Equals(b, StringComparison.Ordinal);

Here we pass StringComparison.Ordinal (constant) to a switch inside Equals, see here https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.Globalization.cs#L46-L67

so JIT ends up importing everything and only then does dead code elimination. it leads to this codegen: https://gist.github.com/EgorBo/7117c2fc53892cf17ade0f11ddd67240 (the final codegen is more or less fine but just take a look at the amount of temp locals)

category:cq
theme:basic-cq

Activity

  1. ghost added
    area-CodeGen-coreclr
    on Feb 15, 2022
  2. ghost added
    untriaged
    on Feb 15, 2022
  3. added this to the Future milestone on Feb 15, 2022
  4. added
    help wanted
    and removed
    untriaged
    on Feb 15, 2022
  5. ghost added
    in-pr
    on Feb 28, 2023
  6. self-assigned this
    on Mar 13, 2023
  7. modified the milestones: Future, 8.0.0 on Mar 13, 2023
  8. ghost removed
    in-pr
    on Mar 15, 2023
  9. ghost locked as resolved and limited conversation to collaborators on May 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrhelp wanted

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions