Repository navigation
Description
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:
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 theinline(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.
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/zis strictly equivalent to-C opt-level=2with 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 tominsize(opt-level=z) rather thanoptsize(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 acceptoptimize(size, speed), if needed, and people seemed generally happy with that.
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=Xcrate-wide and then annotating every other function with eitheroptsizeoroptnonedepending 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(...)]withoptnone/optsizeas needed to implement-Copt-size=0/s/z.
@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 theoptimize(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 usingoptimize(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 implyinginline(never), but, of course, the compiler is always free to not inline.That's right. To summarize the model the lang team liked:
optimizesets the optimization goal of a function body, and closure bodies are part of the body of their containing function.inlinesets 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
noneshould 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 namenonedoesn'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-levelmore 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
RalfJung commentedon Nov 17, 2026
@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.
hanna-kruppe commentedon Nov 17, 2026
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=0in particular. (While the behavior and interpretation ofoptimize(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 sooptimize(speed)doesn't "raise-C opt-levellocally" 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:#[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-leveldoes 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.cezarbbb commentedon Nov 18, 2026
RalfJung commentedon Nov 18, 2026
traviscross commentedon Nov 23, 2026
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:
optimize(size)oroptimize(speed)to a function to be interpreted as if applying-C opt-level=Xto that function, whereXis an optimization level (e.g.,s,z,2, or3) 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".optimize(none)to a function is to be interpreted as if the global optimization levelYwere first requested separately for each function in the program, as if by applying-C opt-level=Yto it, and then this request were removed for the attributed function, leaving no particular optimization request for that function.rustcmight never better approximate our intention.optimize(size)oroptimize(speed)even in unoptimized builds, we'd be OK with that change in behavior, and we'd consider it an acceptable user experience.In coming to these conclusions, we considered that:
rustcimplements it today on nightly, serves a real use case for people who need to tune the optimization behavior in optimized builds.optimize(size)oroptimize(speed), and it's likely people will make varied assumptions in any case.rustcmight 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
rustcand what the limits on changing that behavior might be.hanna-kruppe commentedon Nov 24, 2026
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:
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?
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:
optimize(size/speed)works like this: [...]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?
traviscross commentedon Nov 24, 2026
That's correct.
The scope of the decision is:
optimizeattribute 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.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.
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
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)andoptimize(speed)act as if-C opt-level=Xwere applied to the attributed function, where the compiler choosesXto 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=0is 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. ↩