[clang] [clang-repl] Take the opt level defaults from the driver and cc1 (PR #237999)

Vassil Vassilev via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 3 21:12:36 PST 2026


================
@@ -645,12 +649,42 @@ llvm::Expected<IncrementalExecutor &> Interpreter::getExecutionEngine() {
   return *IncrExecutor.get();
 }
 
-void Interpreter::setOptLevel(unsigned OptLevel, unsigned OptSize) {
-  CodeGenOptions &CGO = getCompilerInstance()->getCodeGenOpts();
-  CGO.OptimizationLevel = OptLevel;
-  CGO.OptimizeSize = OptSize;
-  CGO.setInlining(OptLevel ? CodeGenOptions::NormalInlining
-                           : CodeGenOptions::OnlyAlwaysInlining);
+// Obtain the CodeGenOptions generated for a fresh compilation on the
+// CompilerInstance target with the -O flag for Level and Size.
+static llvm::Expected<CodeGenOptions>
+optFlagCodeGenOpts(const CompilerInstance &CI, unsigned Level, unsigned Size) {
+  std::string Flag =
+      Size == 0 ? "-O" + llvm::utostr(Level) : (Size == 1 ? "-Os" : "-Oz");
+  std::string Target = "--target=" + CI.getTargetOpts().Triple;
+  std::unique_ptr<CompilerInvocation> Invocation = createInvocation(
+      {"clang", "-xc++", Flag.c_str(), Target.c_str(), "<<< inputs >>>"});
+  if (!Invocation || Invocation->getCodeGenOpts().OptimizationLevel != Level ||
+      Invocation->getCodeGenOpts().OptimizeSize != Size)
+    return llvm::createStringError(
+        "no -O flag sets optimization level %u with size %u", Level, Size);
+  return Invocation->getCodeGenOpts();
+}
+
+llvm::Error Interpreter::setOptLevel(unsigned OptLevel, unsigned OptSize) {
+  const CodeGenOptions &Initial = *InitialCodeGenOpts;
+  auto To = optFlagCodeGenOpts(*CI, OptLevel, OptSize);
----------------
vgvassilev wrote:

That is probably slow but I think it violates layering. We will need to think about a better design here. Reconstructing a compiler invocation seems hacky. 

https://github.com/llvm/llvm-project/pull/237999


More information about the cfe-commits mailing list