Skip to content

Inefficient codegen with ternary and additive inverse #135647

Description

@am11

While reviewing #133659, I had a gut feeling about:

int M1(int num, bool r) => num + (r ? 0 : -1);
// vs.
int M2(int num, bool r) => num - (r ? 0 : 1);

https://godbolt.org/z/3czc6z7f9

Expected:

mov  eax, edi
cmp  sil, 1
sbb  eax, 0
ret

Activity

  1. added
    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI
    on Oct 12, 2026
  2. dotnet-policy-service commented on Oct 12, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  3. hamarb123 commented on Oct 13, 2026

    @hamarb123
    Contributor

    I don't see how that is valid codegen for this IL btw - bool can be any value 0-255, and that codegen is only correct for 0-1 - 2-255 bool is UB in C# but not in ECMA-335 - you would have to write C# like num - 1 + (r ? 1 : 0) and change roslyn to get it to emit IL more like:

    ldarg.0
    ldc.i4.1
    sub
    ldarg.1
    add
    ret

    (that is, extend the bool ? 1 : 0 -> (int)bool optimization to any bool, not just for direct IL comparison sequences like x >= 0 ? 1 : 0).

    As you can see, it works as expected if I insert the cast using Unsafe.BitCast instead: https://godbolt.org/z/78PMe5cPd

    Program:M1(int,bool):int (FullOpts):
           movzx    rax, sil
           lea      eax, [rdi+rax-0x01]
           ret      
  4. am11 commented on Oct 13, 2026

    @am11
    MemberAuthor

    @hamarb123, good point, updated expected to cover 2+

  5. removed
    untriagedNew issue has not been triaged by the area owner
    on Oct 13, 2026
  6. added this to the 12.0.0 milestone on Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

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

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions