1 //===- NewPMDriver.cpp - Driver for opt with new PM -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
10 /// This file is just a split of the code that logically belongs in opt.cpp but
11 /// that includes the new pass manager headers.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "NewPMDriver.h"
16 #include "PassPrinters.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/CGSCCPassManager.h"
21 #include "llvm/Bitcode/BitcodeWriterPass.h"
22 #include "llvm/Config/llvm-config.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IRPrintingPasses.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/PassManager.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/Passes/PassBuilder.h"
30 #include "llvm/Passes/PassPlugin.h"
31 #include "llvm/Passes/StandardInstrumentations.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ToolOutputFile.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
37 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
38 #include "llvm/Transforms/Scalar/LoopPassManager.h"
39 #include "llvm/Transforms/Utils/Debugify.h"
40 
41 using namespace llvm;
42 using namespace opt_tool;
43 
44 static cl::opt<bool>
45     DebugPM("debug-pass-manager", cl::Hidden,
46             cl::desc("Print pass management debugging information"));
47 
48 static cl::list<std::string>
49     PassPlugins("load-pass-plugin",
50                 cl::desc("Load passes from plugin library"));
51 
52 // This flag specifies a textual description of the alias analysis pipeline to
53 // use when querying for aliasing information. It only works in concert with
54 // the "passes" flag above.
55 static cl::opt<std::string>
56     AAPipeline("aa-pipeline",
57                cl::desc("A textual description of the alias analysis "
58                         "pipeline for handling managed aliasing queries"),
59                cl::Hidden);
60 
61 /// {{@ These options accept textual pipeline descriptions which will be
62 /// inserted into default pipelines at the respective extension points
63 static cl::opt<std::string> PeepholeEPPipeline(
64     "passes-ep-peephole",
65     cl::desc("A textual description of the function pass pipeline inserted at "
66              "the Peephole extension points into default pipelines"),
67     cl::Hidden);
68 static cl::opt<std::string> LateLoopOptimizationsEPPipeline(
69     "passes-ep-late-loop-optimizations",
70     cl::desc(
71         "A textual description of the loop pass pipeline inserted at "
72         "the LateLoopOptimizations extension point into default pipelines"),
73     cl::Hidden);
74 static cl::opt<std::string> LoopOptimizerEndEPPipeline(
75     "passes-ep-loop-optimizer-end",
76     cl::desc("A textual description of the loop pass pipeline inserted at "
77              "the LoopOptimizerEnd extension point into default pipelines"),
78     cl::Hidden);
79 static cl::opt<std::string> ScalarOptimizerLateEPPipeline(
80     "passes-ep-scalar-optimizer-late",
81     cl::desc("A textual description of the function pass pipeline inserted at "
82              "the ScalarOptimizerLate extension point into default pipelines"),
83     cl::Hidden);
84 static cl::opt<std::string> CGSCCOptimizerLateEPPipeline(
85     "passes-ep-cgscc-optimizer-late",
86     cl::desc("A textual description of the cgscc pass pipeline inserted at "
87              "the CGSCCOptimizerLate extension point into default pipelines"),
88     cl::Hidden);
89 static cl::opt<std::string> VectorizerStartEPPipeline(
90     "passes-ep-vectorizer-start",
91     cl::desc("A textual description of the function pass pipeline inserted at "
92              "the VectorizerStart extension point into default pipelines"),
93     cl::Hidden);
94 static cl::opt<std::string> PipelineStartEPPipeline(
95     "passes-ep-pipeline-start",
96     cl::desc("A textual description of the function pass pipeline inserted at "
97              "the PipelineStart extension point into default pipelines"),
98     cl::Hidden);
99 static cl::opt<std::string> OptimizerLastEPPipeline(
100     "passes-ep-optimizer-last",
101     cl::desc("A textual description of the function pass pipeline inserted at "
102              "the OptimizerLast extension point into default pipelines"),
103     cl::Hidden);
104 
105 // Individual pipeline tuning options.
106 extern cl::opt<bool> DisableLoopUnrolling;
107 
108 extern cl::opt<PGOKind> PGOKindFlag;
109 extern cl::opt<std::string> ProfileFile;
110 extern cl::opt<CSPGOKind> CSPGOKindFlag;
111 extern cl::opt<std::string> CSProfileGenFile;
112 
113 static cl::opt<std::string>
114     ProfileRemappingFile("profile-remapping-file",
115                          cl::desc("Path to the profile remapping file."),
116                          cl::Hidden);
117 static cl::opt<bool> DebugInfoForProfiling(
118     "new-pm-debug-info-for-profiling", cl::init(false), cl::Hidden,
119     cl::desc("Emit special debug info to enable PGO profile generation."));
120 /// @}}
121 
122 template <typename PassManagerT>
123 bool tryParsePipelineText(PassBuilder &PB,
124                           const cl::opt<std::string> &PipelineOpt) {
125   if (PipelineOpt.empty())
126     return false;
127 
128   // Verify the pipeline is parseable:
129   PassManagerT PM;
130   if (auto Err = PB.parsePassPipeline(PM, PipelineOpt)) {
131     errs() << "Could not parse -" << PipelineOpt.ArgStr
132            << " pipeline: " << toString(std::move(Err))
133            << "... I'm going to ignore it.\n";
134     return false;
135   }
136   return true;
137 }
138 
139 /// If one of the EPPipeline command line options was given, register callbacks
140 /// for parsing and inserting the given pipeline
141 static void registerEPCallbacks(PassBuilder &PB, bool VerifyEachPass,
142                                 bool DebugLogging) {
143   if (tryParsePipelineText<FunctionPassManager>(PB, PeepholeEPPipeline))
144     PB.registerPeepholeEPCallback(
145         [&PB, VerifyEachPass, DebugLogging](
146             FunctionPassManager &PM, PassBuilder::OptimizationLevel Level) {
147           ExitOnError Err("Unable to parse PeepholeEP pipeline: ");
148           Err(PB.parsePassPipeline(PM, PeepholeEPPipeline, VerifyEachPass,
149                                    DebugLogging));
150         });
151   if (tryParsePipelineText<LoopPassManager>(PB,
152                                             LateLoopOptimizationsEPPipeline))
153     PB.registerLateLoopOptimizationsEPCallback(
154         [&PB, VerifyEachPass, DebugLogging](
155             LoopPassManager &PM, PassBuilder::OptimizationLevel Level) {
156           ExitOnError Err("Unable to parse LateLoopOptimizationsEP pipeline: ");
157           Err(PB.parsePassPipeline(PM, LateLoopOptimizationsEPPipeline,
158                                    VerifyEachPass, DebugLogging));
159         });
160   if (tryParsePipelineText<LoopPassManager>(PB, LoopOptimizerEndEPPipeline))
161     PB.registerLoopOptimizerEndEPCallback(
162         [&PB, VerifyEachPass, DebugLogging](
163             LoopPassManager &PM, PassBuilder::OptimizationLevel Level) {
164           ExitOnError Err("Unable to parse LoopOptimizerEndEP pipeline: ");
165           Err(PB.parsePassPipeline(PM, LoopOptimizerEndEPPipeline,
166                                    VerifyEachPass, DebugLogging));
167         });
168   if (tryParsePipelineText<FunctionPassManager>(PB,
169                                                 ScalarOptimizerLateEPPipeline))
170     PB.registerScalarOptimizerLateEPCallback(
171         [&PB, VerifyEachPass, DebugLogging](
172             FunctionPassManager &PM, PassBuilder::OptimizationLevel Level) {
173           ExitOnError Err("Unable to parse ScalarOptimizerLateEP pipeline: ");
174           Err(PB.parsePassPipeline(PM, ScalarOptimizerLateEPPipeline,
175                                    VerifyEachPass, DebugLogging));
176         });
177   if (tryParsePipelineText<CGSCCPassManager>(PB, CGSCCOptimizerLateEPPipeline))
178     PB.registerCGSCCOptimizerLateEPCallback(
179         [&PB, VerifyEachPass, DebugLogging](
180             CGSCCPassManager &PM, PassBuilder::OptimizationLevel Level) {
181           ExitOnError Err("Unable to parse CGSCCOptimizerLateEP pipeline: ");
182           Err(PB.parsePassPipeline(PM, CGSCCOptimizerLateEPPipeline,
183                                    VerifyEachPass, DebugLogging));
184         });
185   if (tryParsePipelineText<FunctionPassManager>(PB, VectorizerStartEPPipeline))
186     PB.registerVectorizerStartEPCallback(
187         [&PB, VerifyEachPass, DebugLogging](
188             FunctionPassManager &PM, PassBuilder::OptimizationLevel Level) {
189           ExitOnError Err("Unable to parse VectorizerStartEP pipeline: ");
190           Err(PB.parsePassPipeline(PM, VectorizerStartEPPipeline,
191                                    VerifyEachPass, DebugLogging));
192         });
193   if (tryParsePipelineText<ModulePassManager>(PB, PipelineStartEPPipeline))
194     PB.registerPipelineStartEPCallback(
195         [&PB, VerifyEachPass, DebugLogging](ModulePassManager &PM) {
196           ExitOnError Err("Unable to parse PipelineStartEP pipeline: ");
197           Err(PB.parsePassPipeline(PM, PipelineStartEPPipeline, VerifyEachPass,
198                                    DebugLogging));
199         });
200   if (tryParsePipelineText<FunctionPassManager>(PB, OptimizerLastEPPipeline))
201     PB.registerOptimizerLastEPCallback(
202         [&PB, VerifyEachPass, DebugLogging](ModulePassManager &PM,
203                                             PassBuilder::OptimizationLevel) {
204           ExitOnError Err("Unable to parse OptimizerLastEP pipeline: ");
205           Err(PB.parsePassPipeline(PM, OptimizerLastEPPipeline, VerifyEachPass,
206                                    DebugLogging));
207         });
208 }
209 
210 #define HANDLE_EXTENSION(Ext)                                                  \
211   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
212 #include "llvm/Support/Extension.def"
213 
214 bool llvm::runPassPipeline(StringRef Arg0, Module &M, TargetMachine *TM,
215                            ToolOutputFile *Out, ToolOutputFile *ThinLTOLinkOut,
216                            ToolOutputFile *OptRemarkFile,
217                            StringRef PassPipeline, ArrayRef<StringRef> Passes,
218                            OutputKind OK, VerifierKind VK,
219                            bool ShouldPreserveAssemblyUseListOrder,
220                            bool ShouldPreserveBitcodeUseListOrder,
221                            bool EmitSummaryIndex, bool EmitModuleHash,
222                            bool EnableDebugify, bool Coroutines) {
223   bool VerifyEachPass = VK == VK_VerifyEachPass;
224 
225   Optional<PGOOptions> P;
226   switch (PGOKindFlag) {
227   case InstrGen:
228     P = PGOOptions(ProfileFile, "", "", PGOOptions::IRInstr);
229     break;
230   case InstrUse:
231     P = PGOOptions(ProfileFile, "", ProfileRemappingFile, PGOOptions::IRUse);
232     break;
233   case SampleUse:
234     P = PGOOptions(ProfileFile, "", ProfileRemappingFile,
235                    PGOOptions::SampleUse);
236     break;
237   case NoPGO:
238     if (DebugInfoForProfiling)
239       P = PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
240                      true);
241     else
242       P = None;
243   }
244   if (CSPGOKindFlag != NoCSPGO) {
245     if (P && (P->Action == PGOOptions::IRInstr ||
246               P->Action == PGOOptions::SampleUse))
247       errs() << "CSPGOKind cannot be used with IRInstr or SampleUse";
248     if (CSPGOKindFlag == CSInstrGen) {
249       if (CSProfileGenFile.empty())
250         errs() << "CSInstrGen needs to specify CSProfileGenFile";
251       if (P) {
252         P->CSAction = PGOOptions::CSIRInstr;
253         P->CSProfileGenFile = CSProfileGenFile;
254       } else
255         P = PGOOptions("", CSProfileGenFile, ProfileRemappingFile,
256                        PGOOptions::NoAction, PGOOptions::CSIRInstr);
257     } else /* CSPGOKindFlag == CSInstrUse */ {
258       if (!P)
259         errs() << "CSInstrUse needs to be together with InstrUse";
260       P->CSAction = PGOOptions::CSIRUse;
261     }
262   }
263   PassInstrumentationCallbacks PIC;
264   StandardInstrumentations SI(DebugPM);
265   SI.registerCallbacks(PIC);
266 
267   PipelineTuningOptions PTO;
268   // LoopUnrolling defaults on to true and DisableLoopUnrolling is initialized
269   // to false above so we shouldn't necessarily need to check whether or not the
270   // option has been enabled.
271   PTO.LoopUnrolling = !DisableLoopUnrolling;
272   PTO.Coroutines = Coroutines;
273   PassBuilder PB(TM, PTO, P, &PIC);
274   registerEPCallbacks(PB, VerifyEachPass, DebugPM);
275 
276   // Load requested pass plugins and let them register pass builder callbacks
277   for (auto &PluginFN : PassPlugins) {
278     auto PassPlugin = PassPlugin::Load(PluginFN);
279     if (!PassPlugin) {
280       errs() << "Failed to load passes from '" << PluginFN
281              << "'. Request ignored.\n";
282       continue;
283     }
284 
285     PassPlugin->registerPassBuilderCallbacks(PB);
286   }
287 
288   // Register a callback that creates the debugify passes as needed.
289   PB.registerPipelineParsingCallback(
290       [](StringRef Name, ModulePassManager &MPM,
291          ArrayRef<PassBuilder::PipelineElement>) {
292         if (Name == "debugify") {
293           MPM.addPass(NewPMDebugifyPass());
294           return true;
295         } else if (Name == "check-debugify") {
296           MPM.addPass(NewPMCheckDebugifyPass());
297           return true;
298         }
299         return false;
300       });
301   PB.registerPipelineParsingCallback(
302       [](StringRef Name, ModulePassManager &MPM,
303          ArrayRef<PassBuilder::PipelineElement>) {
304         if (Name == "asan-pipeline") {
305           MPM.addPass(
306               RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
307           MPM.addPass(
308               createModuleToFunctionPassAdaptor(AddressSanitizerPass()));
309           MPM.addPass(ModuleAddressSanitizerPass());
310           return true;
311         } else if (Name == "asan-function-pipeline") {
312           MPM.addPass(
313               RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
314           MPM.addPass(
315               createModuleToFunctionPassAdaptor(AddressSanitizerPass()));
316           return true;
317         }
318         return false;
319       });
320 
321 #define HANDLE_EXTENSION(Ext)                                                  \
322   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
323 #include "llvm/Support/Extension.def"
324 
325   // Specially handle the alias analysis manager so that we can register
326   // a custom pipeline of AA passes with it.
327   AAManager AA;
328   if (!AAPipeline.empty()) {
329     assert(Passes.empty() &&
330            "--aa-pipeline and -foo-pass should not both be specified");
331     if (auto Err = PB.parseAAPipeline(AA, AAPipeline)) {
332       errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
333       return false;
334     }
335   }
336   // For compatibility with legacy pass manager.
337   // Alias analyses are not specially specified when using the legacy PM.
338   SmallVector<StringRef, 4> NonAAPasses;
339   for (auto PassName : Passes) {
340     if (PB.isAAPassName(PassName)) {
341       if (auto Err = PB.parseAAPipeline(AA, PassName)) {
342         errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
343         return false;
344       }
345     } else {
346       NonAAPasses.push_back(PassName);
347     }
348   }
349 
350   LoopAnalysisManager LAM(DebugPM);
351   FunctionAnalysisManager FAM(DebugPM);
352   CGSCCAnalysisManager CGAM(DebugPM);
353   ModuleAnalysisManager MAM(DebugPM);
354 
355   // Register the AA manager first so that our version is the one used.
356   FAM.registerPass([&] { return std::move(AA); });
357 
358   // Register all the basic analyses with the managers.
359   PB.registerModuleAnalyses(MAM);
360   PB.registerCGSCCAnalyses(CGAM);
361   PB.registerFunctionAnalyses(FAM);
362   PB.registerLoopAnalyses(LAM);
363   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
364 
365   ModulePassManager MPM(DebugPM);
366   if (VK > VK_NoVerifier)
367     MPM.addPass(VerifierPass());
368   if (EnableDebugify)
369     MPM.addPass(NewPMDebugifyPass());
370 
371   if (!PassPipeline.empty()) {
372     assert(Passes.empty() &&
373            "PassPipeline and Passes should not both contain passes");
374     if (auto Err =
375             PB.parsePassPipeline(MPM, PassPipeline, VerifyEachPass, DebugPM)) {
376       errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
377       return false;
378     }
379   }
380   for (auto PassName : NonAAPasses) {
381     std::string ModifiedPassName(PassName.begin(), PassName.end());
382     if (PB.isAnalysisPassName(PassName))
383       ModifiedPassName = "require<" + ModifiedPassName + ">";
384     if (auto Err = PB.parsePassPipeline(MPM, ModifiedPassName, VerifyEachPass,
385                                         DebugPM)) {
386       errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
387       return false;
388     }
389   }
390 
391   if (VK > VK_NoVerifier)
392     MPM.addPass(VerifierPass());
393   if (EnableDebugify)
394     MPM.addPass(NewPMCheckDebugifyPass());
395 
396   // Add any relevant output pass at the end of the pipeline.
397   switch (OK) {
398   case OK_NoOutput:
399     break; // No output pass needed.
400   case OK_OutputAssembly:
401     MPM.addPass(
402         PrintModulePass(Out->os(), "", ShouldPreserveAssemblyUseListOrder));
403     break;
404   case OK_OutputBitcode:
405     MPM.addPass(BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder,
406                                   EmitSummaryIndex, EmitModuleHash));
407     break;
408   case OK_OutputThinLTOBitcode:
409     MPM.addPass(ThinLTOBitcodeWriterPass(
410         Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr));
411     break;
412   }
413 
414   // Before executing passes, print the final values of the LLVM options.
415   cl::PrintOptionValues();
416 
417   // Now that we have all of the passes ready, run them.
418   MPM.run(M, MAM);
419 
420   // Declare success.
421   if (OK != OK_NoOutput) {
422     Out->keep();
423     if (OK == OK_OutputThinLTOBitcode && ThinLTOLinkOut)
424       ThinLTOLinkOut->keep();
425   }
426 
427   if (OptRemarkFile)
428     OptRemarkFile->keep();
429 
430   return true;
431 }
432