Skip to content

Difference of Codegen in JIT ASM when using Negation / if-else block code #81479

@ShreyasJejurkar

Description

@ShreyasJejurkar

Was playing with the JIT ASM code and found this interesting difference when using the Negation operator as compared to the if and else block.

public class C 
{
    public bool NegationOperator(bool input) 
    {
        return !input;
    }
    
    public bool IfElseCondition(bool input) 
    {
        if (input)
        {
            return false;
        } 
        else 
        {
            return true;
        }
    }
}

As you can see above we are doing the same thing, in both of the code-block we are just reverting the result based on the input value.
I expect to have the same code-gen generated for both of the code blocks because we are dealing with all constants values except input parameters (which is technically also a constant as it can have possible 2 values only) so JIT can see that and should fold.

But interestingly if-else block code generates a different code than the NegationOperator method.

C.NegationOperator(Boolean)
    L0000: xor eax, eax
    L0002: test dl, dl
    L0004: sete al
    L0007: ret

C.IfElseCondition(Boolean)
    L0000: test dl, dl
    L0002: je short L0007
    L0004: xor eax, eax
    L0006: ret
    L0007: mov eax, 1
    L000c: ret

Sharplab link

Why there is a difference in codegen!? Can't we generate the same ASM code for the IfElseCondition method just like we did it for NegationOperator method? I guess we can avoid je instruction in IfElseCondition.

Metadata

Metadata

Assignees

Labels

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

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions