Skip to content

Commit 7055ddf

Browse files
[Driver][Frontend] Introduce load-pass-plugin option
Allow dynamic loading of LLVM passes via `load-pass-plugin` option passed to the Swift compiler driver.
1 parent 3a511e0 commit 7055ddf

File tree

10 files changed

+120
-18
lines changed

10 files changed

+120
-18
lines changed

include/swift/AST/DiagnosticsIRGen.def

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,5 +65,8 @@ ERROR(temporary_allocation_alignment_not_power_of_2,none,
6565
ERROR(explosion_size_oveflow,none,
6666
"explosion size too large", ())
6767

68+
ERROR(unable_to_load_pass_plugin,none,
69+
"unable to load plugin '%0': '%1'", (StringRef, StringRef))
70+
6871
#define UNDEFINE_DIAGNOSTIC_MACROS
6972
#include "DefineDiagnosticMacros.h"

include/swift/AST/IRGenOptions.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,9 @@ class IRGenOptions {
513513
/// Emit a .casid file next to the object file if CAS Backend is used.
514514
bool EmitCASIDFile;
515515

516+
/// Paths to the pass plugins registered via -load-pass-plugin.
517+
std::vector<std::string> LLVMPassPlugins;
518+
516519
IRGenOptions()
517520
: OutputKind(IRGenOutputKind::LLVMAssemblyAfterOptimization),
518521
Verify(true), OptMode(OptimizationMode::NotSet),

include/swift/Option/Options.td

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1735,6 +1735,11 @@ def use_interface_for_module: Separate<["-", "--"], "use-interface-for-module">,
17351735
HelpText<"Prefer loading these modules via interface">,
17361736
MetaVarName<"<name>">;
17371737

1738+
def load_pass_plugin_EQ : Joined<["-"], "load-pass-plugin=">,
1739+
Flags<[FrontendOption, ArgumentIsPath]>,
1740+
HelpText<"Load LLVM pass plugin from a dynamic shared object file.">,
1741+
MetaVarName<"<path>">;
1742+
17381743
// ONLY SUPPORTED IN NEW DRIVER
17391744

17401745
// These flags only exist here so that the old driver doesn't fail with unknown

include/swift/Subsystems.h

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,10 @@ namespace swift {
265265
/// Given an already created LLVM module, construct a pass pipeline and run
266266
/// the Swift LLVM Pipeline upon it. This will include the emission of LLVM IR
267267
/// if requested (\out is not null).
268-
void performLLVMOptimizations(const IRGenOptions &Opts, llvm::Module *Module,
268+
void performLLVMOptimizations(const IRGenOptions &Opts,
269+
DiagnosticEngine &Diags,
270+
llvm::sys::Mutex *DiagMutex,
271+
llvm::Module *Module,
269272
llvm::TargetMachine *TargetMachine,
270273
llvm::raw_pwrite_stream *out);
271274

lib/Driver/ToolChains.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ void ToolChain::addCommonFrontendArgs(const OutputInfo &OI,
340340
inputArgs.AddLastArg(arguments, options::OPT_enable_experimental_cxx_interop);
341341
inputArgs.AddLastArg(arguments, options::OPT_cxx_interoperability_mode);
342342
inputArgs.AddLastArg(arguments, options::OPT_enable_builtin_module);
343+
inputArgs.AddLastArg(arguments, options::OPT_load_pass_plugin_EQ);
343344

344345
// Pass on any build config options
345346
inputArgs.AddAllArgs(arguments, options::OPT_D);

lib/DriverTool/swift_llvm_opt_main.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,10 @@ int swift_llvm_opt_main(ArrayRef<const char *> argv, void *MainAddr) {
215215
Opts.OutputKind = IRGenOutputKind::LLVMAssemblyAfterOptimization;
216216

217217
// Then perform the optimizations.
218-
performLLVMOptimizations(Opts, M.get(), TM.get(), &Out->os());
218+
SourceManager SM;
219+
DiagnosticEngine Diags(SM);
220+
performLLVMOptimizations(Opts, Diags, nullptr, M.get(), TM.get(),
221+
&Out->os());
219222
} else {
220223
std::string Pipeline = PassPipeline;
221224
llvm::TargetLibraryInfoImpl TLII(ModuleTriple);

lib/Frontend/CompilerInvocation.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2682,6 +2682,10 @@ static bool ParseIRGenArgs(IRGenOptions &Opts, ArgList &Args,
26822682
}
26832683
}
26842684

2685+
for (const Arg *A : Args.filtered(OPT_load_pass_plugin_EQ)) {
2686+
Opts.LLVMPassPlugins.push_back(A->getValue());
2687+
}
2688+
26852689
for (const Arg *A : Args.filtered(OPT_verify_type_layout)) {
26862690
Opts.VerifyTypeLayoutNames.push_back(A->getValue());
26872691
}

lib/IRGen/IRGen.cpp

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
#include "llvm/MC/TargetRegistry.h"
6969
#include "llvm/Object/ObjectFile.h"
7070
#include "llvm/Passes/PassBuilder.h"
71+
#include "llvm/Passes/PassPlugin.h"
7172
#include "llvm/Passes/StandardInstrumentations.h"
7273
#include "llvm/Support/CommandLine.h"
7374
#include "llvm/Support/Debug.h"
@@ -194,7 +195,23 @@ static void align(llvm::Module *Module) {
194195
}
195196
}
196197

198+
template <typename... ArgTypes>
199+
void diagnoseSync(
200+
DiagnosticEngine &Diags, llvm::sys::Mutex *DiagMutex, SourceLoc Loc,
201+
Diag<ArgTypes...> ID,
202+
typename swift::detail::PassArgument<ArgTypes>::type... Args) {
203+
if (DiagMutex)
204+
DiagMutex->lock();
205+
206+
Diags.diagnose(Loc, ID, std::move(Args)...);
207+
208+
if (DiagMutex)
209+
DiagMutex->unlock();
210+
}
211+
197212
void swift::performLLVMOptimizations(const IRGenOptions &Opts,
213+
DiagnosticEngine &Diags,
214+
llvm::sys::Mutex *DiagMutex,
198215
llvm::Module *Module,
199216
llvm::TargetMachine *TargetMachine,
200217
llvm::raw_pwrite_stream *out) {
@@ -236,6 +253,18 @@ void swift::performLLVMOptimizations(const IRGenOptions &Opts,
236253

237254
PassBuilder PB(TargetMachine, PTO, PGOOpt, &PIC);
238255

256+
// Attempt to load pass plugins and register their callbacks with PB.
257+
for (const auto &PluginFile : Opts.LLVMPassPlugins) {
258+
Expected<PassPlugin> PassPlugin = PassPlugin::Load(PluginFile);
259+
if (PassPlugin) {
260+
PassPlugin->registerPassBuilderCallbacks(PB);
261+
} else {
262+
diagnoseSync(Diags, DiagMutex, SourceLoc(),
263+
diag::unable_to_load_pass_plugin, PluginFile,
264+
toString(PassPlugin.takeError()));
265+
}
266+
}
267+
239268
// Register the AA manager first so that our version is the one used.
240269
FAM.registerPass([&] {
241270
auto AA = PB.buildDefaultAAPipeline();
@@ -509,20 +538,6 @@ static void countStatsPostIRGen(UnifiedStatsReporter &Stats,
509538
}
510539
}
511540

512-
template<typename ...ArgTypes>
513-
void
514-
diagnoseSync(DiagnosticEngine &Diags, llvm::sys::Mutex *DiagMutex,
515-
SourceLoc Loc, Diag<ArgTypes...> ID,
516-
typename swift::detail::PassArgument<ArgTypes>::type... Args) {
517-
if (DiagMutex)
518-
DiagMutex->lock();
519-
520-
Diags.diagnose(Loc, ID, std::move(Args)...);
521-
522-
if (DiagMutex)
523-
DiagMutex->unlock();
524-
}
525-
526541
/// Run the LLVM passes. In multi-threaded compilation this will be done for
527542
/// multiple LLVM modules in parallel.
528543
bool swift::performLLVM(const IRGenOptions &Opts,
@@ -591,7 +606,7 @@ bool swift::performLLVM(const IRGenOptions &Opts,
591606
assert(Opts.OutputKind == IRGenOutputKind::Module && "no output specified");
592607
}
593608

594-
performLLVMOptimizations(Opts, Module, TargetMachine,
609+
performLLVMOptimizations(Opts, Diags, DiagMutex, Module, TargetMachine,
595610
OutputFile ? &OutputFile->getOS() : nullptr);
596611

597612
if (Stats) {
@@ -1700,7 +1715,7 @@ GeneratedModule OptimizedIRRequest::evaluate(Evaluator &evaluator,
17001715
if (!irMod)
17011716
return irMod;
17021717

1703-
performLLVMOptimizations(desc.Opts, irMod.getModule(),
1718+
performLLVMOptimizations(desc.Opts, ctx.Diags, nullptr, irMod.getModule(),
17041719
irMod.getTargetMachine(), desc.out);
17051720
return irMod;
17061721
}

test/Frontend/Inputs/TestPlugin.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
//===---------------------- TestPlugin.cpp ----------------------*- C++ -*-===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2023 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
// Used by -load-pass-plugin
14+
15+
#include "llvm/Pass.h"
16+
#include "llvm/Passes/PassBuilder.h"
17+
#include "llvm/Passes/PassPlugin.h"
18+
19+
using namespace llvm;
20+
21+
namespace {
22+
23+
void runTestPlugin(Function &F) {
24+
errs() << "TestPlugin: ";
25+
errs().write_escaped(F.getName()) << '\n';
26+
}
27+
28+
struct TestPluginPass : PassInfoMixin<TestPluginPass> {
29+
PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
30+
runTestPlugin(F);
31+
return PreservedAnalyses::all();
32+
}
33+
};
34+
35+
} // namespace
36+
37+
PassPluginLibraryInfo getTestPluginInfo() {
38+
return {LLVM_PLUGIN_API_VERSION, "TestPlugin", LLVM_VERSION_STRING,
39+
[](PassBuilder &PB) {
40+
PB.registerVectorizerStartEPCallback(
41+
[](llvm::FunctionPassManager &PM, OptimizationLevel Level) {
42+
PM.addPass(TestPluginPass());
43+
});
44+
}};
45+
}
46+
47+
extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
48+
llvmGetPassPluginInfo() {
49+
return getTestPluginInfo();
50+
}

test/Frontend/load-pass-plugin.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// REQUIRES: OS=macosx
2+
3+
// RUN: %target-swift-frontend -load-pass-plugin=nonexistent.dylib %s -emit-ir -o /dev/null 2>&1 | %FileCheck -check-prefix=CHECK-UNABLE-LOAD %s
4+
// CHECK-UNABLE-LOAD: error: unable to load plugin 'nonexistent.dylib': 'Could not load library{{.*}}'
5+
6+
// RUN: %target-clangxx %S/Inputs/TestPlugin.cpp -std=c++17 -stdlib=libc++ \
7+
// RUN: -isysroot %sdk -I %llvm_src_root/include -I %llvm_obj_root/include -L %llvm_obj_root/lib -lLLVMSupport \
8+
// RUN: -Wl,-undefined -Wl,suppress -Wl,-flat_namespace \
9+
// RUN: -dynamiclib -o %t/libTestPlugin.dylib
10+
11+
// RUN: %target-swift-frontend -load-pass-plugin=%t/libTestPlugin.dylib %s -emit-ir -o /dev/null 2>&1 | swift-demangle | %FileCheck %s
12+
// CHECK: TestPlugin: main
13+
// CHECK: TestPlugin: null.empty() -> ()
14+
15+
func empty() {}

0 commit comments

Comments
 (0)