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/StringRef.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/CGSCCPassManager.h"
20 #include "llvm/Bitcode/BitcodeWriterPass.h"
21 #include "llvm/Config/llvm-config.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IRPrintingPasses.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/Passes/PassBuilder.h"
29 #include "llvm/Passes/PassPlugin.h"
30 #include "llvm/Passes/StandardInstrumentations.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/ToolOutputFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
36 #include "llvm/Transforms/Scalar/LoopPassManager.h"
37 #include "llvm/Transforms/Utils/Debugify.h"
38 
39 using namespace llvm;
40 using namespace opt_tool;
41 
42 static cl::opt<bool>
43     DebugPM("debug-pass-manager", cl::Hidden,
44             cl::desc("Print pass management debugging information"));
45 
46 static cl::list<std::string>
47     PassPlugins("load-pass-plugin",
48                 cl::desc("Load passes from plugin library"));
49 
50 // This flag specifies a textual description of the alias analysis pipeline to
51 // use when querying for aliasing information. It only works in concert with
52 // the "passes" flag above.
53 static cl::opt<std::string>
54     AAPipeline("aa-pipeline",
55                cl::desc("A textual description of the alias analysis "
56                         "pipeline for handling managed aliasing queries"),
57                cl::Hidden);
58 
59 /// {{@ These options accept textual pipeline descriptions which will be
60 /// inserted into default pipelines at the respective extension points
61 static cl::opt<std::string> PeepholeEPPipeline(
62     "passes-ep-peephole",
63     cl::desc("A textual description of the function pass pipeline inserted at "
64              "the Peephole extension points into default pipelines"),
65     cl::Hidden);
66 static cl::opt<std::string> LateLoopOptimizationsEPPipeline(
67     "passes-ep-late-loop-optimizations",
68     cl::desc(
69         "A textual description of the loop pass pipeline inserted at "
70         "the LateLoopOptimizations extension point into default pipelines"),
71     cl::Hidden);
72 static cl::opt<std::string> LoopOptimizerEndEPPipeline(
73     "passes-ep-loop-optimizer-end",
74     cl::desc("A textual description of the loop pass pipeline inserted at "
75              "the LoopOptimizerEnd extension point into default pipelines"),
76     cl::Hidden);
77 static cl::opt<std::string> ScalarOptimizerLateEPPipeline(
78     "passes-ep-scalar-optimizer-late",
79     cl::desc("A textual description of the function pass pipeline inserted at "
80              "the ScalarOptimizerLate extension point into default pipelines"),
81     cl::Hidden);
82 static cl::opt<std::string> CGSCCOptimizerLateEPPipeline(
83     "passes-ep-cgscc-optimizer-late",
84     cl::desc("A textual description of the cgscc pass pipeline inserted at "
85              "the CGSCCOptimizerLate extension point into default pipelines"),
86     cl::Hidden);
87 static cl::opt<std::string> VectorizerStartEPPipeline(
88     "passes-ep-vectorizer-start",
89     cl::desc("A textual description of the function pass pipeline inserted at "
90              "the VectorizerStart extension point into default pipelines"),
91     cl::Hidden);
92 static cl::opt<std::string> PipelineStartEPPipeline(
93     "passes-ep-pipeline-start",
94     cl::desc("A textual description of the function pass pipeline inserted at "
95              "the PipelineStart extension point into default pipelines"),
96     cl::Hidden);
97 static cl::opt<std::string> OptimizerLastEPPipeline(
98     "passes-ep-optimizer-last",
99     cl::desc("A textual description of the function pass pipeline inserted at "
100              "the OptimizerLast extension point into default pipelines"),
101     cl::Hidden);
102 
103 // Individual pipeline tuning options.
104 static cl::opt<bool> DisableLoopUnrolling(
105     "new-pm-disable-loop-unrolling",
106     cl::desc("Disable loop unrolling in all relevant passes"), cl::init(false));
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, OutputKind OK,
218                            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;
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 
302 #define HANDLE_EXTENSION(Ext)                                                  \
303   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
304 #include "llvm/Support/Extension.def"
305 
306   // Specially handle the alias analysis manager so that we can register
307   // a custom pipeline of AA passes with it.
308   AAManager AA;
309   if (auto Err = PB.parseAAPipeline(AA, AAPipeline)) {
310     errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
311     return false;
312   }
313 
314   LoopAnalysisManager LAM(DebugPM);
315   FunctionAnalysisManager FAM(DebugPM);
316   CGSCCAnalysisManager CGAM(DebugPM);
317   ModuleAnalysisManager MAM(DebugPM);
318 
319   // Register the AA manager first so that our version is the one used.
320   FAM.registerPass([&] { return std::move(AA); });
321 
322   // Register all the basic analyses with the managers.
323   PB.registerModuleAnalyses(MAM);
324   PB.registerCGSCCAnalyses(CGAM);
325   PB.registerFunctionAnalyses(FAM);
326   PB.registerLoopAnalyses(LAM);
327   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
328 
329   ModulePassManager MPM(DebugPM);
330   if (VK > VK_NoVerifier)
331     MPM.addPass(VerifierPass());
332   if (EnableDebugify)
333     MPM.addPass(NewPMDebugifyPass());
334 
335   if (auto Err =
336           PB.parsePassPipeline(MPM, PassPipeline, VerifyEachPass, DebugPM)) {
337     errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
338     return false;
339   }
340 
341   if (VK > VK_NoVerifier)
342     MPM.addPass(VerifierPass());
343   if (EnableDebugify)
344     MPM.addPass(NewPMCheckDebugifyPass());
345 
346   // Add any relevant output pass at the end of the pipeline.
347   switch (OK) {
348   case OK_NoOutput:
349     break; // No output pass needed.
350   case OK_OutputAssembly:
351     MPM.addPass(
352         PrintModulePass(Out->os(), "", ShouldPreserveAssemblyUseListOrder));
353     break;
354   case OK_OutputBitcode:
355     MPM.addPass(BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder,
356                                   EmitSummaryIndex, EmitModuleHash));
357     break;
358   case OK_OutputThinLTOBitcode:
359     MPM.addPass(ThinLTOBitcodeWriterPass(
360         Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr));
361     break;
362   }
363 
364   // Before executing passes, print the final values of the LLVM options.
365   cl::PrintOptionValues();
366 
367   // Now that we have all of the passes ready, run them.
368   MPM.run(M, MAM);
369 
370   // Declare success.
371   if (OK != OK_NoOutput) {
372     Out->keep();
373     if (OK == OK_OutputThinLTOBitcode && ThinLTOLinkOut)
374       ThinLTOLinkOut->keep();
375   }
376 
377   if (OptRemarkFile)
378     OptRemarkFile->keep();
379 
380   return true;
381 }
382