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