Add support for running LLVM optimizer. (#6225)

Adds a flag `--optimize=<mode>` that specifies what to optimize for:

* `--optimize=none` turns off the optimizer as much as possible, but
still respects always_inline.
* `--optimize=debug` aims to be the equivalent of `-Og` / `-O1`, and
provides optimizations that don't affect the ability to debug the
program. This is the default.
* `--optimize=size` optimizes for the size of the produced program, and
aims to be the equivalent of `-Oz`.
* `--optimize=speed` optimizes for the execution time of the produced
program, and aims to be the equivalent of `-O3`.

Following the approach taken by Clang, the optimization level feeds into
both the configuration of the LLVM pass pipeline and the attributes
added to function definitions generated by the frontend.

Optimization is performed in a new phase, `optimize`, which runs between
`lower` and `codegen`.

---------

Co-authored-by: Dana Jansens <danakj@orodu.net>
Co-authored-by: Chandler Carruth <chandlerc@gmail.com>
This commit is contained in:
Richard Smith
2025-11-05 00:15:14 +00:00
committed by GitHub
co-authored by Dana Jansens Chandler Carruth
parent db150ffc5c
commit aa69a484eb
202 changed files with 3376 additions and 1253 deletions
+31
View File
@@ -23,6 +23,7 @@
#include "toolchain/lower/constant.h"
#include "toolchain/lower/function_context.h"
#include "toolchain/lower/mangler.h"
#include "toolchain/lower/options.h"
#include "toolchain/lower/specific_coalescer.h"
#include "toolchain/sem_ir/absolute_node_id.h"
#include "toolchain/sem_ir/diagnostic_loc_converter.h"
@@ -619,6 +620,36 @@ auto FileContext::BuildFunctionBody(SemIR::FunctionId function_id,
AddLoweredSpecificForGeneric(declaration_function.generic_id, specific_id);
}
// Set attributes on the function definition.
{
llvm::AttrBuilder attr_builder(llvm_context());
attr_builder.addAttribute(llvm::Attribute::NoUnwind);
// TODO: We should take the opt level from the SemIR file; it might not be
// the same for all files in a compilation.
if (context().opt_level() == Lower::OptimizationLevel::None) {
// --optimize=none disables all optimizations for this function.
attr_builder.addAttribute(llvm::Attribute::OptimizeNone);
attr_builder.addAttribute(llvm::Attribute::NoInline);
} else {
// Otherwise, always inline thunks.
if (definition_function.special_function_kind ==
SemIR::Function::SpecialFunctionKind::Thunk) {
attr_builder.addAttribute(llvm::Attribute::AlwaysInline);
}
// Convert --optimize=size into optsize and minsize.
if (context().opt_level() == Lower::OptimizationLevel::Size) {
attr_builder.addAttribute(llvm::Attribute::OptimizeForSize);
attr_builder.addAttribute(llvm::Attribute::MinSize);
}
// TODO: Should we generate an InlineHint for some functions? Perhaps for
// those defined in the API file?
}
llvm_function->addFnAttrs(attr_builder);
}
FunctionContext function_lowering(
definition_context, llvm_function, *this, specific_id,
coalescer_.InitializeFingerprintForSpecific(specific_id),