[flang] Add -O flag to tco (#151869)

At the moment, there is no established way to emit LLVM IR before
optimization in LLVM. tco can partially does, but the optimization level
is fixed to 2. This patch adds -O flag to tco.

Note that this is not completely equivalent to the frontend option. tco
does not accept -O flag without numbers, and the default optimization
level is not 0 but 2.
This commit is contained in:
parabola94 2025-08-07 00:04:32 +09:00 committed by GitHub
parent f092b820d1
commit a9dacb10fe
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -51,6 +51,12 @@ static cl::opt<bool> emitFir("emit-fir",
cl::desc("Parse and pretty-print the input"),
cl::init(false));
static cl::opt<unsigned>
OptLevel("O",
cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
"(default = '-O2')"),
cl::Prefix, cl::init(2));
static cl::opt<std::string> targetTriple("target",
cl::desc("specify a target triple"),
cl::init("native"));
@ -96,6 +102,22 @@ static void printModule(mlir::ModuleOp mod, raw_ostream &output) {
output << mod << '\n';
}
static std::optional<llvm::OptimizationLevel>
getOptimizationLevel(unsigned level) {
switch (level) {
default:
return std::nullopt;
case 0:
return llvm::OptimizationLevel::O0;
case 1:
return llvm::OptimizationLevel::O1;
case 2:
return llvm::OptimizationLevel::O2;
case 3:
return llvm::OptimizationLevel::O3;
}
}
// compile a .fir file
static llvm::LogicalResult
compileFIR(const mlir::PassPipelineCLParser &passPipeline) {
@ -157,9 +179,17 @@ compileFIR(const mlir::PassPipelineCLParser &passPipeline) {
if (mlir::failed(passPipeline.addToPipeline(pm, errorHandler)))
return mlir::failure();
} else {
MLIRToLLVMPassPipelineConfig config(llvm::OptimizationLevel::O2);
std::optional<llvm::OptimizationLevel> level =
getOptimizationLevel(OptLevel);
if (!level) {
errs() << "Error invalid optimization level\n";
return mlir::failure();
}
MLIRToLLVMPassPipelineConfig config(*level);
// TODO: config.StackArrays should be set here?
config.EnableOpenMP = true; // assume the input contains OpenMP
config.AliasAnalysis = enableAliasAnalysis && !testGeneratorMode;
config.LoopVersioning = OptLevel > 2;
if (codeGenLLVM) {
// Run only CodeGen passes.
fir::createDefaultFIRCodeGenPassPipeline(pm, config);