Skip to content

Clarify our intended interpretation of the optimize attribute #166079

Backlog

Description

@traviscross

Regarding the stabilization of the optimize attribute, the question has come up of whether lang meant for the modes of this attribute to suggest, for optimization, a vector direction, vector magnitude, or both.

For optimize(none), we clarified that we mean it as the absence of a request for any specific optimizations for the attributed function (overriding any defaults requesting specific optimizations that would otherwise apply).

For optimize(size) and optimize(speed), in our clarifications, we talked about these setting an "optimization goal". It's maybe unclear whether the goal for optimize(size) is "make this function as small as possible, even at the cost of speed" or "to the degree that the compiler has been asked to optimize, make this function as small as possible, even at the cost of speed" — or whether we see much difference, as a language matter, between these.

One practical question that's been asked is: if rustc interprets optimize(size) as "to the degree that the compiler has been asked to optimize, make this function as small as possible, even at the cost of speed", and there were later demand for a way to ask the compiler for the other thing, whether we would entertain that request or whether we'd consider it already covered by optimize(size) (with rustc having simply earlier underapproximated our original intention). (And we're asked the parallel question for optimize(speed).)

The Reference documentation is here: The optimize attribute.

(The nonnormative notes about rustc behavior are being tweaked slightly for clarity in rust-lang/reference#2415.)

What do we think?

cc @rust-lang/lang @veluca93


Here are the comments that seem relevant to determining what we earlier meant:

On 2026-06-02, @nagisa wrote:

I believe the overarching question in stabilizing this attribute should be whether we're happy with the capability and scope of this attribute. Code contained in functions with optimize(none) for example code can still participate in optimizations despite the inline(never) due to global cross-function analyses and there being many configurations in which the attribute can be lost (various LTO configurations?) It really is hard in a modern backend to ensure that optimization restrictions are propagated all the way through.

I realize that I'm basically reiterating the following comment: #54882 (comment). I don't necessarily think that we must block the stabilization of these attributes on this point, but I think it is important that we set ourselves' and the users' expectations on what this attribute can and cannot do. It might very well end up the case that in process of doing so we realize this feature does not pass the bar of quality we expect out of Rust. At the same time this feature is genuinely useful despite all its flaws and those flaws aren't likely to be addressed in any meaningful way, so stabilizing it might be the only way forward for it.

On 2026-06-02, @nikic wrote:

From the LLVM perspective, stabilizing these should be fine. I've done some work (culminating in llvm/llvm-project#191363) to ensure that -C opt-level=s/z is strictly equivalent to -C opt-level=2 with optsize/minsize attributes on every function. These changes are not in our current LLVM version, but I think the state in LLVM 22 is already sufficiently good to stabilize.

One thing I would like to see more explicitly discussed is the meaning of #[optimize(size)], which IIRC currently maps to minsize (opt-level=z) rather than optsize (opt-level=s). This choice should be optimized. We could also map to optsize instead, or we could expect both options. I don't have any specific preference here, I just want to make sure we're making a deliberate decision.

On 2026-06-10, I wrote (in part):

In the lang meeting today, we discussed the three questions raised as concerns:

On the capabilities and scope question, we were all agreed that we're happy to accept the limitations.

On the question of meaning, we were happy with optimize(size) focusing on size optimization and leaving to compiler to determine what that means in terms of the appropriate flags to apply. We discussed how we could later accept optimize(size, speed), if needed, and people seemed generally happy with that.

On 2026-06-18, @nagisa wrote:

There isn't a way to tell LLVM that you want to optimize a single function for speed; or at least there wasn't. My memory is that I had planned to implement this as setting -Copt-level=X crate-wide and then annotating every other function with either optsize or optnone depending on what the original optimization level was. Turned out to be a relatively non-trivial task.

EDIT: though now with the improvements on LLVM side that Nikita mentioned maybe we can do tell LLVM that we want speed pretty much unconditionally and then mark all the functions not otherwise annotated with an #[optimize(...)] with optnone/optsize as needed to implement -Copt-size=0/s/z.

On 2026-06-19, @nikic wrote:

@nikic, is there a way to get optimize(speed) to work? How does clang handle GCC-style push-option attributes?

optimize(speed) is supported (or at least it's supposed to be, I haven't verified). The way it currently works is by raising the global optimization level to O2, and not annotating the optimize(speed) functions with minsize. In LLVM 23, the global optimization level will always be O2 by default, which will avoid any kind of weird behavior where using optimize(speed) on one function could impact some other code due to the change to the global optimization level.

tl;dr optimize(speed) is the default from the LLVM perspective, so the implementation of it is to just not add attributes to optimize for size.

On 2026-07-01, @tmandry wrote (in part):

I understand the purpose of this attribute to be setting the optimization goal for a function body. This is framed around intent rather than mechanics. It does not offer fine-grained control over backend-specific optimization levels. (The implementation offers limited control by letting compiler flags influence that.)

One can imagine adding more fine-grained control later. At the language level this would be useful to application-specific code. But this feature is already useful for libraries. Library authors tend to know the performance-sensitive areas of their code better than users, and when paired with information about the intended use case this can be enough to override the globally configured optimization goal of the program or crate.

This applies most of all to #[optimize(speed)]. I think the motivation for #[optimize(size)] is weaker on its own – it's certainly useful at the application level where binary size is a problem, but that use case would be better served with more fine-grained controls. Still, both are useful compared to what we have now, and it makes sense to offer the two of them together.

On 2026-07-16, @tmandry wrote:

In summary, we do not want to specify optimize(none) as implying inline(never), but, of course, the compiler is always free to not inline.

That's right. To summarize the model the lang team liked:

  • optimize sets the optimization goal of a function body, and closure bodies are part of the body of their containing function.
  • inline sets the inline policy of a function call boundary, and closures have their own boundary.
  • Neither should imply the other at the language level.
  • The compiler is free to change how it inlines to better implement the optimization goal, or vice versa. Both attributes are best-effort, and the implementation approach is allowed to change or ignore the attributes altogether.

If a particular combination of attributes is ineffective, given how our compiler or backend work, we should probably lint on that combination. I don't think we need to block stabilization on such a lint.

On 2026-07-29, I wrote:

From a lang perspective, I think about the intent we write down in the Reference for these attributes. In that respect, I interpret optimize(none) as follows:

If you compile a program with -Copt-level=3, that's equivalent to applying to each function in the program an (unnameable) attribute that asks for the "level 3" optimizations. If you then write #[optimize(none)] on one function, that's equivalent to removing the other attribute from that function.

That is, optimize(none) says "I do not request any specific optimizations for this function". The compiler is, of course, always free to optimize at its discretion. optimize(none) simply means the programmer isn't asking for any, and if the ask was made globally, this retracts the ask for that function.


In the meeting, there was general agreement about this interpretation.

On 2026-07-31, @tmandry wrote (in part):

I would treat it very similar to the other optimize(_), as a request for the compiler to move generally in a certain direction in the trade-off space of optimizations.

I came in with the intuition that none should be treated similarly to the others. What pushed me away from it being a "direction" is that it's hard to define what that direction is, and the name none doesn't imply one. It's the thing the compiler does by default, which favors compile times and debugging without being entirely optimized for either one.

Maybe we should just spell this as #[optimize(level = 0)] or #[optimize(level0)] to make the parallel with -Copt-level more clear?

There are benefits to that, but currently we have consensus on the lang team for a more semantic interpretation. The benefit of the semantic approach is it's less tied to a compiler implementation and it doesn't imply a one-dimensional goal, like a number does.

In the future the compiler could accept -Copt-level=none, just like it accepts -Cdebuginfo=none.

The original RFC 2412 (2018) wrote:

#[optimize(speed)] is a no-op when a global optimization for speed option is set (i.e. -C opt-level=1-3). Similarly #[optimize(size)] is a no-op when a global optimization for size option is set (i.e. -C opt-level=s/z). #[optimize] attributes are no-op when no optimizations are done globally (i.e. -C opt-level=0). In all other cases the exact interaction of the #[optimize] attribute with the global optimization level is not specified and is left up to implementation to decide.

In our meeting on 2026-11-11, we reviewed the facts, including @nikic's description of the behavior, and concluded that we were happy for the optimize attribute stabilization to proceed, as far as we were concerned, and that we were happy with the intent and spelling of this attribute.

Activity

  1. added
    T-lang
    C-discussion
    I-lang-nominated
    I-lang-radar
    P-lang-drag-1
    on Nov 16, 2026
  2. added
    needs-triage
    on Nov 16, 2026
  3. removed
    needs-triage
    on Nov 16, 2026
  4. added
    I-compiler-nominated
    on Nov 17, 2026
  5. RalfJung commented on Nov 17, 2026

    @RalfJung
    Member

    @davidtwco @BoxyUwU I have also nominated this for compiler discussion, to ensure that the compiler team is okay with stabilizing the current behavior of the attribute. T-Lang has left most of the details up to the implementation, but once it becomes stable, changing it again could negatively impact users that relied on the old semantics, so we should be reasonably comfortable with the current behavior.

  6. hanna-kruppe commented on Nov 17, 2026

    @hanna-kruppe
    Contributor

    To give more context where this question is coming from: a lot of the recent post-stabilization discussion has revolved around the interaction of optimize(speed) and -C opt-level=0 in particular. (While the behavior and interpretation of optimize(speed/size) is generally symmetric, the use cases people are now discussing are very skewed to that specific combination.)

    The current meaning (modulo implementation bugs) in rustc + LLVM is that optimize(speed) changes "direction" but not "magnitude" and so optimize(speed) doesn't "raise -C opt-level locally" but only affects choices made within the optimization passes that are run anyway. Some people would (also/instead) like to have a way to get the "magnitude" interpretation, i.e., enable more optimizations for parts of a crate compiled with -C opt-level=0. It has also been pointed out that other implementations could support or prefer the latter meaning (e.g. GCC supports raising optimization level for individual functions). There are several ways to go about this. The main options I see are:

    1. Leave open whether the attribute suggests "direction, magnitude, or both" so each implementation (and new release of one) can pick freely. Users won't be able to portably communicate either "direction" or "magnitude" suggestions, though we could introduce additional hints in the future to let them do that.
    2. Pick the "direction" interpretation, which matches current rustc + LLVM. If other interpretations become relevant in the future, we can still consider introduce new hints to express "magnitude" suggestions (and presumably you could combine these hints to suggest "both direction and magnitude").
    3. Pick the "magnitude" interpretation or the "both" interpretation, knowing that it does not match rustc + LLVM. Treat this as a QoI concern, though if someone would find a way to make rustc+LLVM also "do more optimizations" for functions annotated #[optimize(speed)] (without downsides), then that would presumably be considered a welcome improvement.

    Obviously these attributes are just hints, whether and how they affect anything is a QoI concern. But for rustc, we'd ideally commit to one meaning of the attribute, and not drastically change what it means in the future. As Ralf mentions, such changes would negatively affect existing users of the attribute. Thus, even if rustc later gains support for "do more optimization on these functions than -C opt-level does by default" I expect that we'd want to spell it differently, rather than re-interpreting #[optimize(speed/size)]. Since any new stable surface for #[optimize] would be a t-lang decision, it seems prudent to check ahead of time if such extensions would be contrary to the intended interpretation of what's currently on its way to stable.

  7. cezarbbb commented on Nov 18, 2026

    @cezarbbb
  8. RalfJung commented on Nov 18, 2026

    @RalfJung
  9. traviscross commented on Nov 23, 2026

    @traviscross
    ContributorAuthor

    We discussed this at length on our 2026-11-18 lang call, reviewing the history of what we'd said previously, what is implemented today, the limits of what might be implemented in the future, and the use cases that people have for this feature. We concluded:

    1. We intend for applying optimize(size) or optimize(speed) to a function to be interpreted as if applying -C opt-level=X to that function, where X is an optimization level (e.g., s, z, 2, or 3) chosen by the compiler to match the suggestion of "optimize for smaller code, even at the cost of execution speed" or "optimize for faster execution, even at the cost of code size".
      • We previously clarified that applying optimize(none) to a function is to be interpreted as if the global optimization level Y were first requested separately for each function in the program, as if by applying -C opt-level=Y to it, and then this request were removed for the attributed function, leaving no particular optimization request for that function.
    2. This is just a hint, and we're OK with the compiler underapproximating that intention or ignoring it entirely. We understand that rustc might never better approximate our intention.
    3. If the compiler were to later better approximate our intention, by giving effect to optimize(size) or optimize(speed) even in unoptimized builds, we'd be OK with that change in behavior, and we'd consider it an acceptable user experience.
    4. We should document this carefully.
    5. We're happy to see this stabilized feature ship with the release.

    In coming to these conclusions, we considered that:

    • This feature, as rustc implements it today on nightly, serves a real use case for people who need to tune the optimization behavior in optimized builds.
    • The people whom the feature serves today are unlikely to be negatively affected if the attribute is later given effect in unoptimized builds. (For such code, people generally care only about their optimized builds.)
    • People who expect that the attribute will affect code in unoptimized builds may be disappointed when it doesn't work, and they may not use it for that reason, but they would not be negatively affected if it were to start working later.
    • It's not entirely obvious what behavior people should expect when seeing optimize(size) or optimize(speed), and it's likely people will make varied assumptions in any case.
    • Optimization requests are just suggestions, and it's a mistake to expect too much of these attributes.
    • We could later add a way to specifically request that an optimization goal be set for an attributed function only in optimized builds.
    • rustc might never optimize attributed functions in unoptimized builds.

    We're grateful for the efforts that many people have put in on this, both on the feature itself and in helping to clarify the exact nature of its behavior in rustc and what the limits on changing that behavior might be.

  10. removed
    I-lang-nominated
    P-lang-drag-1
    on Nov 23, 2026
  11. hanna-kruppe commented on Nov 24, 2026

    @hanna-kruppe
    Contributor

    Thank you for the detailed write-up. I have some follow-up questions.

    First, I don't see an explicit, direct answer to my original question, as paraphrased by TC:

    One practical question that's been asked is: if rustc interprets optimize(size) as "to the degree that the compiler has been asked to optimize, make this function as small as possible, even at the cost of speed", and there were later demand for a way to ask the compiler for the other thing, whether we would entertain that request or whether we'd consider it already covered by optimize(size) (with rustc having simply earlier underapproximated our original intention). (And we're asked the parallel question for optimize(speed).)

    I don't want to assume, but based on the intended interpretation and the "people whom the feature serves today are unlikely to be negatively affected" it seems like the answer would be: no, change the behavior for the existing attributes (and perhaps use a new spelling for requesting the previous behavior). Is this correct? And if yes, where does this answer lie on the spectrum from "point-in-time vibe check" vs "it's covered by the previous stabilization FCP and by the Reference"?

    Second, what's the plan for achieving this part?

    1. We should document this carefully.

    From my POV, the current language in the Reference notes (in non-normative text) how rustc implements this attribute today, but is not super clear about the intent (unsurprisingly, since the distinction wasn't identified and decided previously). We also don't seem to have any documentation other than the Reference. It isn't obvious to me how to properly communicate all of these aspects to users:

    • Currently, in rustc, optimize(size/speed) works like this: [...]
    • But the intent that users communicate with the attribute is [...] (quite different from what rustc does)
    • It's possible but far from certain that rustc will ever implement that intention

    For example, if a user expected the "locally raise opt-level" effect, sees it's not happening, and reports it as a bug... how do we explain this state of affairs to them? Is it a bug or not? Is their expectation correct or not?

  12. traviscross commented on Nov 24, 2026

    @traviscross
    ContributorAuthor

    I don't want to assume, but based on the intended interpretation and the "people whom the feature serves today are unlikely to be negatively affected" it seems like the answer would be: no, change the behavior for the existing attributes (and perhaps use a new spelling for requesting the previous behavior). Is this correct?

    That's correct.

    And if yes, where does this answer lie on the spectrum from "point-in-time vibe check" vs "it's covered by the previous stabilization FCP and by the Reference"?

    The scope of the decision is:

    1. Our happiness to see the optimize attribute ship with the upcoming stable release, where that happiness is based, in part, on our expectations about how we might feel and what decisions we might make in the future.
      • Beyond the constraints imposed by the attribute stabilizing, these expectations are not binding on a future lang team.
    2. What we want to write down in the Reference, or in other places, about our intended interpretation of the attribute, as a clarification of our stabilization FCP.

    Second, what's the plan for achieving this part?

    1. We should document this carefully.

    I'll review the Reference section in light of our discussion and ensure it correctly encodes both our intention and the relevant aspects of the implementation situation. We'll also want to mention this matter to @rust-lang/release so that they have the opportunity to highlight this in the release notes and release blog post.

    For example, if a user expected the "locally raise opt-level" effect, sees it's not happening, and reports it as a bug... how do we explain this state of affairs to them? Is it a bug or not? Is their expectation correct or not?

    The user's expectation would be reasonable given the intent, but the behavior would not be a bug because the attribute is a hint that the compiler is free to underapproximate or ignore while still being within spec.1 The report could be tracked as a possible improvement that may never happen. Or it could reasonably be closed if there are no current plans to go further.

    Footnotes

    1. And as was suggested in the meeting, our intent here could still be read as being optimization-level agnostic. Our model is that optimize(size) and optimize(speed) act as if -C opt-level=X were applied to the attributed function, where the compiler chooses X to match the suggestion "optimize for smaller code, even at the cost of execution speed" or "optimize for faster execution, even at the cost of code size". X=0 is a valid choice. It doesn't point in the wrong direction. It just goes zero distance in the desired direction. We specified no bounds on the acceptable magnitude. ↩

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

    C-discussionI-compiler-nominatedI-lang-radarT-lang

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions