Skip to content

[API Proposal]: Scalar BitOperations.ConditionalSelect (or similar) #119597

Open

Description

@kg

Background and motivation

At present the JIT optimization to transform a ? b : c into a cmov or equivalent instruction does not always light up. AFAIK we do not have an API that exposes a way to manually request/demand a cmov for scalars, while it is available for vectors. One example I know of is that we are not currently able to generate cmovs automatically for code inside loops, which can show up in surprising cases (for example, if a scalar method call gets inlined into a loop.)

This came up in a discussion with @jakobbotsch today so I wanted to file a tracking issue for it w/a rough proposal.

This particular problem came up when researching the vectorized dictionary - targets without SIMD require a good scalar search fallback, and scalar bucket search is much faster with access to cmov, but I was unable to get RyuJIT to produce cmov in the necessary places, unlike clang or msvc.

API Proposal

public static T ConditionalSelect<T>(bool cond, T trueValue, T falseValue);

API Usage

Without API:

uint result = 32;
for (int i = bucket.Count - 1; i > 0; i--) {
    // The loop prevents this from turning into a cmov
    if (needle == bucket[i])
        result = i;
}
return result;

With API:

uint result = 32;
for (int i = bucket.Count - 1; i > 0; i--)
    result = BitOperations.ConditionalSelect(needle == bucket[i], i, result);
return result;

Alternative Designs

No response

Risks

Users may manually inject cmovs in places where they are not actually optimal, where the JIT is better equipped to make the decision about whether to use them.

Activity

  1. added
    api-suggestion
    on Sep 11, 2025
  2. dotnet-policy-service commented on Sep 11, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-runtime-intrinsics
    See info in area-owners.md if you want to be subscribed.

  3. added
    untriaged
    on Sep 11, 2025
  4. tannergooding commented on Sep 11, 2025

    @tannergooding
    Member

    This has been discussed a few different times and we've largely not had consensus around adding it. I believe there's some complexity in adding support to the JIT as well, but it may have lessened since we've done the general CSEL/CMOV support expansion and have IR nodes to represent the operations now.

    Ideally we'd just get the JIT to recognize the pattern (particularly cond ? x : y) and light up in more places by default, barring some exception like PGO giving significant weights. Likewise, even with the explicit API, it may be desirable for PGO data to override the use of cmov/csel if the weights are "significant" enough (as can happen with C/C++ compilers).

    We probably should have some more in depth discussion around this to decide what the behavior and guarantees would be; and then we can decide where such an API might be exposed afterwards.

    CC. @dotnet/jit-contrib

    Particularly interested in @AndyAyersMS input on the PGO interplay and @jkotas input on exposing this as an xplat API.

  5. jkotas commented on Sep 11, 2025

    @jkotas
    Member

    we'd just get the JIT to recognize the pattern (particularly cond ? x : y) and light up in more places by default

    I agree. It should be a job for the JIT to figure out what's the right instruction to use in given situation.

    If we are going to introduce this API, I would like see guidance about when to use ? : vs. when to use this API. I do not think we want to see people changing ? : everywhere to use this API because of it is better.

  6. kg commented on Sep 11, 2025

    @kg
    ContributorAuthor

    we'd just get the JIT to recognize the pattern (particularly cond ? x : y) and light up in more places by default

    I agree. It should be a job for the JIT to figure out what's the right instruction to use in given situation.

    If we are going to introduce this API, I would like see guidance about when to use ? : vs. when to use this API. I do not think we want to see people changing ? : everywhere to use this API because of it is better.

    Agreed there, I think in practice most of the time it doesn't make sense to use explicit cmov, which is why at the time I didn't open an issue about it. But it is potentially a spot where people might have to jump through elaborate hoops to get native-level performance in hot paths, or be unable to get it at all. I feel like this is an 'intrinsic of last resort' if we expose it, which might mean it's best not to? Though I'd love to see it.

    The vectorized dictionary case is two nested loops, so unrolling the internal loop by hand still isn't enough to make cmov happen. And the negative impact on branch prediction of not having the cmov is significant.

  7. jakobbotsch commented on Sep 11, 2025

    @jakobbotsch
    Member

    I think the guidance would be to use this API when the programmer expects the condition to be unpredictable, i.e. close to random. I see the API as a hint to that JIT that it should prefer branchless instructions.

    On more aggressive if-conversion: the current problem is that it is very hard to predict whether if-conversion is beneficial for the JIT. It requires analysis on data and control flow dependencies and whether or not they are loop carried, and we have not built that analysis. We got that wrong before and saw 40% regressions in core span functions in micro benchmarks (#82106 (comment)).

  8. added
    needs-further-triage
    and removed
    untriaged
    on Sep 24, 2025
  9. added this to the Future milestone on Sep 24, 2025
  10. huoyaoyuan commented on Sep 26, 2025

    @huoyaoyuan
    Member

    An example for cmov recognition problem with inlining: #113651 (comment)

    Since it's represented with branches in IL, we should make sure the optimization isn't broken with inlining.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Runtime.Intrinsicsneeds-further-triage

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions