Skip to content

Tracking Issue for const_eval_select #124625

Open

Description

@RalfJung

This is a tracking issue for the const_eval_select intrinsic.

The intrinsic provides a way for a const fn to check whether it runs at compile time or at runtime. Several major points need to be resolved before it can be stabilized:

  • Do we even want to allow const fn to do something like this? Or do we want to guarantee the property that const fn behave the same at runtime and at compile time? Currently they behave the same.

    Even if add float semantics RFC rfcs#3514 gets accepted, the set of possible return values of a function is the same at compile time and at runtime (but the actual concrete return value that is chosen may differ). const_eval_select is qualitatively different from allowing float operations in const fn. With floats, the compile time behavior can actually be seen at runtime if optimizations kick in -- and while it is possible to do horrible things with black_box to write a function that de facto is always true at compile time and false at runtime on x86, (a) this is clearly cursed, and (b) it's actually not possible to do this in a portable way.

    Note that one could specify const_eval_select as "at runtime, non-deterministically pick either the compile time or the runtime behavior (but implementations generally will prefer the runtime behavior)". That would formally satisfy the requirement that every compile-time behavior is also possible at runtime (but the opposite direction would cease to hold when const_eval_select becomes stable). However this is a silly way to achieve that property -- de facto, it becomes possible to write a function that is always true at compile time and false at runtime, and the mere fact that it may return true at runtime (but actually it never does) will not stop people from relying on it. I call this "gratuitous non-determinism" -- this is non-determinism that doesn't actually occur in practice and exists solely to satisfy some abstract property of the spec. I think the align_offset story showed us that gratuitous non-determinism is very confusing and it is hard to prevent people from just ignoring it.

  • Assuming we want something like const_eval_select, how should it be exposed on stable? The problem is that a fn is_const_eval() -> bool is insufficient, because if you do if is_const_eval() { ... } else { ... }, the const-checker will still require both arms to only call const fn. That's why const_eval_select has this awkward interface where you give it two functions and it calls one of them. But the interface is truly awkward and ideally we can find something better.

    I think there is possible overlap here with the discussions around const if and controlling which constants and called functions get monomorphized: What are the guarantees around which constants (and callees) in a function get monomorphized? #122301. If const if EXPR already says that only the arm actually taken will be monomorphized, then maybe const if is_const_eval() only const-checks one of the arms? That would still be a very special magic case though since we can't evaluate the conditional to a bool first. Wrapping is_const_eval in your own function would change its behavior. This really feels like it has to be primitive syntax, but I don't know what the syntax should be.

About tracking issues

Tracking issues are used to record the overall progress of implementation.
They are also used as hubs connecting to other relevant issues, e.g., bugs or open design questions.
A tracking issue is however not meant for large scale discussion, questions, or bug reports about a feature.
Instead, open a dedicated issue for the specific matter and add the relevant feature gate label.
Discussion comments will get marked as off-topic or deleted.
Repeated discussions on the tracking issue may lead to the tracking issue getting locked.

Steps

Unresolved Questions

XXX --- list all the "unresolved questions" found in the RFC to ensure they are
not forgotten

Implementation history

Related issues

Activity

  1. added
    C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFC
    T-langRelevant to the language team
    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)
    on May 2, 2024
  2. RalfJung commented on May 2, 2024

    @RalfJung
    MemberAuthor

    Cc @rust-lang/wg-const-eval

  3. coolreader18 commented on May 9, 2024

    @coolreader18
    Contributor

    For syntax - I could imagine a macro in core that expands to builtin#is_const_eval, and then the const checker special-cases an if with that as the condition. Perhaps that's too magic, but I feel like the macro would communicate that there's something special going on.

    if core::is_const_eval!() {
        // ...
    } else {
        // ...
    }
  4. RalfJung commented on May 9, 2024

    @RalfJung
    MemberAuthor

    I don't think a macro is enough. Note that if you change the code like this, it will no longer have the right behavior:

    let b = core::is_const_eval!();
    if b {
        // ...
    } else {
        // ...
    }

    So, we'd want the macro to error when it is not used as the sole condition of an if. (if core::is_const_eval!() && other also cannot work.)

  5. added 3 commits that reference this issue on Jul 26, 2024
  6. added a commit that references this issue on Jul 27, 2024
  7. nvzqz commented on Aug 5, 2024

    @nvzqz
    Contributor

    Rather than go with a macro, we could have the language make use of the existing keyword by simply having if const {.

  8. jhpratt commented on Aug 5, 2024

    @jhpratt
    Member

    I feel like there's a situation where that wouldn't work due to the existence of inline const, but can't come up with a simple example off-hand.

  9. oli-obk commented on Aug 5, 2024

    @oli-obk
    Contributor

    I feel like there's a situation where that wouldn't work due to the existence of inline const, but can't come up with a simple example off-hand.

    if const { } { } parses as if (const {}) {} and then fails typeck. if const {} just fails parsing. Also it's just too confusing imo to have two syntactical constructs so close to each other, even if we can get away with it.

    if in const {} has been proposed before

  10. matveitolochko commented on Oct 17, 2024

    @matveitolochko

    I feel like it can be passed as part of the cfg macro, so that it could be used in a cfg_if! situation.

    cfg_if! {
        if #[cfg(const_eval)] {
            // Constant
        } else {
            // Non-constant
        }
    }
  11. kayabaNerve commented on Jul 24, 2025

    @kayabaNerve

    As a consumer, my interest was in introducing SIMD acceleration (the stable intrinsics available via core::arch) to functions which are currently const fn. This leaves me with two options:

    1. const_eval_select
    2. One codebase which is entirely const, before a wrapper codebase which is entirely non-const. The wrapper codebase may delegate or not.

    The obvious issues with such a design is if the wrapper ever delegates to the const fn codebase, it will never regain control. This means in order to runtime accelerate a low-level function, I must never delegate any higher-level functions.

    In practice, this would force a macro/build script to generate two codebases from a single source with some equivalency to const_eval_select such that the resulting source code (passed to the Rust compiler) does not itself have const_eval_select.

    While I cannot comment on the compiler internals, nor if functions should be exactly equal to functions at runtime, I believe there is clear reason to the user for the functionality offered by const_eval_select (with no commentary on this specific implementation).

  12. Keith-Cancel commented on Jul 29, 2025

    @Keith-Cancel
    Contributor

    Something like this could be quite handy. It would make it easy to have a like a generic implementation that works in rust const contexts. Then like a hyper optimized version using like inline assembly or intrinsics. This can cleanup up an API in such instances instead of having two functions like foo() and foo_const() it would be possible to have a single foo(), which would be really nice.

  13. tarcieri commented on Jul 31, 2025

    @tarcieri
    Contributor

    Do we even want to allow const fn to do something like this? Or do we want to guarantee the property that const fn behave the same at runtime and at compile time? Currently they behave the same.

    As a data point: in @RustCrypto we've kept SIMD out of const fn so far by having const fn versions of a function and putting the SIMD acceleration in trait impls (think e.g. pub const fn add and a non-const Add trait impl with SIMD), but with the forthcoming stabilization of const impl Trait, that approach isn't going to continue to work, at least if we want to support const traits, which would be fantastic.

    At that point, we either need something like const_eval_select, or for Miri to be able to emulate the relevant intrinsics so they're const fn-friendly (which I guess would just be pushing the usage of const_eval_select down into the standard library?)

    Based on the above comments, it seems we're not the only ones who would like to be able to use SIMD in const fn contexts. Though the means of execution are different, the computed results are the same (or if not, it's a bug!)

  14. hanna-kruppe commented on Jul 31, 2025

    @hanna-kruppe
    Contributor

    I don’t see any reason why SIMD should require const_eval_select or any other way to branch on “is this const eval”. Pretty much every SIMD intrinsic is trivial to make const because they just do arithmetic operations and memory accesses. There’s just a metric ton of them so nobody’s been eager to constify all of them. But it’s possible and valuable.

    Note that miri-the-tool already supports portable SIMD and a big chunk of core::arch intrinsics (mostly those currently implemented using the same rustc intrinsics used by portable SIMD). It may take much longer to fully const-stabilize all the core::arch intrinsics, and the constification may always lag behind addition of new intrinsics, but overall this use case seems more like a reason to invest the effort into const SIMD, not a reason to open the const_eval_select can of worms.

    Inline assembly is different - realistically it’ll never be const. So maybe there’s some good use cases to be found there?

  15. tarcieri commented on Jul 31, 2025

    @tarcieri
    Contributor

    Intrinsics would cover probably 99% of our use cases, but there are still gaps, like ADX (and MULX to avoid clobbering ADX flags), which last I checked LLVM doesn't support at all (I think it doesn't implement the relevant flags, at least for ADX?). Perhaps down the road the bigint helper methods (#85532) could eventually support codegen for them whenever LLVM adds support

  16. hanna-kruppe commented on Jul 31, 2025

    @hanna-kruppe
    Contributor

    I guess wanting to work around a codegen performance issue and needing to dip into non-const land for it is more likely to occur in the kinds of code that’s like to use SIMD in the first place. Not super likely in the grand scheme of things, but it does happen and is really annoying when it happens.

  17. RalfJung commented on Aug 1, 2025

    @RalfJung
    MemberAuthor

    I don't think having const-eval implementations of LLVM intrinsics is sustainable.

    We can fairly easily have const-eval implementations of the simd_* intrinsics, that can just be moved over from Miri. But for the stdarch intrinsics that directly use LLVM intrinsics, I think we should either find some way to factor them through a reasonably small set of general-purpose intrinsics, or we should have the const-eval implementation for them in stdarch (e.g. via const_eval_select).

    I would suggest opening a separate issue for "SIMD in const-eval" since, as noted above, it doesn't have to require const-eval-select stabilization.

  18. Keith-Cancel commented on Jan 23, 2026

    @Keith-Cancel
    Contributor

    I don't think having const-eval implementations of LLVM intrinsics is sustainable.

    I agree, but even if all intrinsics were magically made const there still inline assembly. That alone in my opinion necessitates something like this. Like MULX and ADDX where mentioned above and X64_86 is a pretty well supported architecture. Let alone lesser used architectures out there. So even getting an intrinsic to begin with is not always a guaranteed.

  19. tarcieri commented on Jan 25, 2026

    @tarcieri
    Contributor

    My need for inline assembly could go away if the bigint_helper_methods could automatically emit ADX/MULX as appropriate with #[cfg(target_feature = "bmi2")] or what have you, but last I checked LLVM lacked support for their flags as even a prerequisite for using them in codegen (double check me on that, though).

    The other missing piece would be some kind of const fn wrapper for nascent constant-time selection intrinsics

  20. nazar-pc commented on Jul 24, 2026

    @nazar-pc

    I have a proposal to use specialization for this purpose: https://internals.rust-lang.org/t/const-fn-specialization/24488?u=nazar-pc

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

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCT-langRelevant to the language team

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions