[clang] [flang] [llvm] [polly] [Plugins] Make plugins inherit from PassPlugin (PR #247742)
Alexis Engelke via cfe-commits
cfe-commits at lists.llvm.org
Wed Dec 2 01:23:35 PST 2026
https://github.com/aengelke updated https://github.com/llvm/llvm-project/pull/247742
>From a558ba3698780b29d8ae636ee3a1912556220e22 Mon Sep 17 00:00:00 2001
From: Alexis Engelke <alexis.engelke at inria.fr>
Date: Tue, 1 Dec 2026 18:56:35 +0100
Subject: [PATCH 1/2] [Plugins] Make plugins inherit from PassPlugin
Solve the problem of plugins requiring global state for arguments by
making PassPlugin a polymorphic class from which plugins inherit.
---
clang/lib/CodeGen/BackendUtil.cpp | 16 +-
clang/lib/CodeGen/CMakeLists.txt | 1 -
clang/lib/Frontend/CMakeLists.txt | 1 +
clang/lib/Frontend/CompilerInstance.cpp | 11 +-
flang/lib/Frontend/FrontendActions.cpp | 6 +-
.../ExecuteCompilerInvocation.cpp | 13 +-
llvm/docs/ReleaseNotes.md | 17 +-
llvm/docs/WritingAnLLVMNewPMPass.md | 62 ++++--
llvm/examples/Bye/Bye.cpp | 89 ++++-----
llvm/examples/Ciao/Ciao.cpp | 58 +++---
llvm/examples/IRTransforms/SimplifyCFG.cpp | 67 +++----
llvm/include/llvm/Plugins/PassPlugin.h | 177 ++++++++----------
llvm/lib/LTO/LTO.cpp | 15 +-
llvm/lib/LTO/LTOBackend.cpp | 18 +-
llvm/lib/Plugins/PassPlugin.cpp | 51 +++--
llvm/tools/llc/NewPMDriver.cpp | 5 +-
llvm/tools/llc/NewPMDriver.h | 3 +-
llvm/tools/llc/llc.cpp | 22 +--
llvm/tools/opt/NewPMDriver.cpp | 7 +-
llvm/tools/opt/NewPMDriver.h | 4 +-
llvm/tools/opt/optdriver.cpp | 13 +-
.../InlineAdvisorPlugin.cpp | 22 ++-
.../InlineOrderPlugin/InlineOrderPlugin.cpp | 35 ++--
.../PluginInlineAdvisorAnalysisTest.cpp | 4 +-
.../PluginInlineOrderAnalysisTest.cpp | 4 +-
.../Plugins/DoublerPlugin/DoublerPlugin.cpp | 10 +-
llvm/unittests/Passes/Plugins/PluginsTest.cpp | 41 ++--
llvm/unittests/Passes/Plugins/TestPlugin.h | 1 -
.../Passes/Plugins/TestPlugin/TestPlugin.cpp | 10 +-
polly/lib/Support/RegisterPasses.cpp | 20 +-
30 files changed, 405 insertions(+), 398 deletions(-)
diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp
index d86c52432b42eb..426981f21be715 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -116,10 +116,6 @@
using namespace clang;
using namespace llvm;
-#define HANDLE_EXTENSION(Ext) \
- llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
-#include "llvm/Support/Extension.def"
-
// Path and name of file used for profile generation
static std::string
getProfileGenName(const cl::LibraryOptionsContext &LibraryOptions,
@@ -982,9 +978,6 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
Plugin->registerPassBuilderCallbacks(PB);
for (const auto &PassCallback : CodeGenOpts.PassBuilderCallbacks)
PassCallback(PB);
-#define HANDLE_EXTENSION(Ext) \
- get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
-#include "llvm/Support/Extension.def"
// Register the target library analysis directly and give it a customized
// preset TLI.
@@ -1264,7 +1257,7 @@ void EmitAssemblyHelper::RunCodegenPipeline(
// Invoke pre-codegen callback from plugin, which might want to take over the
// entire code generation itself.
for (const std::unique_ptr<llvm::PassPlugin> &Plugin : CI.getPassPlugins()) {
- if (Plugin->invokePreCodeGenCallback(
+ if (Plugin->preCodeGenCallback(
*TM, *TheModule, *OS, DwoOS ? &DwoOS->os() : nullptr, CGFT,
!CodeGenOpts.VerifyModule, /*DisableSimplifyLibCalls=*/false,
/*MSI=*/nullptr, CI.getVirtualFileSystemPtr()))
@@ -1533,12 +1526,7 @@ bool clang::passPluginArguments(CompilerInstance &CI) {
const std::vector<std::string> &Args = CI.getCodeGenOpts().PassPluginArgs;
if (Args.empty())
return true;
- SmallVector<PassPluginLibraryInfo, 0> Infos;
- for (const std::unique_ptr<PassPlugin> &Plugin : CI.getPassPlugins())
- Infos.push_back(Plugin->getInfo());
-#define HANDLE_EXTENSION(Ext) Infos.push_back(get##Ext##PluginInfo());
-#include "llvm/Support/Extension.def"
- if (Error E = llvm::passPluginArguments(Infos, Args)) {
+ if (Error E = llvm::passPluginArguments(CI.getPassPlugins(), Args)) {
CI.getDiagnostics().Report(diag::err_fe_pass_plugin_arg)
<< toString(std::move(E));
return false;
diff --git a/clang/lib/CodeGen/CMakeLists.txt b/clang/lib/CodeGen/CMakeLists.txt
index 1ac56d0ad1b83d..6af2f951724958 100644
--- a/clang/lib/CodeGen/CMakeLists.txt
+++ b/clang/lib/CodeGen/CMakeLists.txt
@@ -10,7 +10,6 @@ set(LLVM_LINK_COMPONENTS
Coroutines
Coverage
Demangle
- Extensions
FrontendDriver
FrontendHLSL
FrontendOpenMP
diff --git a/clang/lib/Frontend/CMakeLists.txt b/clang/lib/Frontend/CMakeLists.txt
index c40baa3657fe1e..6747b6884669df 100644
--- a/clang/lib/Frontend/CMakeLists.txt
+++ b/clang/lib/Frontend/CMakeLists.txt
@@ -3,6 +3,7 @@ add_subdirectory(Rewrite)
set(LLVM_LINK_COMPONENTS
BitReader
BitstreamReader
+ Extensions
Option
Plugins
ProfileData
diff --git a/clang/lib/Frontend/CompilerInstance.cpp b/clang/lib/Frontend/CompilerInstance.cpp
index 1dd048fe633e57..625e6837e5d276 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -70,6 +70,10 @@
#include <time.h>
#include <utility>
+#define HANDLE_EXTENSION(Ext) \
+ llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
+#include "llvm/Support/Extension.def"
+
using namespace clang;
CompilerInstance::CompilerInstance(
@@ -1114,13 +1118,18 @@ void CompilerInstance::LoadRequestedPlugins() {
// Load and store pass plugins for the back-end.
for (const std::string &Path : getCodeGenOpts().PassPlugins) {
if (auto PassPlugin = llvm::PassPlugin::load(Path)) {
- PassPlugins.emplace_back(std::make_unique<llvm::PassPlugin>(*PassPlugin));
+ PassPlugins.emplace_back(std::move(PassPlugin.get()));
} else {
getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
<< Path << toString(PassPlugin.takeError());
}
}
+ // Add plugins statically compiled into LLVM.
+#define HANDLE_EXTENSION(Ext) \
+ PassPlugins.push_back(get##Ext##PluginInfo().Instantiate());
+#include "llvm/Support/Extension.def"
+
// Check if any of the loaded plugins replaces the main AST action
for (const FrontendPluginRegistry::entry &Plugin :
FrontendPluginRegistry::entries()) {
diff --git a/flang/lib/Frontend/FrontendActions.cpp b/flang/lib/Frontend/FrontendActions.cpp
index c7f5bde0b252c5..618602acd955e1 100644
--- a/flang/lib/Frontend/FrontendActions.cpp
+++ b/flang/lib/Frontend/FrontendActions.cpp
@@ -949,7 +949,7 @@ static void generateMachineCodeOrAssemblyImpl(
// Invoke pre-codegen callback from plugin, which might want to take over the
// entire code generation itself.
for (const std::unique_ptr<llvm::PassPlugin> &plugin : ci.getPassPlugins()) {
- if (plugin->invokePreCodeGenCallback(
+ if (plugin->preCodeGenCallback(
tm, llvmModule, os, dwoOS ? &dwoOS->os() : nullptr, cgft,
/*DisableVerify=*/true, /*DisableSimplifyLibCalls=*/false,
/*MSI=*/nullptr, llvm::vfs::getRealFileSystem())) {
@@ -1050,10 +1050,6 @@ void CodeGenAction::runOptimizationPipeline(llvm::raw_pwrite_stream &os) {
// Register plugin callbacks with PB.
for (const std::unique_ptr<llvm::PassPlugin> &plugin : ci.getPassPlugins())
plugin->registerPassBuilderCallbacks(pb);
- // Register static plugin extensions.
-#define HANDLE_EXTENSION(Ext) \
- get##Ext##PluginInfo().RegisterPassBuilderCallbacks(pb);
-#include "llvm/Support/Extension.def"
// Register the target library analysis directly and give it a customized
// preset TLI depending on -fveclib
diff --git a/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
index 0391042c540f33..19263474e4de1a 100644
--- a/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ b/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -30,6 +30,10 @@
#include "llvm/Plugins/PassPlugin.h"
#include "llvm/Support/CommandLine.h"
+#define HANDLE_EXTENSION(Ext) \
+ llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
+#include "llvm/Support/Extension.def"
+
namespace Fortran::frontend {
static std::unique_ptr<FrontendAction>
@@ -181,9 +185,9 @@ bool executeCompilerInvocation(CompilerInstance *flang) {
// Load and store LLVM pass plugins.
for (const std::string &path :
flang->getInvocation().getCodeGenOpts().LLVMPassPlugins) {
- if (llvm::Expected<llvm::PassPlugin> passPlugin =
+ if (llvm::Expected<std::unique_ptr<llvm::PassPlugin>> passPlugin =
llvm::PassPlugin::load(path)) {
- flang->addPassPlugin(std::make_unique<llvm::PassPlugin>(*passPlugin));
+ flang->addPassPlugin(std::move(passPlugin.get()));
} else {
unsigned diagID = flang->getDiagnostics().getCustomDiagID(
clang::DiagnosticsEngine::Error, "unable to load plugin '%0': '%1'");
@@ -192,6 +196,11 @@ bool executeCompilerInvocation(CompilerInstance *flang) {
}
}
+ // Add plugins statically compiled into LLVM.
+#define HANDLE_EXTENSION(Ext) \
+ flang->addPassPlugin(get##Ext##PluginInfo().Instantiate());
+#include "llvm/Support/Extension.def"
+
// Honor -mllvm. This should happen AFTER plugins have been loaded!
if (!flang->getFrontendOpts().llvmArgs.empty()) {
unsigned numArgs = flang->getFrontendOpts().llvmArgs.size();
diff --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md
index ee81b2f960d69b..f3b9e21adce92e 100644
--- a/llvm/docs/ReleaseNotes.md
+++ b/llvm/docs/ReleaseNotes.md
@@ -240,6 +240,13 @@ Makes programs 10x faster by doing Special New Thing.
only to allow incremental migration of LLVM IR tests, and will be removed in
the near future.
+* LLVM pass plugins are now have to subclass `PassPlugin`.
+ Plugin options are no longer accepted as ordinary LLVM options by tools.
+ Instead, `opt` and `llc` accept `-plugin-arg=<plugin>,<arg>` and pass `<arg`> to the new plugin callback `parseArguments`.
+ A plugin that defines `cl::opt` has to call `cl::ParseCommandLineOptions` itself inside `ParseArguments`.
+
+* The pass plugin `preCodeGenCallback` parameters now match `llvm::runCodeGenPipeline`.
+
### Changes to building LLVM
* The minimum required CMake version to build LLVM has been raised from 3.20.0
@@ -579,15 +586,7 @@ Makes programs 10x faster by doing Special New Thing.
* `llvm-mc` now supports `--verify[=<prefixes>]` to check diagnostics against `<prefix>-<kind> {{...}}` comments in the input instead of printing them.
* `opt` and `llc` load `-load-pass-plugin` plugins after parsing the command line, so a loaded plugin's options are no longer accepted as ordinary options.
- Pass them with `-plugin-arg=<plugin>,<arg>` (see below).
-
-* `opt` and `llc` accept `-plugin-arg=<plugin>,<arg>`, which passes `<arg>` to the new `PassPluginLibraryInfo::ParseArguments` callback of the pass plugin named `<plugin>`.
- A plugin that defines `cl::opt` has to call `cl::ParseCommandLineOptions` itself inside `ParseArguments`.
- `LLVM_PLUGIN_API_VERSION` is now 3.
-
-* `PassPluginLibraryInfo::PreCodeGenCallback` now matches the parameters of the
- new `llvm::runCodeGenPipeline()`.
- This is also covered by the `LLVM_PLUGIN_API_VERSION` bump to 3.
+ Pass them with `-plugin-arg=<plugin>,<arg>` (see above).
* llvm-offload-binary can now compress packaged binaries using zstd or zlib.
diff --git a/llvm/docs/WritingAnLLVMNewPMPass.md b/llvm/docs/WritingAnLLVMNewPMPass.md
index 4ea4578ae53b9f..2642e755f8a025 100644
--- a/llvm/docs/WritingAnLLVMNewPMPass.md
+++ b/llvm/docs/WritingAnLLVMNewPMPass.md
@@ -243,19 +243,34 @@ add_llvm_pass_plugin(MyPassName source.cpp)
See the definition of `add_llvm_pass_plugin` for more CMake details.
-The pass must provide at least one of two entry points for the new pass manager,
-one for static registration and one for dynamically loaded plugins:
+Pass plugins inherit from the `PassPlugin` class. The driver will instantiate
+loaded plugins, pass plugin arguments to the `parseArguments()` function, and
+invoke callbacks where appropriate. The basic skeleton of a pass plugin looks
+like this:
-- `llvm::PassPluginLibraryInfo get##Name##PluginInfo();`
-- `extern "C" ::llvm::PassPluginLibraryInfo llvmGetPassPluginInfo() LLVM_ATTRIBUTE_WEAK;`
+```c++
+// Subclass PassPlugin
+class MyPassPluginName {
+public:
+ MyPassNamePlugin() : PassPlugin("MyPassName") {}
+ void registerPassBuilderCallbacks(PassBuilder &PB) override {
+ // Register callbacks on PB here.
+ }
+};
+
+// Entry point used for dynamically-linked/loaded plugins.
+extern "C" ::llvm::PassPluginLibraryInfo llvmGetPassPluginInfo() LLVM_ATTRIBUTE_WEAK {
+ return llvm::getPassPluginLibraryInfo<MyPassNamePlugin>();
+}
+```
-Pass plugins are compiled and linked dynamically by default. Setting
-`LLVM_${NAME}_LINK_INTO_TOOLS` to `ON` turns the project into a statically
-linked extension.
+In-tree pass plugins can also be linked statically into LLVM when configured
+with `LLVM_${NAME}_LINK_INTO_TOOLS=ON`. The entry for statically-linked plugins
+is `llvm::PassPluginLibraryInfo get##Name##PluginInfo();`.
-For an in-tree example, see `llvm/examples/Bye/`.
+### Driver-side handling of plugins
-To make `PassBuilder` aware of statically linked pass plugins:
+To make `PassBuilder` aware of pass plugins:
```c++
// Declare plugin extension function declarations.
@@ -264,18 +279,27 @@ To make `PassBuilder` aware of statically linked pass plugins:
...
-// Register plugin extensions in PassBuilder.
-#define HANDLE_EXTENSION(Ext) get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
+// Vector of plugin instantiations.
+SmallVector<std::unique_ptr<PassPlugin>> Plugins;
+
+// Instantiate all statically-linked plugins.
+#define HANDLE_EXTENSION(Ext) \
+ Plugins.push_back(get##Ext##PluginInfo().Instantiate());
#include "llvm/Support/Extension.def"
-```
-To make `PassBuilder` aware of dynamically linked pass plugins:
+// Load and instantiate dynamic plugin(s).
+for (const auto PathToPlugin : PluginPaths) {
+ Expected<std::unique_ptr<PassPlugin>> Plugin = PassPlugin::load(PathToPlugin);
+ if (!Plugin)
+ reportError(Plugin.takeError());
+ Plugins.push_back(std::move(Plugin.get());
+}
+
+// Pass arguments to plugins.
+if (Error E = passPluginArguments(Plugins, PluginArgs))
+ reportError(E);
-```c++
-// Load plugin dynamically.
-auto Plugin = PassPlugin::load(PathToPlugin);
-if (!Plugin)
- report_error();
// Register plugin extensions in PassBuilder.
-Plugin.registerPassBuilderCallbacks(PB);
+for (auto &Plugin : Plugins)
+ Plugin->registerPassBuilderCallbacks(PB);
```
diff --git a/llvm/examples/Bye/Bye.cpp b/llvm/examples/Bye/Bye.cpp
index ae4d114f14399b..fb0f84d6a36e5e 100644
--- a/llvm/examples/Bye/Bye.cpp
+++ b/llvm/examples/Bye/Bye.cpp
@@ -45,40 +45,55 @@ struct Bye : OptionalPassInfoMixin<Bye> {
}
};
-void registerPassBuilderCallbacks(PassBuilder &PB) {
- PB.registerVectorizerStartEPCallback(
- [](llvm::FunctionPassManager &PM, OptimizationLevel Level) {
- PM.addPass(Bye());
- });
- PB.registerPipelineParsingCallback(
- [](StringRef Name, llvm::FunctionPassManager &PM,
- ArrayRef<llvm::PassBuilder::PipelineElement>) {
- if (Name == "goodbye") {
+class ByePlugin : public PassPlugin {
+public:
+ ByePlugin() : PassPlugin("Bye") {}
+
+ void registerPassBuilderCallbacks(PassBuilder &PB) override {
+ PB.registerVectorizerStartEPCallback(
+ [](llvm::FunctionPassManager &PM, OptimizationLevel Level) {
PM.addPass(Bye());
- return true;
- }
- return false;
- });
-}
+ });
+ PB.registerPipelineParsingCallback(
+ [](StringRef Name, llvm::FunctionPassManager &PM,
+ ArrayRef<llvm::PassBuilder::PipelineElement>) {
+ if (Name == "goodbye") {
+ PM.addPass(Bye());
+ return true;
+ }
+ return false;
+ });
+ }
-bool preCodeGenCallback(TargetMachine &, Module &M, raw_pwrite_stream &OS,
- raw_pwrite_stream *DwoOS, CodeGenFileType CGFT, bool,
- bool, const ModuleSummaryIndex *,
- IntrusiveRefCntPtr<vfs::FileSystem>) {
- if (LastWords) {
- if (CGFT != CodeGenFileType::AssemblyFile) {
- // Test error emission.
- M.getContext().emitError("last words unsupported for binary output");
- return false;
+ bool preCodeGenCallback(TargetMachine &, Module &M, raw_pwrite_stream &OS,
+ raw_pwrite_stream *DwoOS, CodeGenFileType CGFT, bool,
+ bool, const ModuleSummaryIndex *,
+ IntrusiveRefCntPtr<vfs::FileSystem>) override {
+ if (LastWords) {
+ if (CGFT != CodeGenFileType::AssemblyFile) {
+ // Test error emission.
+ M.getContext().emitError("last words unsupported for binary output");
+ return false;
+ }
+ OS << "CodeGen Bye\n";
+ if (DwoOS)
+ *DwoOS << "DwoGen Bye\n";
+ return true; // Suppress remaining compilation pipeline.
}
- OS << "CodeGen Bye\n";
- if (DwoOS)
- *DwoOS << "DwoGen Bye\n";
- return true; // Suppress remaining compilation pipeline.
+ // Do nothing.
+ return false;
}
- // Do nothing.
- return false;
-}
+
+ Error parseArguments(ArrayRef<const char *> Args) override {
+ SmallVector<const char *, 0> Argv = {"Bye"};
+ append_range(Argv, Args);
+ std::string Msg;
+ raw_string_ostream OS(Msg);
+ if (!cl::ParseCommandLineOptions(Argv.size(), Argv.data(), "", &OS))
+ return createStringError(StringRef(Msg).trim());
+ return Error::success();
+ }
+};
} // namespace
@@ -88,21 +103,9 @@ static RegisterPass<LegacyBye> X("goodbye", "Good Bye World Pass",
false /* Only looks at CFG */,
false /* Analysis Pass */);
-static Error parseArguments(ArrayRef<const char *> Args) {
- SmallVector<const char *, 0> Argv = {"Bye"};
- append_range(Argv, Args);
- std::string Msg;
- raw_string_ostream OS(Msg);
- if (!cl::ParseCommandLineOptions(Argv.size(), Argv.data(), "", &OS))
- return createStringError(StringRef(Msg).trim());
- return Error::success();
-}
-
/* New PM Registration */
llvm::PassPluginLibraryInfo getByePluginInfo() {
- return {LLVM_PLUGIN_API_VERSION, "Bye",
- LLVM_VERSION_STRING, registerPassBuilderCallbacks,
- preCodeGenCallback, parseArguments};
+ return getPassPluginLibraryInfo<ByePlugin>();
}
#ifndef LLVM_BYE_LINK_INTO_TOOLS
diff --git a/llvm/examples/Ciao/Ciao.cpp b/llvm/examples/Ciao/Ciao.cpp
index 98e137615ad669..1762539299db95 100644
--- a/llvm/examples/Ciao/Ciao.cpp
+++ b/llvm/examples/Ciao/Ciao.cpp
@@ -47,38 +47,42 @@ static RegisterTargetPassConfigCallback RegisterLegacyCiao{
namespace {
bool ForwardCodeGen = false;
-// Take over code generation and forward it to the default pipeline. Plugins
-// that run an LLVM-based pipeline of their own work this way.
-bool preCodeGenCallback(TargetMachine &TM, Module &M, raw_pwrite_stream &OS,
- raw_pwrite_stream *DwoOS, CodeGenFileType CGFT,
- bool DisableVerify, bool DisableSimplifyLibCalls,
- const ModuleSummaryIndex *MSI,
- IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
- if (!ForwardCodeGen)
- return false;
- // Leave a trace in the output that tests can check for.
- for (Function &F : M)
- if (!F.isDeclaration())
- F.setName("ciao_" + F.getName());
- if (Error Err =
- runCodeGenPipeline(TM, M, OS, DwoOS, CGFT, DisableVerify,
- DisableSimplifyLibCalls, MSI, std::move(VFS)))
- M.getContext().emitError(toString(std::move(Err)));
- return true;
-}
+class CiaoPlugin : public PassPlugin {
+public:
+ CiaoPlugin() : PassPlugin("Ciao") {}
-Error parseArguments(ArrayRef<const char *> Args) {
- for (StringRef Arg : Args)
- if (Arg == "forward-codegen")
- ForwardCodeGen = true;
- return Error::success();
-}
+ // Take over code generation and forward it to the default pipeline. Plugins
+ // that run an LLVM-based pipeline of their own work this way.
+ bool preCodeGenCallback(TargetMachine &TM, Module &M, raw_pwrite_stream &OS,
+ raw_pwrite_stream *DwoOS, CodeGenFileType CGFT,
+ bool DisableVerify, bool DisableSimplifyLibCalls,
+ const ModuleSummaryIndex *MSI,
+ IntrusiveRefCntPtr<vfs::FileSystem> VFS) override {
+ if (!ForwardCodeGen)
+ return false;
+ // Leave a trace in the output that tests can check for.
+ for (Function &F : M)
+ if (!F.isDeclaration())
+ F.setName("ciao_" + F.getName());
+ if (Error Err =
+ runCodeGenPipeline(TM, M, OS, DwoOS, CGFT, DisableVerify,
+ DisableSimplifyLibCalls, MSI, std::move(VFS)))
+ M.getContext().emitError(toString(std::move(Err)));
+ return true;
+ }
+
+ Error parseArguments(ArrayRef<const char *> Args) override {
+ for (StringRef Arg : Args)
+ if (Arg == "forward-codegen")
+ ForwardCodeGen = true;
+ return Error::success();
+ }
+};
} // namespace
// We use the pass-plugin for preCodeGenCallback and argument parsing. The
// legacy codegen pipeline relies on the static initialization.
extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
llvmGetPassPluginInfo() {
- return {LLVM_PLUGIN_API_VERSION, "Ciao", LLVM_VERSION_STRING, nullptr,
- preCodeGenCallback, parseArguments};
+ return getPassPluginLibraryInfo<CiaoPlugin>();
}
diff --git a/llvm/examples/IRTransforms/SimplifyCFG.cpp b/llvm/examples/IRTransforms/SimplifyCFG.cpp
index e62181b3451b22..56778d6d97c447 100644
--- a/llvm/examples/IRTransforms/SimplifyCFG.cpp
+++ b/llvm/examples/IRTransforms/SimplifyCFG.cpp
@@ -383,42 +383,45 @@ struct SimplifyCFGPass : public OptionalPassInfoMixin<SimplifyCFGPass> {
return PreservedAnalyses::none();
}
};
-} // namespace
-// Selects the tutorial version with -plugin-arg=SimplifyCFG,v1 (or v2, v3).
-static Error parseArguments(ArrayRef<const char *> Args) {
- std::optional<TutorialVersion> V;
- if (Args.size() == 1)
- V = StringSwitch<std::optional<TutorialVersion>>(Args[0])
- .Case("v1", V1)
- .Case("v2", V2)
- .Case("v3", V3)
- .Default(std::nullopt);
- if (!V)
- return createStringError(
- "SimplifyCFG: expected one argument, v1, v2 or v3");
- Version = *V;
- return Error::success();
-}
+class ExampleIRTransformsPlugin : public PassPlugin {
+public:
+ ExampleIRTransformsPlugin() : PassPlugin("SimplifyCFG") {}
+
+ void registerPassBuilderCallbacks(PassBuilder &PB) override {
+ PB.registerPipelineParsingCallback(
+ [](StringRef Name, llvm::FunctionPassManager &PM,
+ ArrayRef<llvm::PassBuilder::PipelineElement>) {
+ if (Name == "tut-simplifycfg") {
+ PM.addPass(SimplifyCFGPass());
+ return true;
+ }
+ return false;
+ });
+ }
+
+ // Selects the tutorial version with -plugin-arg=SimplifyCFG,v1 (or v2, v3).
+ Error parseArguments(ArrayRef<const char *> Args) override {
+ std::optional<TutorialVersion> V;
+ if (Args.size() == 1)
+ V = StringSwitch<std::optional<TutorialVersion>>(Args[0])
+ .Case("v1", V1)
+ .Case("v2", V2)
+ .Case("v3", V3)
+ .Default(std::nullopt);
+ if (!V)
+ return createStringError(
+ "SimplifyCFG: expected one argument, v1, v2 or v3");
+ Version = *V;
+ return Error::success();
+ }
+};
+
+} // namespace
/* New PM Registration */
llvm::PassPluginLibraryInfo getExampleIRTransformsPluginInfo() {
- return {LLVM_PLUGIN_API_VERSION,
- "SimplifyCFG",
- LLVM_VERSION_STRING,
- [](PassBuilder &PB) {
- PB.registerPipelineParsingCallback(
- [](StringRef Name, llvm::FunctionPassManager &PM,
- ArrayRef<llvm::PassBuilder::PipelineElement>) {
- if (Name == "tut-simplifycfg") {
- PM.addPass(SimplifyCFGPass());
- return true;
- }
- return false;
- });
- },
- nullptr,
- parseArguments};
+ return getPassPluginLibraryInfo<ExampleIRTransformsPlugin>();
}
#ifndef LLVM_EXAMPLEIRTRANSFORMS_LINK_INTO_TOOLS
diff --git a/llvm/include/llvm/Plugins/PassPlugin.h b/llvm/include/llvm/Plugins/PassPlugin.h
index d070e1c3d32c9e..72e8e4cb2b0e10 100644
--- a/llvm/include/llvm/Plugins/PassPlugin.h
+++ b/llvm/include/llvm/Plugins/PassPlugin.h
@@ -20,7 +20,9 @@
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/Error.h"
+#include "llvm/Support/VirtualFileSystemFwd.h"
#include <cstdint>
+#include <memory>
#include <string>
namespace llvm {
@@ -28,42 +30,36 @@ class Module;
class ModuleSummaryIndex;
class PassBuilder;
class TargetMachine;
-namespace vfs {
-class FileSystem;
-} // namespace vfs
-/// \macro LLVM_PLUGIN_API_VERSION
-/// Identifies the API version understood by this plugin.
-///
-/// When a plugin is loaded, the driver will check it's supported plugin version
-/// against that of the plugin. A mismatch is an error. The supported version
-/// will be incremented for ABI-breaking changes to the \c PassPluginLibraryInfo
-/// struct, i.e. when callbacks are added, removed, or reordered.
-#define LLVM_PLUGIN_API_VERSION 3
+/// A loaded pass plugin. This class is supposed to be subclassed out by plugin
+/// implementors; virtual functions provide extension points that are invoked by
+/// the driver. Hosts may invoke callbacks concurrently, e.g. for parallel
+/// ThinLTO backends, so plugins must guard any state they share between
+/// invocations.
+class LLVM_ABI PassPlugin {
+ StringRef Name;
-extern "C" {
-/// Information about the plugin required to load its passes
-///
-/// This struct defines the core interface for pass plugins and is supposed to
-/// be filled out by plugin implementors. Unused function pointers can be set to
-/// nullptr. LLVM-side users of a plugin are expected to use the \c PassPlugin
-/// class below to interface with it. Hosts may invoke callbacks concurrently,
-/// e.g. for parallel ThinLTO backends, so plugins must guard any state they
-/// share between invocations.
-struct PassPluginLibraryInfo {
- /// The API version understood by this plugin, usually \c
- /// LLVM_PLUGIN_API_VERSION
- uint32_t APIVersion;
- /// A meaningful name of the plugin. -plugin-arg=<PluginName>,<arg> passes
+public:
+ /// Set a meaningful name of the plugin. -plugin-arg=<PluginName>,<arg> passes
/// <arg> to the plugin with this name.
- const char *PluginName;
- /// The version of the plugin.
- const char *PluginVersion;
+ PassPlugin(llvm::StringRef Name) : Name(Name) {}
+ virtual ~PassPlugin();
- /// The callback for registering plugin passes with a \c PassBuilder
- /// instance
- void (*RegisterPassBuilderCallbacks)(PassBuilder &) = nullptr;
+ /// Attempts to load a pass plugin from a given file.
+ ///
+ /// \returns Returns an error if either the library cannot be found or loaded,
+ /// there is no public entry point, or the plugin implements the wrong API
+ /// version.
+ static Expected<std::unique_ptr<PassPlugin>> load(StringRef Filename);
+
+ StringRef getName() const { return Name; }
+
+ /// The callback for registering plugin passes with a PassBuilder.
+ virtual void registerPassBuilderCallbacks(PassBuilder &PB) {}
+ /// Invoke the pre-codegen callback. Keep the signature in sync with
+ /// llvm::runCodeGenPipeline().
+ ///
/// Callback called before running the back-end passes on the module. The
/// callback can generate code itself by writing the expected output to OS
/// and returning true to prevent the default pipeline and further plugin
@@ -77,100 +73,81 @@ struct PassPluginLibraryInfo {
/// The callback might be invoked from a worker thread, so exiting inside the
/// callback is unsafe. Failures should be reported through the module's
/// context instead and return false.
- bool (*PreCodeGenCallback)(TargetMachine &TM, Module &M,
- raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS,
- CodeGenFileType CGFT, bool DisableVerify,
- bool DisableSimplifyLibCalls,
- const ModuleSummaryIndex *MSI,
- IntrusiveRefCntPtr<vfs::FileSystem> VFS) = nullptr;
+ virtual bool preCodeGenCallback(TargetMachine &TM, Module &M,
+ raw_pwrite_stream &OS,
+ raw_pwrite_stream *DwoOS,
+ CodeGenFileType CGFT, bool DisableVerify,
+ bool DisableSimplifyLibCalls,
+ const ModuleSummaryIndex *MSI,
+ IntrusiveRefCntPtr<vfs::FileSystem> VFS) {
+ return false;
+ }
/// Callback receiving the arguments given to the plugin, e.g. by
/// -plugin-arg=<PluginName>,<arg>, in order.
- Error (*ParseArguments)(ArrayRef<const char *> Args) = nullptr;
+ virtual Error parseArguments(ArrayRef<const char *> Args) {
+ if (Args.empty())
+ return Error::success();
+ return createStringError("pass plugin '" + Twine(Name) +
+ "' does not accept arguments");
+ }
};
-}
-/// A loaded pass plugin.
-///
-/// An instance of this class wraps a loaded pass plugin and gives access to
-/// its interface defined by the \c PassPluginLibraryInfo it exposes.
-class PassPlugin {
-public:
- /// Attempts to load a pass plugin from a given file.
- ///
- /// \returns Returns an error if either the library cannot be found or loaded,
- /// there is no public entry point, or the plugin implements the wrong API
- /// version.
- LLVM_ABI static Expected<PassPlugin> load(StringRef Filename);
-
- /// Get the filename of the loaded plugin.
- StringRef getFilename() const { return Filename; }
-
- /// Get the plugin name
- StringRef getPluginName() const { return Info.PluginName; }
-
- /// Get the plugin version
- StringRef getPluginVersion() const { return Info.PluginVersion; }
-
- /// Get the plugin API version
- uint32_t getAPIVersion() const { return Info.APIVersion; }
-
- const PassPluginLibraryInfo &getInfo() const { return Info; }
-
- /// Invoke the PassBuilder callback registration
- void registerPassBuilderCallbacks(PassBuilder &PB) const {
- if (Info.RegisterPassBuilderCallbacks)
- Info.RegisterPassBuilderCallbacks(PB);
- }
+/// \macro LLVM_PLUGIN_API_VERSION
+#define LLVM_PLUGIN_API_VERSION (LLVM_VERSION_MAJOR * 100 + LLVM_VERSION_MINOR)
- /// Invoke the pre-codegen callback. Keep the signature in sync with
- /// llvm::runCodeGenPipeline().
- LLVM_ABI bool
- invokePreCodeGenCallback(TargetMachine &TM, Module &M, raw_pwrite_stream &OS,
- raw_pwrite_stream *DwoOS, CodeGenFileType CGFT,
- bool DisableVerify, bool DisableSimplifyLibCalls,
- const ModuleSummaryIndex *MSI,
- IntrusiveRefCntPtr<vfs::FileSystem> VFS) const;
-
-private:
- PassPlugin(const std::string &Filename, const sys::DynamicLibrary &Library)
- : Filename(Filename), Library(Library), Info() {}
-
- std::string Filename;
- sys::DynamicLibrary Library;
- PassPluginLibraryInfo Info;
+extern "C" {
+/// Information about the plugin required to load its passes
+struct PassPluginLibraryInfo {
+ /// The LLVM API version this plugin is compiled aggainst, should be \c
+ /// LLVM_PLUGIN_API_VERSION. As plugins use the C++ API, they must be compiled
+ /// against the same version of LLVM. This field provides some guard rails
+ /// against accidentally loading incompatible plugins, which can lead to
+ /// crashes/misbehavior that could otherwise be hard to identify.
+ uint32_t APIVersion;
+ /// Callback to create a new instance of the PassPlugin subclass.
+ std::unique_ptr<PassPlugin> (*Instantiate)();
};
+}
+
+/// Convenience function to create a PassPluginLibraryInfo for a PassPlugin
+/// subclass. Intended to be returned from \c llvmGetPassPluginInfo.
+template <typename T> static PassPluginLibraryInfo getPassPluginLibraryInfo() {
+ return PassPluginLibraryInfo{LLVM_PLUGIN_API_VERSION,
+ []() -> std::unique_ptr<PassPlugin> {
+ return std::unique_ptr<PassPlugin>(new T());
+ }};
+}
/// Passes each "<PluginName>,<arg>" in \p Args to the \c ParseArguments
/// callback of the extension in \p Infos with that name. Two extensions with
/// the same name are an error.
-LLVM_ABI Error passPluginArguments(ArrayRef<PassPluginLibraryInfo> Infos,
+LLVM_ABI Error passPluginArguments(ArrayRef<PassPlugin *> Plugins,
ArrayRef<std::string> Args);
+// Convenience function for unique pointer arrays.
+LLVM_ABI Error passPluginArguments(
+ ArrayRef<std::unique_ptr<PassPlugin>> Plugins, ArrayRef<std::string> Args);
} // namespace llvm
-// The function returns a struct with default initializers.
-#ifdef __clang__
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
-#endif
/// The public entry point for a pass plugin.
///
/// When a plugin is loaded by the driver, it will call this entry point to
/// obtain information about this plugin and about how to register its passes.
-/// This function needs to be implemented by the plugin, see the example below:
+/// This function needs to be implemented by the plugin and should return the
+/// result of \c getPassPluginLibraryInfo. Example:
///
/// ```
+/// class MyPassPlugin : public PassPlugin {
+/// public:
+/// MyPassPlugin() : PassPlugin("MyPass") {}
+/// void registerPassBuilderCallbacks(PassBuilder &PB) override { /* ... */ }
+/// };
/// extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK
/// llvmGetPassPluginInfo() {
-/// return {
-/// LLVM_PLUGIN_API_VERSION, "MyPlugin", "v0.1", [](PassBuilder &PB) { ... }
-/// };
+/// return getPassPluginLibraryInfo<MyPassPlugin>();
/// }
/// ```
extern "C" LLVM_ABI_EXPORT ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK
llvmGetPassPluginInfo();
-#ifdef __clang__
-#pragma clang diagnostic pop
-#endif
#endif /* LLVM_PLUGINS_PASSPLUGIN_H */
diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index b865810eed82b6..0be6202cf64f24 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -1324,12 +1324,16 @@ Error LTO::setupPassPlugins() {
// Load plugins from file. Failures leave them all unregistered.
SmallVector<std::unique_ptr<PassPlugin>, 0> Loaded;
for (const std::string &PluginFN : Conf.PassPluginFilenames) {
- Expected<PassPlugin> Plugin = PassPlugin::load(PluginFN);
+ Expected<std::unique_ptr<PassPlugin>> Plugin = PassPlugin::load(PluginFN);
if (!Plugin)
return Plugin.takeError();
- Loaded.push_back(std::make_unique<PassPlugin>(std::move(*Plugin)));
+ Loaded.push_back(std::move(Plugin.get()));
}
+#define HANDLE_EXTENSION(Ext) \
+ Loaded.push_back(get##Ext##PluginInfo().Instantiate());
+#include "llvm/Support/Extension.def"
+
// Register them ahead of the client loaded ones.
SmallVector<PassPlugin *> FromFiles;
for (std::unique_ptr<PassPlugin> &Plugin : Loaded) {
@@ -1343,12 +1347,7 @@ Error LTO::setupPassPlugins() {
if (Conf.PassPluginArgs.empty())
return Error::success();
- SmallVector<PassPluginLibraryInfo, 0> Infos;
- for (const PassPlugin *Plugin : Conf.LoadedPassPlugins)
- Infos.push_back(Plugin->getInfo());
-#define HANDLE_EXTENSION(Ext) Infos.push_back(get##Ext##PluginInfo());
-#include "llvm/Support/Extension.def"
- return llvm::passPluginArguments(Infos, Conf.PassPluginArgs);
+ return llvm::passPluginArguments(Conf.LoadedPassPlugins, Conf.PassPluginArgs);
}
Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index 52eae632c0b7d6..9d4b66fb740920 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -194,11 +194,6 @@ Error Config::addSaveTemps(std::string OutputFileName, bool UseInputModulePath,
return Error::success();
}
-#define HANDLE_EXTENSION(Ext) \
- llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
-#include "llvm/Support/Extension.def"
-#undef HANDLE_EXTENSION
-
static ArrayRef<PassPlugin *> getPassPlugins(const Config &Conf) {
// lto::LTO::run() loaded plugins requested by file. Direct callers must pass
// them pre-loaded.
@@ -209,14 +204,7 @@ static ArrayRef<PassPlugin *> getPassPlugins(const Config &Conf) {
// Call pass builder registration callbacks for all pass-plugins
static void RegisterPassPlugins(const Config &Conf, PassBuilder &PB) {
- // Static built-in plugins
-#define HANDLE_EXTENSION(Ext) \
- get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
-#include "llvm/Support/Extension.def"
-#undef HANDLE_EXTENSION
-
- // Dynamic plugins
- for (const PassPlugin *Plugin : getPassPlugins(Conf))
+ for (PassPlugin *Plugin : getPassPlugins(Conf))
Plugin->registerPassBuilderCallbacks(PB);
}
@@ -486,8 +474,8 @@ static void codegen(const Config &Conf, TargetMachine *TM,
!isEmptyModule(Mod) ? &CombinedIndex : nullptr;
// Allow plugins to handle or even take over code generation entirely.
- for (const PassPlugin *Plugin : getPassPlugins(Conf)) {
- if (Plugin->invokePreCodeGenCallback(
+ for (PassPlugin *Plugin : getPassPlugins(Conf)) {
+ if (Plugin->preCodeGenCallback(
*TM, Mod, *Stream->OS, DwoOut ? &DwoOut->os() : nullptr,
Conf.CGFileType, /*DisableVerify=*/true,
/*DisableSimplifyLibCalls=*/false, MSI, vfs::getRealFileSystem())) {
diff --git a/llvm/lib/Plugins/PassPlugin.cpp b/llvm/lib/Plugins/PassPlugin.cpp
index 5b164c6957978e..0968b6e6ad39bd 100644
--- a/llvm/lib/Plugins/PassPlugin.cpp
+++ b/llvm/lib/Plugins/PassPlugin.cpp
@@ -9,6 +9,7 @@
#include "llvm/Plugins/PassPlugin.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVectorExtras.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
@@ -16,7 +17,9 @@
using namespace llvm;
-Expected<PassPlugin> PassPlugin::load(StringRef Filename) {
+PassPlugin::~PassPlugin() = default;
+
+Expected<std::unique_ptr<PassPlugin>> PassPlugin::load(StringRef Filename) {
std::string Error;
auto Library =
sys::DynamicLibrary::getPermanentLibrary(Filename.str().c_str(), &Error);
@@ -25,8 +28,6 @@ Expected<PassPlugin> PassPlugin::load(StringRef Filename) {
Filename + "': " + Error,
inconvertibleErrorCode());
- PassPlugin P{Filename.str(), Library};
-
// llvmGetPassPluginInfo should be resolved to the definition from the plugin
// we are currently loading.
intptr_t getDetailsFn =
@@ -39,40 +40,29 @@ Expected<PassPlugin> PassPlugin::load(StringRef Filename) {
Filename + "'. Is this a legacy plugin?",
inconvertibleErrorCode());
- P.Info = reinterpret_cast<decltype(llvmGetPassPluginInfo) *>(getDetailsFn)();
+ PassPluginLibraryInfo Info =
+ reinterpret_cast<decltype(llvmGetPassPluginInfo) *>(getDetailsFn)();
- if (P.Info.APIVersion != LLVM_PLUGIN_API_VERSION)
+ if (Info.APIVersion != LLVM_PLUGIN_API_VERSION || !Info.Instantiate)
return make_error<StringError>(
Twine("Wrong API version on plugin '") + Filename + "'. Got version " +
- Twine(P.Info.APIVersion) + ", supported version is " +
+ Twine(Info.APIVersion) + ", supported version is " +
Twine(LLVM_PLUGIN_API_VERSION) + ".",
inconvertibleErrorCode());
- return P;
-}
-
-bool PassPlugin::invokePreCodeGenCallback(
- TargetMachine &TM, Module &M, raw_pwrite_stream &OS,
- raw_pwrite_stream *DwoOS, CodeGenFileType CGFT, bool DisableVerify,
- bool DisableSimplifyLibCalls, const ModuleSummaryIndex *MSI,
- IntrusiveRefCntPtr<vfs::FileSystem> VFS) const {
- if (Info.PreCodeGenCallback)
- return Info.PreCodeGenCallback(TM, M, OS, DwoOS, CGFT, DisableVerify,
- DisableSimplifyLibCalls, MSI,
- std::move(VFS));
- return false;
+ return Info.Instantiate();
}
-Error llvm::passPluginArguments(ArrayRef<PassPluginLibraryInfo> Infos,
+Error llvm::passPluginArguments(ArrayRef<PassPlugin *> Plugins,
ArrayRef<std::string> Args) {
DenseMap<StringRef, unsigned> Index;
- for (auto [I, Info] : enumerate(Infos))
- if (!Index.try_emplace(Info.PluginName, I).second)
+ for (auto [I, Plugin] : enumerate(Plugins))
+ if (!Index.try_emplace(Plugin->getName(), I).second)
return createStringError("multiple pass plugins are named '" +
- Twine(Info.PluginName) + "'");
+ Twine(Plugin->getName()) + "'");
// ParseArguments takes argv-style C strings. The argument is the suffix of
// Arg after the first comma, so it is NUL-terminated and needs no copy.
- SmallVector<SmallVector<const char *, 0>, 0> PluginArgs(Infos.size());
+ SmallVector<SmallVector<const char *, 0>, 0> PluginArgs(Plugins.size());
for (const std::string &Arg : Args) {
auto [Name, Rest] = StringRef(Arg).split(',');
// Rest is null without a comma and empty for an empty argument.
@@ -83,14 +73,17 @@ Error llvm::passPluginArguments(ArrayRef<PassPluginLibraryInfo> Infos,
return createStringError("no pass plugin named '" + Name + "' is loaded");
PluginArgs[It->second].push_back(Rest.data());
}
- for (auto [Info, PArgs] : zip_equal(Infos, PluginArgs)) {
+ for (auto [Plugin, PArgs] : zip_equal(Plugins, PluginArgs)) {
if (PArgs.empty())
continue;
- if (!Info.ParseArguments)
- return createStringError("pass plugin '" + Twine(Info.PluginName) +
- "' does not accept arguments");
- if (Error E = Info.ParseArguments(PArgs))
+ if (Error E = Plugin->parseArguments(PArgs))
return E;
}
return Error::success();
}
+
+Error llvm::passPluginArguments(ArrayRef<std::unique_ptr<PassPlugin>> Plugins,
+ ArrayRef<std::string> Args) {
+ return passPluginArguments(
+ map_to_vector(Plugins, [](const auto &P) { return P.get(); }), Args);
+}
diff --git a/llvm/tools/llc/NewPMDriver.cpp b/llvm/tools/llc/NewPMDriver.cpp
index 76bb405a98859f..c715b4966ceede 100644
--- a/llvm/tools/llc/NewPMDriver.cpp
+++ b/llvm/tools/llc/NewPMDriver.cpp
@@ -90,7 +90,8 @@ int llvm::compileModuleWithNewPM(
std::unique_ptr<TargetMachine> Target, std::unique_ptr<ToolOutputFile> Out,
std::unique_ptr<ToolOutputFile> DwoOut, LLVMContext &Context,
const TargetLibraryInfoImpl &TLII, VerifierKind VK, StringRef PassPipeline,
- ArrayRef<PassPlugin> PassPlugins, CodeGenFileType FileType) {
+ ArrayRef<std::unique_ptr<PassPlugin>> PassPlugins,
+ CodeGenFileType FileType) {
raw_pwrite_stream *OS = &Out->os();
@@ -142,7 +143,7 @@ int llvm::compileModuleWithNewPM(
PassBuilder PB(Context, Target.get(), std::nullopt, std::nullopt, &PIC);
for (auto &PassPlugin : PassPlugins)
- PassPlugin.registerPassBuilderCallbacks(PB);
+ PassPlugin->registerPassBuilderCallbacks(PB);
PB.registerModuleAnalyses(MAM);
PB.registerCGSCCAnalyses(CGAM);
PB.registerFunctionAnalyses(FAM);
diff --git a/llvm/tools/llc/NewPMDriver.h b/llvm/tools/llc/NewPMDriver.h
index e37dd17d5f377c..5433132222cd39 100644
--- a/llvm/tools/llc/NewPMDriver.h
+++ b/llvm/tools/llc/NewPMDriver.h
@@ -44,7 +44,8 @@ int compileModuleWithNewPM(
std::unique_ptr<TargetMachine> Target, std::unique_ptr<ToolOutputFile> Out,
std::unique_ptr<ToolOutputFile> DwoOut, LLVMContext &Context,
const TargetLibraryInfoImpl &TLII, VerifierKind VK, StringRef PassPipeline,
- ArrayRef<PassPlugin> PassPlugins, CodeGenFileType FileType);
+ ArrayRef<std::unique_ptr<PassPlugin>> PassPlugins,
+ CodeGenFileType FileType);
} // namespace llvm
#endif
diff --git a/llvm/tools/llc/llc.cpp b/llvm/tools/llc/llc.cpp
index e3c510dc18c1a0..b1b76bf424106e 100644
--- a/llvm/tools/llc/llc.cpp
+++ b/llvm/tools/llc/llc.cpp
@@ -289,7 +289,7 @@ static void setPGOOptions(TargetMachine &TM) {
TM.setPGOOption(PGOOpt);
}
-static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &,
+static int compileModule(char **argv, ArrayRef<std::unique_ptr<PassPlugin>>,
LLVMContext &Context, std::string &OutputFilename);
[[noreturn]] static void reportError(Twine Msg, StringRef Filename = "") {
@@ -403,17 +403,14 @@ int main(int argc, char **argv) {
codegen::getToolOptions(), ArrayRef(argv, argc),
"llvm system compiler\n");
- SmallVector<PassPlugin, 1> PluginList;
+ SmallVector<std::unique_ptr<PassPlugin>, 1> PluginList;
for (const std::string &Path : PassPlugins) {
auto Plugin = PassPlugin::load(Path);
if (!Plugin)
reportFatalUsageError(Plugin.takeError());
- PluginList.emplace_back(Plugin.get());
+ PluginList.emplace_back(std::move(Plugin.get()));
}
- if (Error E = passPluginArguments(
- map_to_vector(PluginList,
- [](const PassPlugin &P) { return P.getInfo(); }),
- PluginArgs))
+ if (Error E = passPluginArguments(PluginList, PluginArgs))
reportFatalUsageError(std::move(E));
if (!PassPipeline.empty() && !getRunPassNames().empty()) {
@@ -498,7 +495,8 @@ static bool addPass(PassManagerBase &PM, const char *argv0, StringRef PassName,
return false;
}
-static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
+static int compileModule(char **argv,
+ ArrayRef<std::unique_ptr<PassPlugin>> PluginList,
LLVMContext &Context, std::string &OutputFilename) {
// Load the module to be compiled...
SMDiagnostic Err;
@@ -724,10 +722,10 @@ static int compileModule(char **argv, SmallVectorImpl<PassPlugin> &PluginList,
for (auto &Plugin : PluginList) {
CodeGenFileType CGFT = codegen::getFileType(Context.getLibraryOptions());
- if (Plugin.invokePreCodeGenCallback(
- *Target, *M, Out->os(), DwoOut ? &DwoOut->os() : nullptr, CGFT,
- NoVerify, DisableSimplifyLibCalls, /*MSI=*/nullptr,
- vfs::getRealFileSystem())) {
+ if (Plugin->preCodeGenCallback(*Target, *M, Out->os(),
+ DwoOut ? &DwoOut->os() : nullptr, CGFT,
+ NoVerify, DisableSimplifyLibCalls,
+ /*MSI=*/nullptr, vfs::getRealFileSystem())) {
// TODO: Deduplicate code with below and the NewPMDriver.
if (Context.getDiagHandlerPtr()->HasErrors)
exit(1);
diff --git a/llvm/tools/opt/NewPMDriver.cpp b/llvm/tools/opt/NewPMDriver.cpp
index 48a712f1b83be1..7e9973da7bc7db 100644
--- a/llvm/tools/opt/NewPMDriver.cpp
+++ b/llvm/tools/opt/NewPMDriver.cpp
@@ -378,7 +378,7 @@ bool llvm::runPassPipeline(
StringRef Arg0, Module &M, TargetMachine *TM, TargetLibraryInfoImpl *TLII,
ToolOutputFile *Out, ToolOutputFile *ThinLTOLinkOut,
ToolOutputFile *OptRemarkFile, StringRef PassPipeline,
- ArrayRef<PassPluginLibraryInfo> Extensions,
+ ArrayRef<std::unique_ptr<PassPlugin>> PassPlugins,
ArrayRef<std::function<void(PassBuilder &)>> PassBuilderCallbacks,
OutputKind OK, VerifierKind VK, bool ShouldPreserveAssemblyUseListOrder,
bool ShouldPreserveBitcodeUseListOrder, bool EmitSummaryIndex,
@@ -482,9 +482,8 @@ bool llvm::runPassPipeline(
registerEPCallbacks(PB);
// Let plugins and linked extensions register pass builder callbacks.
- for (const PassPluginLibraryInfo &Info : Extensions)
- if (Info.RegisterPassBuilderCallbacks)
- Info.RegisterPassBuilderCallbacks(PB);
+ for (auto &Plugin : PassPlugins)
+ Plugin->registerPassBuilderCallbacks(PB);
// Load any explicitly specified plugins.
for (auto &PassCallback : PassBuilderCallbacks)
diff --git a/llvm/tools/opt/NewPMDriver.h b/llvm/tools/opt/NewPMDriver.h
index 769a31ceab78b9..275684a6d040cc 100644
--- a/llvm/tools/opt/NewPMDriver.h
+++ b/llvm/tools/opt/NewPMDriver.h
@@ -26,7 +26,7 @@ namespace llvm {
class LLVMContext;
class PassBuilder;
class StringRef;
-struct PassPluginLibraryInfo;
+class PassPlugin;
class Module;
class TargetMachine;
class ToolOutputFile;
@@ -70,7 +70,7 @@ bool runPassPipeline(
StringRef Arg0, Module &M, TargetMachine *TM, TargetLibraryInfoImpl *TLII,
ToolOutputFile *Out, ToolOutputFile *ThinLinkOut,
ToolOutputFile *OptRemarkFile, StringRef PassPipeline,
- ArrayRef<PassPluginLibraryInfo> Extensions,
+ ArrayRef<std::unique_ptr<PassPlugin>> PassPlugins,
ArrayRef<std::function<void(PassBuilder &)>> PassBuilderCallbacks,
opt_tool::OutputKind OK, opt_tool::VerifierKind VK,
bool ShouldPreserveAssemblyUseListOrder,
diff --git a/llvm/tools/opt/optdriver.cpp b/llvm/tools/opt/optdriver.cpp
index 7bb9a8a72c150a..0b76e9e325a7ee 100644
--- a/llvm/tools/opt/optdriver.cpp
+++ b/llvm/tools/opt/optdriver.cpp
@@ -477,16 +477,17 @@ optMain(int argc, char **argv,
return 1;
}
- SmallVector<PassPluginLibraryInfo, 0> Extensions;
+ SmallVector<std::unique_ptr<PassPlugin>, 0> Plugins;
for (const std::string &Path : PassPlugins) {
auto Plugin = PassPlugin::load(Path);
if (!Plugin)
reportFatalUsageError(Plugin.takeError());
- Extensions.push_back(Plugin->getInfo());
+ Plugins.push_back(std::move(Plugin.get()));
}
-#define HANDLE_EXTENSION(Ext) Extensions.push_back(get##Ext##PluginInfo());
+#define HANDLE_EXTENSION(Ext) \
+ Plugins.push_back(get##Ext##PluginInfo().Instantiate());
#include "llvm/Support/Extension.def"
- if (Error E = passPluginArguments(Extensions, PluginArgs))
+ if (Error E = passPluginArguments(Plugins, PluginArgs))
reportFatalUsageError(std::move(E));
const bool UseNPM = PassList.empty() || PassPipeline.getNumOccurrences() > 0;
@@ -828,8 +829,8 @@ optMain(int argc, char **argv,
// layer.
if (!runPassPipeline(
argv[0], *M, TM.get(), &TLII, Out.get(), ThinLinkOut.get(),
- RemarksFile.get(), Pipeline, Extensions, PassBuilderCallbacks, OK,
- VK, /* ShouldPreserveAssemblyUseListOrder */ false,
+ RemarksFile.get(), Pipeline, Plugins, PassBuilderCallbacks, OK, VK,
+ /* ShouldPreserveAssemblyUseListOrder */ false,
/* ShouldPreserveBitcodeUseListOrder */ true, EmitSummaryIndex,
EmitModuleHash, EnableDebugify, VerifyDebugInfoPreserve,
EnableProfileVerification, UnifiedLTO))
diff --git a/llvm/unittests/Analysis/InlineAdvisorPlugin/InlineAdvisorPlugin.cpp b/llvm/unittests/Analysis/InlineAdvisorPlugin/InlineAdvisorPlugin.cpp
index 498a77271b2570..e38318902db501 100644
--- a/llvm/unittests/Analysis/InlineAdvisorPlugin/InlineAdvisorPlugin.cpp
+++ b/llvm/unittests/Analysis/InlineAdvisorPlugin/InlineAdvisorPlugin.cpp
@@ -17,18 +17,22 @@ InlineAdvisor *DefaultAdvisorFactory(Module &M, FunctionAnalysisManager &FAM,
return new DefaultInlineAdvisor(M, FAM, Params, IC);
}
+class DynamicAdvisorPlugin : public PassPlugin {
+public:
+ DynamicAdvisorPlugin() : PassPlugin("DynamicDefaultAdvisor") {}
+
+ void registerPassBuilderCallbacks(PassBuilder &PB) override {
+ PB.registerAnalysisRegistrationCallback([](ModuleAnalysisManager &MAM) {
+ PluginInlineAdvisorAnalysis PA(DefaultAdvisorFactory);
+ MAM.registerPass([&] { return PA; });
+ });
+ }
+};
+
} // namespace
-/* New PM Registration */
llvm::PassPluginLibraryInfo getDefaultDynamicAdvisorPluginInfo() {
- return {LLVM_PLUGIN_API_VERSION, "DynamicDefaultAdvisor", LLVM_VERSION_STRING,
- [](PassBuilder &PB) {
- PB.registerAnalysisRegistrationCallback(
- [](ModuleAnalysisManager &MAM) {
- PluginInlineAdvisorAnalysis PA(DefaultAdvisorFactory);
- MAM.registerPass([&] { return PA; });
- });
- }};
+ return getPassPluginLibraryInfo<DynamicAdvisorPlugin>();
}
extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
diff --git a/llvm/unittests/Analysis/InlineOrderPlugin/InlineOrderPlugin.cpp b/llvm/unittests/Analysis/InlineOrderPlugin/InlineOrderPlugin.cpp
index a263edc3f6f410..55b0f55b3077fc 100644
--- a/llvm/unittests/Analysis/InlineOrderPlugin/InlineOrderPlugin.cpp
+++ b/llvm/unittests/Analysis/InlineOrderPlugin/InlineOrderPlugin.cpp
@@ -41,25 +41,28 @@ NoFooInlineOrderFactory(FunctionAnalysisManager &FAM,
return std::make_unique<NoFooInlineOrder>(FAM, Params, MAM, M);
}
+class DynamicDefaultInlineOrderPlugin : public PassPlugin {
+public:
+ DynamicDefaultInlineOrderPlugin() : PassPlugin("DynamicDefaultInlineOrder") {}
+
+ void registerPassBuilderCallbacks(PassBuilder &PB) override {
+ // We use the PassBuilder's callback mechanism to register our Analysis:
+ // this will register our PluginInlineOrderAnalysis instance with the
+ // ModuleAnalysisManager
+ PB.registerAnalysisRegistrationCallback([](ModuleAnalysisManager &MAM) {
+ MAM.registerPass([] {
+ // defaultInlineOrderFactory will be used to create an InlineOrder
+ return PluginInlineOrderAnalysis(NoFooInlineOrderFactory);
+ });
+ });
+ }
+};
+
} // namespace
-/* New PM Registration */
+// /* New PM Registration */
llvm::PassPluginLibraryInfo getDefaultDynamicInlineOrderPluginInfo() {
- return {LLVM_PLUGIN_API_VERSION, "DynamicDefaultInlineOrder",
- LLVM_VERSION_STRING, [](PassBuilder &PB) {
- // We use the PassBuilder's callback mechanism
- // to register our Analysis: this will register
- // our PluginInlineOrderAnalysis instance with
- // the ModuleAnalysisManager
- PB.registerAnalysisRegistrationCallback(
- [](ModuleAnalysisManager &MAM) {
- MAM.registerPass([] {
- // defaultInlineOrderFactory will be
- // used to create an InlineOrder
- return PluginInlineOrderAnalysis(NoFooInlineOrderFactory);
- });
- });
- }};
+ return getPassPluginLibraryInfo<DynamicDefaultInlineOrderPlugin>();
}
extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
diff --git a/llvm/unittests/Analysis/PluginInlineAdvisorAnalysisTest.cpp b/llvm/unittests/Analysis/PluginInlineAdvisorAnalysisTest.cpp
index c9a1bd887d4807..db0c2567b5e434 100644
--- a/llvm/unittests/Analysis/PluginInlineAdvisorAnalysisTest.cpp
+++ b/llvm/unittests/Analysis/PluginInlineAdvisorAnalysisTest.cpp
@@ -63,10 +63,10 @@ struct CompilerInstance {
void setupPlugin() {
auto PluginPath = libPath();
ASSERT_NE("", PluginPath);
- Expected<PassPlugin> Plugin = PassPlugin::load(PluginPath);
+ Expected<std::unique_ptr<PassPlugin>> Plugin = PassPlugin::load(PluginPath);
ASSERT_TRUE(!!Plugin) << "Plugin path: " << PluginPath
<< " Error: " << Plugin.takeError();
- Plugin->registerPassBuilderCallbacks(PB);
+ (*Plugin)->registerPassBuilderCallbacks(PB);
}
// connect the FooOnlyInlineAdvisor to our compiler instance
diff --git a/llvm/unittests/Analysis/PluginInlineOrderAnalysisTest.cpp b/llvm/unittests/Analysis/PluginInlineOrderAnalysisTest.cpp
index 1b74ead2315aa6..b6a45ccacda999 100644
--- a/llvm/unittests/Analysis/PluginInlineOrderAnalysisTest.cpp
+++ b/llvm/unittests/Analysis/PluginInlineOrderAnalysisTest.cpp
@@ -45,9 +45,9 @@ struct CompilerInstance {
void setupPlugin() {
auto PluginPath = libPath();
ASSERT_NE("", PluginPath);
- Expected<PassPlugin> Plugin = PassPlugin::load(PluginPath);
+ Expected<std::unique_ptr<PassPlugin>> Plugin = PassPlugin::load(PluginPath);
ASSERT_TRUE(!!Plugin) << "Plugin path: " << PluginPath;
- Plugin->registerPassBuilderCallbacks(PB);
+ (*Plugin)->registerPassBuilderCallbacks(PB);
}
CompilerInstance() : PB(Ctx) {
diff --git a/llvm/unittests/Passes/Plugins/DoublerPlugin/DoublerPlugin.cpp b/llvm/unittests/Passes/Plugins/DoublerPlugin/DoublerPlugin.cpp
index 4b53f9d1e14939..b905feb67df0fb 100644
--- a/llvm/unittests/Passes/Plugins/DoublerPlugin/DoublerPlugin.cpp
+++ b/llvm/unittests/Passes/Plugins/DoublerPlugin/DoublerPlugin.cpp
@@ -24,8 +24,13 @@ struct DoublerModulePass : public OptionalPassInfoMixin<DoublerModulePass> {
return PreservedAnalyses::none();
}
+};
+
+class DoublerPassPlugin : public PassPlugin {
+public:
+ DoublerPassPlugin() : PassPlugin("DoublerPlugin") {}
- static void registerCallbacks(PassBuilder &PB) {
+ void registerPassBuilderCallbacks(PassBuilder &PB) override {
PB.registerPipelineParsingCallback(
[](StringRef Name, ModulePassManager &PM,
ArrayRef<PassBuilder::PipelineElement> InnerPipeline) {
@@ -40,6 +45,5 @@ struct DoublerModulePass : public OptionalPassInfoMixin<DoublerModulePass> {
extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK
llvmGetPassPluginInfo() {
- return {LLVM_PLUGIN_API_VERSION, "DoublerPlugin", "2.2-unit",
- DoublerModulePass::registerCallbacks};
+ return getPassPluginLibraryInfo<DoublerPassPlugin>();
}
diff --git a/llvm/unittests/Passes/Plugins/PluginsTest.cpp b/llvm/unittests/Passes/Plugins/PluginsTest.cpp
index 668cf2367ebf9d..02c98dd24c4bcf 100644
--- a/llvm/unittests/Passes/Plugins/PluginsTest.cpp
+++ b/llvm/unittests/Passes/Plugins/PluginsTest.cpp
@@ -48,18 +48,17 @@ TEST(PluginsTests, LoadPlugin) {
auto PluginPath = LibPath();
ASSERT_NE("", PluginPath);
- Expected<PassPlugin> Plugin = PassPlugin::load(PluginPath);
+ Expected<std::unique_ptr<PassPlugin>> Plugin = PassPlugin::load(PluginPath);
ASSERT_TRUE(!!Plugin) << "Plugin path: " << PluginPath;
- ASSERT_EQ(TEST_PLUGIN_NAME, Plugin->getPluginName());
- ASSERT_EQ(TEST_PLUGIN_VERSION, Plugin->getPluginVersion());
+ ASSERT_EQ(TEST_PLUGIN_NAME, (*Plugin)->getName());
LLVMContext C;
PassBuilder PB(C);
ModulePassManager PM;
ASSERT_THAT_ERROR(PB.parsePassPipeline(PM, "plugin-pass"), Failed());
- Plugin->registerPassBuilderCallbacks(PB);
+ (*Plugin)->registerPassBuilderCallbacks(PB);
ASSERT_THAT_ERROR(PB.parsePassPipeline(PM, "plugin-pass"), Succeeded());
}
@@ -77,38 +76,36 @@ TEST(PluginsTests, LoadMultiplePlugins) {
ASSERT_NE("", DoublerPluginPath);
ASSERT_NE("", TestPluginPath);
- Expected<PassPlugin> DoublerPlugin1 = PassPlugin::load(DoublerPluginPath);
- ASSERT_TRUE(!!DoublerPlugin1)
- << "Plugin path: " << DoublerPlugin1->getFilename();
+ Expected<std::unique_ptr<PassPlugin>> DoublerPlugin1 =
+ PassPlugin::load(DoublerPluginPath);
+ ASSERT_TRUE(!!DoublerPlugin1) << "Plugin path: " << DoublerPluginPath;
- Expected<PassPlugin> TestPlugin = PassPlugin::load(TestPluginPath);
- ASSERT_TRUE(!!TestPlugin) << "Plugin path: " << TestPlugin->getFilename();
+ Expected<std::unique_ptr<PassPlugin>> TestPlugin =
+ PassPlugin::load(TestPluginPath);
+ ASSERT_TRUE(!!TestPlugin) << "Plugin path: " << TestPluginPath;
// If llvmGetPassPluginInfo is resolved as a weak symbol taking into account
// all loaded symbols, the second call to PassPlugin::load will actually
// return the llvmGetPassPluginInfo from the most recently loaded plugin, in
// this case TestPlugin.
- Expected<PassPlugin> DoublerPlugin2 = PassPlugin::load(DoublerPluginPath);
- ASSERT_TRUE(!!DoublerPlugin2)
- << "Plugin path: " << DoublerPlugin2->getFilename();
-
- ASSERT_EQ("DoublerPlugin", DoublerPlugin1->getPluginName());
- ASSERT_EQ("2.2-unit", DoublerPlugin1->getPluginVersion());
- ASSERT_EQ(TEST_PLUGIN_NAME, TestPlugin->getPluginName());
- ASSERT_EQ(TEST_PLUGIN_VERSION, TestPlugin->getPluginVersion());
+ Expected<std::unique_ptr<PassPlugin>> DoublerPlugin2 =
+ PassPlugin::load(DoublerPluginPath);
+ ASSERT_TRUE(!!DoublerPlugin2) << "Plugin path: " << DoublerPluginPath;
+
+ ASSERT_EQ("DoublerPlugin", (*DoublerPlugin1)->getName());
+ ASSERT_EQ(TEST_PLUGIN_NAME, (*TestPlugin)->getName());
// Check that the plugin name/version is set correctly when loaded a second
// time
- ASSERT_EQ("DoublerPlugin", DoublerPlugin2->getPluginName());
- ASSERT_EQ("2.2-unit", DoublerPlugin2->getPluginVersion());
+ ASSERT_EQ("DoublerPlugin", (*DoublerPlugin2)->getName());
LLVMContext C;
PassBuilder PB(C);
ModulePassManager PM;
const char *PipelineText = "module(doubler-pass,plugin-pass,doubler-pass)";
ASSERT_THAT_ERROR(PB.parsePassPipeline(PM, PipelineText), Failed());
- TestPlugin->registerPassBuilderCallbacks(PB);
- DoublerPlugin1->registerPassBuilderCallbacks(PB);
- DoublerPlugin2->registerPassBuilderCallbacks(PB);
+ (*TestPlugin)->registerPassBuilderCallbacks(PB);
+ (*DoublerPlugin1)->registerPassBuilderCallbacks(PB);
+ (*DoublerPlugin2)->registerPassBuilderCallbacks(PB);
ASSERT_THAT_ERROR(PB.parsePassPipeline(PM, PipelineText), Succeeded());
SMDiagnostic Err;
diff --git a/llvm/unittests/Passes/Plugins/TestPlugin.h b/llvm/unittests/Passes/Plugins/TestPlugin.h
index 801a89065cda55..ea54e878550ffd 100644
--- a/llvm/unittests/Passes/Plugins/TestPlugin.h
+++ b/llvm/unittests/Passes/Plugins/TestPlugin.h
@@ -1,2 +1 @@
#define TEST_PLUGIN_NAME "TestPlugin"
-#define TEST_PLUGIN_VERSION "0.1-unit"
diff --git a/llvm/unittests/Passes/Plugins/TestPlugin/TestPlugin.cpp b/llvm/unittests/Passes/Plugins/TestPlugin/TestPlugin.cpp
index 1fc237cedae66f..7b06527837f8c1 100644
--- a/llvm/unittests/Passes/Plugins/TestPlugin/TestPlugin.cpp
+++ b/llvm/unittests/Passes/Plugins/TestPlugin/TestPlugin.cpp
@@ -17,8 +17,13 @@ struct TestModulePass : public OptionalPassInfoMixin<TestModulePass> {
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM) {
return PreservedAnalyses::all();
}
+};
+
+class TestPlugin : public PassPlugin {
+public:
+ TestPlugin() : PassPlugin(TEST_PLUGIN_NAME) {}
- static void registerCallbacks(PassBuilder &PB) {
+ void registerPassBuilderCallbacks(PassBuilder &PB) override {
PB.registerPipelineParsingCallback(
[](StringRef Name, ModulePassManager &PM,
ArrayRef<PassBuilder::PipelineElement> InnerPipeline) {
@@ -33,6 +38,5 @@ struct TestModulePass : public OptionalPassInfoMixin<TestModulePass> {
extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK
llvmGetPassPluginInfo() {
- return {LLVM_PLUGIN_API_VERSION, TEST_PLUGIN_NAME, TEST_PLUGIN_VERSION,
- TestModulePass::registerCallbacks};
+ return getPassPluginLibraryInfo<TestPlugin>();
}
diff --git a/polly/lib/Support/RegisterPasses.cpp b/polly/lib/Support/RegisterPasses.cpp
index 0a9664feadaf7a..a08a7a011eb242 100644
--- a/polly/lib/Support/RegisterPasses.cpp
+++ b/polly/lib/Support/RegisterPasses.cpp
@@ -607,6 +607,14 @@ parseModulePipeline(StringRef Name, llvm::ModulePassManager &MPM,
return false;
}
+class PollyPassPlugin : public PassPlugin {
+public:
+ PollyPassPlugin() : PassPlugin("Polly") {}
+
+ void registerPassBuilderCallbacks(PassBuilder &PB) override;
+ Error parseArguments(ArrayRef<const char *> Args) override;
+};
+
/// Register Polly to be available as an optimizer
///
///
@@ -633,7 +641,7 @@ parseModulePipeline(StringRef Name, llvm::ModulePassManager &MPM,
/// We are currently evaluating the benefit or running Polly at b). b) is nice
/// as everything is fully inlined and canonicalized, but we need to be able to
/// handle LICMed code to make it useful.
-void registerPollyPasses(PassBuilder &PB) {
+void PollyPassPlugin::registerPassBuilderCallbacks(PassBuilder &PB) {
PassInstrumentationCallbacks *PIC = PB.getPassInstrumentationCallbacks();
IntrusiveRefCntPtr<vfs::FileSystem> FS = PB.getVirtualFileSystemPtr();
LLVMContext &Context = PB.getContext();
@@ -692,9 +700,8 @@ void registerPollyPasses(PassBuilder &PB) {
break;
}
}
-} // namespace polly
-static Error parseArguments(ArrayRef<const char *> Args) {
+Error PollyPassPlugin::parseArguments(ArrayRef<const char *> Args) {
SmallVector<const char *> Argv = {"Polly"};
append_range(Argv, Args);
std::string Msg;
@@ -703,11 +710,8 @@ static Error parseArguments(ArrayRef<const char *> Args) {
return createStringError(StringRef(Msg).trim());
return Error::success();
}
+} // namespace polly
llvm::PassPluginLibraryInfo getPollyPluginInfo() {
- llvm::PassPluginLibraryInfo Info = {LLVM_PLUGIN_API_VERSION, "Polly",
- LLVM_VERSION_STRING,
- polly::registerPollyPasses};
- Info.ParseArguments = parseArguments;
- return Info;
+ return getPassPluginLibraryInfo<PollyPassPlugin>();
}
>From 4ab84ca73759260207dacaaccaa6d2cde9b734f8 Mon Sep 17 00:00:00 2001
From: Alexis Engelke <engelke at in.tum.de>
Date: Wed, 2 Dec 2026 09:23:02 +0000
Subject: [PATCH 2/2] port SimplifyCFG+Ciao plugins to avoid global state
---
llvm/examples/Ciao/Ciao.cpp | 3 ++-
llvm/examples/IRTransforms/SimplifyCFG.cpp | 12 ++++++++----
2 files changed, 10 insertions(+), 5 deletions(-)
diff --git a/llvm/examples/Ciao/Ciao.cpp b/llvm/examples/Ciao/Ciao.cpp
index 1762539299db95..520c0e94acb04f 100644
--- a/llvm/examples/Ciao/Ciao.cpp
+++ b/llvm/examples/Ciao/Ciao.cpp
@@ -45,9 +45,10 @@ static RegisterTargetPassConfigCallback RegisterLegacyCiao{
}};
namespace {
-bool ForwardCodeGen = false;
class CiaoPlugin : public PassPlugin {
+ bool ForwardCodeGen = false;
+
public:
CiaoPlugin() : PassPlugin("Ciao") {}
diff --git a/llvm/examples/IRTransforms/SimplifyCFG.cpp b/llvm/examples/IRTransforms/SimplifyCFG.cpp
index 56778d6d97c447..46a265d731990d 100644
--- a/llvm/examples/IRTransforms/SimplifyCFG.cpp
+++ b/llvm/examples/IRTransforms/SimplifyCFG.cpp
@@ -46,7 +46,6 @@ using namespace llvm;
using namespace PatternMatch;
enum TutorialVersion { V1, V2, V3 };
-static TutorialVersion Version = V1;
#define DEBUG_TYPE "tut-simplifycfg"
@@ -363,6 +362,9 @@ static bool doSimplify_v3(Function &F, DominatorTree &DT) {
namespace {
struct SimplifyCFGPass : public OptionalPassInfoMixin<SimplifyCFGPass> {
+ TutorialVersion Version;
+ SimplifyCFGPass(TutorialVersion Version) : Version(Version) {}
+
PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM) {
switch (Version) {
case V1:
@@ -385,15 +387,17 @@ struct SimplifyCFGPass : public OptionalPassInfoMixin<SimplifyCFGPass> {
};
class ExampleIRTransformsPlugin : public PassPlugin {
+ TutorialVersion Version = V1;
+
public:
ExampleIRTransformsPlugin() : PassPlugin("SimplifyCFG") {}
void registerPassBuilderCallbacks(PassBuilder &PB) override {
PB.registerPipelineParsingCallback(
- [](StringRef Name, llvm::FunctionPassManager &PM,
- ArrayRef<llvm::PassBuilder::PipelineElement>) {
+ [this](StringRef Name, llvm::FunctionPassManager &PM,
+ ArrayRef<llvm::PassBuilder::PipelineElement>) {
if (Name == "tut-simplifycfg") {
- PM.addPass(SimplifyCFGPass());
+ PM.addPass(SimplifyCFGPass(Version));
return true;
}
return false;
More information about the cfe-commits
mailing list