Clarify our intended interpretation of the `optimize` attribute

Abierto
#166,079 4 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
28/100
Tipo de issue
Documentación
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
rust

Línea de trabajo

Start with the Rust Reference section on the optimize attribute and compare its wording with the decisions and implementation discussion linked in this issue, especially the stabilization PR and PR #165592. The issue asks the language team to clarify whether size and speed express a direction or a magnitude, but the discussion already records agreement on the intended interpretation. Done means determining whether the Reference needs clarification and proposing wording consistent with that agreement.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

C-discussion I-compiler-nominated I-lang-nominated I-lang-radar P-lang-drag-1 T-lang

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 https://github.com/rust-lang/reference/pull/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: https://github.com/rust-lang/rust/issues/54882#issuecomment-2789971186. 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 https://github.com/llvm/llvm-project/pull/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.

Lenguaje dominante
Rust
Estrellas
122k
Forks
16.7k
Merge medio
2 d 16 h
PR fusionados (30 d)
515

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de rust-lang/rust

Todos los issues de rust-lang/rust

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.