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

Aaron Jomy via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 3 04:00:43 PST 2026


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

>From b3883628f69239c3bb3c206c32a6601685b6663d Mon Sep 17 00:00:00 2001
From: Aaron Jomy <aaronjomyjoseph at gmail.com>
Date: Fri, 23 Oct 2026 23:53:11 +0200
Subject: [PATCH 1/2] [clang-repl] Take the opt level defaults from the driver
 and cc1

setOptLevel updates only OptimizationLevel, OptimizeSize and the
inlining mode, but the -O flag decides more, such as loop unrolling and
the vectorizers. A clang-repl session raised from -O0 to -O2 currently
runs without them.

Compare the defaults of the startup and new -O flags and move every
option still at its startup default to the new one. Options set
explicitly at startup keep their value.

Assisted-by: Claude Opus 5.5
---
 clang/include/clang/Interpreter/Interpreter.h |  9 +++-
 clang/lib/Interpreter/Interpreter.cpp         | 48 ++++++++++++++++---
 .../unittests/Interpreter/InterpreterTest.cpp | 40 +++++++++++++++-
 3 files changed, 86 insertions(+), 11 deletions(-)

diff --git a/clang/include/clang/Interpreter/Interpreter.h b/clang/include/clang/Interpreter/Interpreter.h
index 5228b7fe80bd32..d132b1d93dae16 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -40,6 +40,7 @@ namespace driver {
 class Compilation;
 } // namespace driver
 
+class CodeGenOptions;
 class CompilerInstance;
 class CXXRecordDecl;
 class Decl;
@@ -133,6 +134,9 @@ class Interpreter {
   /// Compiler instance performing the incremental compilation.
   std::unique_ptr<CompilerInstance> CI;
 
+  /// CI's startup CodeGenOptions, to tell explicit options from -O defaults.
+  std::unique_ptr<const CodeGenOptions> InitialCodeGenOpts;
+
   /// An optional compiler instance for CUDA offloading
   std::unique_ptr<CompilerInstance> DeviceCI;
 
@@ -172,8 +176,9 @@ class Interpreter {
 
   /// Set the optimization level and size used to emit subsequently parsed
   /// input. \p OptSize mirrors \c CodeGenOptions::OptimizeSize (1 for -Os,
-  /// 2 for -Oz).
-  void setOptLevel(unsigned OptLevel, unsigned OptSize = 0);
+  /// 2 for -Oz). Options not set explicitly at startup take the defaults of
+  /// the new -O flag. Fails if no -O flag matches \p OptLevel and \p OptSize.
+  llvm::Error setOptLevel(unsigned OptLevel, unsigned OptSize = 0);
 
   /// Undo N previous incremental inputs.
   llvm::Error Undo(unsigned N = 1);
diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp
index d6cce74b7275f7..c3b85b7f5d3edf 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -27,6 +27,7 @@
 #include "clang/CodeGen/CodeGenAction.h"
 #include "clang/CodeGen/ObjectFilePCHContainerWriter.h"
 #include "clang/Driver/Compilation.h"
+#include "clang/Driver/CreateInvocationFromArgs.h"
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/Job.h"
 #include "clang/Driver/Tool.h"
@@ -295,7 +296,8 @@ struct PragmaReplHandler : public PragmaHandler {
       return;
     }
 
-    Interp.setOptLevel(Level->first, Level->second);
+    if (llvm::Error Err = Interp.setOptLevel(Level->first, Level->second))
+      llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
   }
 };
 
@@ -439,6 +441,8 @@ Interpreter::Interpreter(std::unique_ptr<CompilerInstance> Instance,
                          std::unique_ptr<clang::ASTConsumer> Consumer)
     : IncrExecutorBuilder(std::move(IEB)) {
   CI = std::move(Instance);
+  InitialCodeGenOpts =
+      std::make_unique<const CodeGenOptions>(CI->getCodeGenOpts());
   llvm::ErrorAsOutParameter EAO(&ErrOut);
   auto LLVMCtx = std::make_unique<llvm::LLVMContext>();
   TSCtx = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(LLVMCtx));
@@ -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);
+  if (!To)
+    return To.takeError();
+  auto From =
+      optFlagCodeGenOpts(*CI, Initial.OptimizationLevel, Initial.OptimizeSize);
+  if (!From)
+    return From.takeError();
+  // An option that started at the default of the startup flag follows the
+  // level. One the startup arguments set keeps its value.
+  CodeGenOptions &CGO = CI->getCodeGenOpts();
+#define CODEGENOPT(Name, Bits, Default, Compatibility)                         \
+  if (Initial.Name == From->Name)                                              \
+    CGO.Name = To->Name;
+#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility)              \
+  if (Initial.get##Name() == From->get##Name())                                \
+    CGO.set##Name(To->get##Name());
+#include "clang/Basic/CodeGenOptions.def"
+  return llvm::Error::success();
 }
 
 ASTContext &Interpreter::getASTContext() {
diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp b/clang/unittests/Interpreter/InterpreterTest.cpp
index 41c1facc8f2f08..2c7ef8b72f160f 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/Function.h"
 #include "llvm/IR/Module.h"
 #include "llvm/TargetParser/Host.h"
+#include "llvm/Testing/Support/Error.h"
 
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -586,7 +587,7 @@ TEST_F(InterpreterTest, SetOptLevel) {
   EXPECT_TRUE(F0->hasFnAttribute(llvm::Attribute::OptimizeNone));
 
   // A change only takes effect on the next parsed module.
-  Interp->setOptLevel(2);
+  cantFail(Interp->setOptLevel(2));
 
   auto &PTU1 = cantFail(Interp->Parse("extern \"C\" int f1() { return 1; }"));
   llvm::Function *F1 = PTU1.TheModule->getFunction("f1");
@@ -595,7 +596,7 @@ TEST_F(InterpreterTest, SetOptLevel) {
   EXPECT_FALSE(F1->hasFnAttribute(llvm::Attribute::NoInline));
 
   // -Oz is level 2, size 2.
-  Interp->setOptLevel(2, 2);
+  cantFail(Interp->setOptLevel(2, 2));
 
   auto &PTU2 = cantFail(Interp->Parse("extern \"C\" int f2() { return 2; }"));
   llvm::Function *F2 = PTU2.TheModule->getFunction("f2");
@@ -651,6 +652,41 @@ TEST_F(InterpreterTest, PragmaOptimizeLevel) {
   EXPECT_TRUE(HasAttr(PTU6, "f6", llvm::Attribute::OptimizeNone));
 }
 
+TEST_F(InterpreterTest, SetOptLevelMatchesOptFlag) {
+  std::unique_ptr<Interpreter> Interp = createInterpreter();
+
+  struct {
+    const char *Flag;
+    unsigned Level, Size;
+  } Levels[] = {{"-O2", 2, 0}, {"-O3", 3, 0}, {"-Os", 2, 1},
+                {"-Oz", 2, 2}, {"-O1", 1, 0}, {"-O0", 0, 0}};
+  for (const auto &L : Levels) {
+    cantFail(Interp->setOptLevel(L.Level, L.Size));
+    std::unique_ptr<Interpreter> Ref = createInterpreter({L.Flag});
+    const CodeGenOptions &Got = Interp->getCompilerInstance()->getCodeGenOpts();
+    const CodeGenOptions &Want = Ref->getCompilerInstance()->getCodeGenOpts();
+#define CODEGENOPT(Name, Bits, Default, Compatibility)                         \
+  EXPECT_EQ(Got.Name, Want.Name) << #Name << " at " << L.Flag;
+#define ENUM_CODEGENOPT(Name, Type, Bits, Default, Compatibility)              \
+  EXPECT_EQ(Got.get##Name(), Want.get##Name()) << #Name << " at " << L.Flag;
+#include "clang/Basic/CodeGenOptions.def"
+  }
+
+  // No -O flag sets level 3 with size 1.
+  EXPECT_THAT_ERROR(Interp->setOptLevel(3, 1), llvm::Failed());
+}
+
+TEST_F(InterpreterTest, SetOptLevelKeepsExplicitOptions) {
+  std::unique_ptr<Interpreter> Interp =
+      createInterpreter({"-O2", "-fno-vectorize"});
+  const CodeGenOptions &CGO = Interp->getCompilerInstance()->getCodeGenOpts();
+  for (unsigned Level : {3, 0, 2}) {
+    cantFail(Interp->setOptLevel(Level));
+    EXPECT_FALSE(CGO.VectorizeLoop);
+    EXPECT_EQ(CGO.VectorizeSLP, Level > 0);
+  }
+}
+
 TEST_F(InterpreterTest, TranslationUnit_CanonicalDecl) {
   std::vector<const char *> Args;
   std::unique_ptr<Interpreter> Interp = createInterpreter(Args);

>From 7a210687c711aad9a2945882ad37d71a86ff61db Mon Sep 17 00:00:00 2001
From: Aaron Jomy <aaronjomyjoseph at gmail.com>
Date: Tue, 3 Nov 2026 08:32:15 +0100
Subject: [PATCH 2/2] [clang-repl] Check the kept startup options in a lit test

---
 .../pragma-optimize-explicit-options.cpp      | 32 +++++++++++++++++++
 .../unittests/Interpreter/InterpreterTest.cpp | 11 -------
 2 files changed, 32 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/Interpreter/pragma-optimize-explicit-options.cpp

diff --git a/clang/test/Interpreter/pragma-optimize-explicit-options.cpp b/clang/test/Interpreter/pragma-optimize-explicit-options.cpp
new file mode 100644
index 00000000000000..b9f96951fed1b8
--- /dev/null
+++ b/clang/test/Interpreter/pragma-optimize-explicit-options.cpp
@@ -0,0 +1,32 @@
+// REQUIRES: host-supports-jit
+//
+// An option set at startup keeps its value when '#pragma clang repl optimize'
+// changes the level. -fno-inline-functions marks every function noinline.
+//
+// RUN: cat %s | clang-repl -Xcc -O2 -Xcc -fno-inline-functions \
+// RUN:   -Xcc -Xclang -Xcc -emit-llvm | FileCheck %s
+
+extern "C" int f_o2(int x) { return x; }
+// CHECK:      ; Function Attrs: {{.*}}noinline
+// CHECK-NOT:  optnone
+// CHECK-SAME: {{$}}
+// CHECK-NEXT: define {{.*}}i32 @f_o2(
+
+#pragma clang repl optimize(O3)
+extern "C" int f_o3(int x) { return x; }
+// CHECK:      ; Function Attrs: {{.*}}noinline
+// CHECK-NOT:  optnone
+// CHECK-SAME: {{$}}
+// CHECK-NEXT: define {{.*}}i32 @f_o3(
+
+#pragma clang repl optimize(O0)
+extern "C" int f_o0(int x) { return x; }
+// CHECK:      ; Function Attrs: {{.*}}noinline {{.*}}optnone
+// CHECK-NEXT: define {{.*}}i32 @f_o0(
+
+#pragma clang repl optimize(O2)
+extern "C" int f_back(int x) { return x; }
+// CHECK:      ; Function Attrs: {{.*}}noinline
+// CHECK-NOT:  optnone
+// CHECK-SAME: {{$}}
+// CHECK-NEXT: define {{.*}}i32 @f_back(
diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp b/clang/unittests/Interpreter/InterpreterTest.cpp
index 2c7ef8b72f160f..d1c773e81890c8 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -676,17 +676,6 @@ TEST_F(InterpreterTest, SetOptLevelMatchesOptFlag) {
   EXPECT_THAT_ERROR(Interp->setOptLevel(3, 1), llvm::Failed());
 }
 
-TEST_F(InterpreterTest, SetOptLevelKeepsExplicitOptions) {
-  std::unique_ptr<Interpreter> Interp =
-      createInterpreter({"-O2", "-fno-vectorize"});
-  const CodeGenOptions &CGO = Interp->getCompilerInstance()->getCodeGenOpts();
-  for (unsigned Level : {3, 0, 2}) {
-    cantFail(Interp->setOptLevel(Level));
-    EXPECT_FALSE(CGO.VectorizeLoop);
-    EXPECT_EQ(CGO.VectorizeSLP, Level > 0);
-  }
-}
-
 TEST_F(InterpreterTest, TranslationUnit_CanonicalDecl) {
   std::vector<const char *> Args;
   std::unique_ptr<Interpreter> Interp = createInterpreter(Args);



More information about the cfe-commits mailing list