Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions text/3820-target-feature-traits.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
- Feature Name: (`target_feature_traits`)
- Start Date: (2025-05-25)
- RFC PR: [rust-lang/rfcs#3820](https://github.com/rust-lang/rfcs/pull/3820)
- Rust Issue: [rust-lang/rust#139368](https://github.com/rust-lang/rust/issues/139368)

# Summary
[summary]: #summary

This RFC proposes the addition of an `unsafe` variant of the existing `target_feature` attribute, and to modify the behaviour of the existing non-`unsafe` attribute to make it more compatible with traits.

See https://github.com/rust-lang/rust/issues/139368 for the discussion preceding this RFC and overall rationale.

### New behaviour of `#[target_feature(enable = "x")]` in traits

- Target features can be enabled on trait *definition* methods (safe or unsafe). This imposes on the caller the same requirements that calling a concrete function with those features would impose.
- Target features can be enabled on trait *impl* methods, as long as the corresponding definition enables a superset of the enabled features.
- Provided methods in traits count as both a definition and an impl, and behave accordingly (i.e. overridden impls can enable any subset of the features specified on the provided method).

Compared to the current status, this:
- allows to use target features in safe trait methods
- disallows using features in a trait impl that were not expected in the trait definition

For the second case, we plan to emit a lint and to make this into a hard-error in a future edition.

### New `#[unsafe(target_feature(force = "x"))]` attribute

This `unsafe` attribute can be applied to free functions, trait method implementations or trait method definitions.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might benefit from some examples, e.g. proof types:

struct Avx;

impl Avx {
    fn new() -> Option<Self> {
        if is_x86_feature_detected!("avx") {
            Some(Self)
        } else {
            None
        }
    }
}

#[unsafe(target_feature(force = "avx"))]
fn requires_avx(_proof: Avx) {
    // AVX is enabled, but can be called with an entirely safe abstraction
}

An expanded version with static dispatch depending on feature would be nice, too

Copy link
Contributor

@traviscross traviscross Jun 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From our earlier thread in rust-lang/rust#139368, here's a worked example of what can be done today, demonstrating the relevant safety analysis:

Playground link

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the playground link:

// The key factor, in my view, is that despite the trait function
// being marked as `unsafe`, it must actually be always safe to call
// (at least as far as `target_feature` is concerned; it could have
// unrelated preconditions).  If this were not the case, then it would
// need to obligate the caller to never call it in a generic context,
// and that wouldn't be a very appealing kind of precondition for us
// at a language level.

I'm curious if you see the "it must always be safe to call" part as specific to the example, or whether it should apply in general?

I didn't quite understand the connection between having additional safety requirements and using it in a generic context, nor whether in that case we're discussing the trait or function being generic (or possibly both).


It comes with the following soundness requirement: a function with the signature of the function the attribute is applied to must _only be callable if the force-enabled features are guaranteed to be present_ (this can be done, for example, if the function takes arguments that carry appropriate safety invariants).
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like for this line to be weakened slightly; I believe it would also be fine for the safety invariant to be that these functions are only called in contexts where the target feature is know to be present.
So for reachable pub functions, that would be equivalent to this stricter condition, but intra-module (and especially intra-function), the weaker condition would better reflect what users want.

For example, if I write a macro which wants to generate:

#[unsafe(target_feature(force = "avx2"))]
fn do_my_thing(arg1: __mm128) -> __mm128 {
    // User provided code
}
if is_x86_target_feature_enabled("avx2") {
     do_my_thing(user_provided_arg1);
}

Where the safety here is guaranteed because do_my_thing cannot be called except in the block which performs the check due to macro hygiene.
This is of course equivalent to:

struct Token;
#[unsafe(target_feature(force = "avx2"))]
fn do_my_thing(token: Token, arg1: __mm128) -> __mm128 {
    // User provided code
}
if is_x86_target_feature_enabled("avx2") {
     do_my_thing(Token, user_provided_arg1);
}

Which meets this stricter condition because it's impossible to name Token outside of the macro, and the macro only constructs Token once the features have been checked. But that's pointless busiwork only introduced by this condition being so strict.


For context, this is thinking about this feature in the context of Fearless SIMD, specifically linebender/fearless_simd#108. That currently cannot currently allow the addition of arbitrary attributes to the generated function (e.g. if the user wanted to add #[inline(never)], #[track_caller], #[allow/expect], etc.) safely - the user could always add another #[target_feature(enable = "...")], breaking the safety guarantees.

For the specific example in the macro-generated code of linebender/fearless_simd#108, we already have a suitable value of the equivalent Token to hand, so it isn't actually any cost to the requirement for that PR. But I don't see any reason why the much simpler macro generating the first code block shouldn't be useful and wouldn't be valid.


This being weaker would need a little bit more care - in particular, it would need to be written to exclude #[panic_handler] and main. This would be similar to [attributes.codegen.target_feature.allowed-positions], which I don't think would implicitly apply to unsafe(target_feature) (because this RFC introduces #[unsafe(target_feature)] as a "new" attribute, rather than as an extension to the old attribute).


Because of the soundness requirement, applying this attribute does not impose additional the requirements for calling this function on the callers (which is why the attribute can be applied to arbitrary trait methods).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo fix:

Suggested change
Because of the soundness requirement, applying this attribute does not impose additional the requirements for calling this function on the callers (which is why the attribute can be applied to arbitrary trait methods).
Because of the soundness requirement, applying this attribute does not impose additional requirements for calling this function on the callers (which is why the attribute can be applied to arbitrary trait methods).


The effect of the attribute is otherwise equivalent to `#[target_feature(enable = "x")]`.

Note that this version of the attribute can be used in the use-cases where `#[target_feature(enable = "x")]` would no longer be allowed.

Also note that the safety requirements of `#[unsafe(target_feature(force = "x"))]` only depend on the function's *signature*. This implies that an implementation (whether it is overriding a provided method or implementing a required method) should also be allowed to enable a feature (without needing to discharge any further safety requirements) if the corresponding definition had the `#[unsafe(target_feature(force = "x"))]` applied to it.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

without needing to discharge any further safety requirements

Just checking: I believe this is intended to refer specifically to target-feature requirements, not all safety requirements in general?

An example may be good here as well.