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