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, 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, 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, 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, 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, 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, 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, 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, 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, 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 || PseudoProbeForProfiling) 263 P = PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction, 264 DebugInfoForProfiling, PseudoProbeForProfiling); 265 else 266 P = None; 267 } 268 if (CSPGOKindFlag != NoCSPGO) { 269 if (P && (P->Action == PGOOptions::IRInstr || 270 P->Action == PGOOptions::SampleUse)) 271 errs() << "CSPGOKind cannot be used with IRInstr or SampleUse"; 272 if (CSPGOKindFlag == CSInstrGen) { 273 if (CSProfileGenFile.empty()) 274 errs() << "CSInstrGen needs to specify CSProfileGenFile"; 275 if (P) { 276 P->CSAction = PGOOptions::CSIRInstr; 277 P->CSProfileGenFile = CSProfileGenFile; 278 } else 279 P = PGOOptions("", CSProfileGenFile, ProfileRemappingFile, 280 PGOOptions::NoAction, PGOOptions::CSIRInstr); 281 } else /* CSPGOKindFlag == CSInstrUse */ { 282 if (!P) 283 errs() << "CSInstrUse needs to be together with InstrUse"; 284 P->CSAction = PGOOptions::CSIRUse; 285 } 286 } 287 if (TM) 288 TM->setPGOOption(P); 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 AddressSanitizerOptions Opts; 343 if (Name == "asan-pipeline") { 344 MPM.addPass( 345 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 346 MPM.addPass( 347 createModuleToFunctionPassAdaptor(AddressSanitizerPass(Opts))); 348 MPM.addPass(ModuleAddressSanitizerPass()); 349 return true; 350 } else if (Name == "asan-function-pipeline") { 351 MPM.addPass( 352 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>()); 353 MPM.addPass( 354 createModuleToFunctionPassAdaptor(AddressSanitizerPass(Opts))); 355 return true; 356 } 357 return false; 358 }); 359 360 #define HANDLE_EXTENSION(Ext) \ 361 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); 362 #include "llvm/Support/Extension.def" 363 364 // Specially handle the alias analysis manager so that we can register 365 // a custom pipeline of AA passes with it. 366 AAManager AA; 367 if (Passes.empty()) { 368 if (auto Err = PB.parseAAPipeline(AA, AAPipeline)) { 369 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 370 return false; 371 } 372 } 373 374 // For compatibility with the legacy PM AA pipeline. 375 // AAResultsWrapperPass by default provides basic-aa in the legacy PM 376 // unless -disable-basic-aa is specified. 377 // TODO: remove this once tests implicitly requiring basic-aa use -passes= and 378 // -aa-pipeline=basic-aa. 379 if (!Passes.empty() && !DisableBasicAA) { 380 if (auto Err = PB.parseAAPipeline(AA, "basic-aa")) { 381 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 382 return false; 383 } 384 } 385 386 // For compatibility with legacy pass manager. 387 // Alias analyses are not specially specified when using the legacy PM. 388 for (auto PassName : Passes) { 389 if (PB.isAAPassName(PassName)) { 390 if (auto Err = PB.parseAAPipeline(AA, PassName)) { 391 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 392 return false; 393 } 394 } 395 } 396 397 // Register the AA manager first so that our version is the one used. 398 FAM.registerPass([&] { return std::move(AA); }); 399 // Register our TargetLibraryInfoImpl. 400 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); 401 402 // Register all the basic analyses with the managers. 403 PB.registerModuleAnalyses(MAM); 404 PB.registerCGSCCAnalyses(CGAM); 405 PB.registerFunctionAnalyses(FAM); 406 PB.registerLoopAnalyses(LAM); 407 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 408 409 ModulePassManager MPM; 410 if (VK > VK_NoVerifier) 411 MPM.addPass(VerifierPass()); 412 if (EnableDebugify) 413 MPM.addPass(NewPMDebugifyPass()); 414 415 // Add passes according to the -passes options. 416 if (!PassPipeline.empty()) { 417 assert(Passes.empty() && 418 "PassPipeline and Passes should not both contain passes"); 419 if (auto Err = PB.parsePassPipeline(MPM, PassPipeline)) { 420 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 421 return false; 422 } 423 } 424 // Add passes specified using the legacy PM syntax (i.e. not using 425 // -passes). This should be removed later when such support has been 426 // deprecated, i.e. when all lit tests running opt (and not using 427 // -enable-new-pm=0) have been updated to use -passes. 428 for (auto PassName : Passes) { 429 std::string ModifiedPassName(PassName.begin(), PassName.end()); 430 if (PB.isAnalysisPassName(PassName)) 431 ModifiedPassName = "require<" + ModifiedPassName + ">"; 432 // FIXME: These translations are supposed to be removed when lit tests that 433 // use these names have been updated to use the -passes syntax (and when the 434 // support for using the old syntax to specify passes is considered as 435 // deprecated for the new PM). 436 if (ModifiedPassName == "early-cse-memssa") 437 ModifiedPassName = "early-cse<memssa>"; 438 else if (ModifiedPassName == "post-inline-ee-instrument") 439 ModifiedPassName = "ee-instrument<post-inline>"; 440 else if (ModifiedPassName == "loop-extract-single") 441 ModifiedPassName = "loop-extract<single>"; 442 else if (ModifiedPassName == "lower-matrix-intrinsics-minimal") 443 ModifiedPassName = "lower-matrix-intrinsics<minimal>"; 444 if (auto Err = PB.parsePassPipeline(MPM, ModifiedPassName)) { 445 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n"; 446 return false; 447 } 448 } 449 450 if (VK > VK_NoVerifier) 451 MPM.addPass(VerifierPass()); 452 if (EnableDebugify) 453 MPM.addPass(NewPMCheckDebugifyPass()); 454 455 // Add any relevant output pass at the end of the pipeline. 456 switch (OK) { 457 case OK_NoOutput: 458 break; // No output pass needed. 459 case OK_OutputAssembly: 460 MPM.addPass( 461 PrintModulePass(Out->os(), "", ShouldPreserveAssemblyUseListOrder)); 462 break; 463 case OK_OutputBitcode: 464 MPM.addPass(BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder, 465 EmitSummaryIndex, EmitModuleHash)); 466 break; 467 case OK_OutputThinLTOBitcode: 468 MPM.addPass(ThinLTOBitcodeWriterPass( 469 Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr)); 470 break; 471 } 472 473 // Before executing passes, print the final values of the LLVM options. 474 cl::PrintOptionValues(); 475 476 // Now that we have all of the passes ready, run them. 477 MPM.run(M, MAM); 478 479 // Declare success. 480 if (OK != OK_NoOutput) { 481 Out->keep(); 482 if (OK == OK_OutputThinLTOBitcode && ThinLTOLinkOut) 483 ThinLTOLinkOut->keep(); 484 } 485 486 if (OptRemarkFile) 487 OptRemarkFile->keep(); 488 489 if (DebugifyEach && !DebugifyExport.empty()) 490 exportDebugifyStats(DebugifyExport, Debugify.StatsMap); 491 492 return true; 493 } 494 495 void llvm::printPasses(raw_ostream &OS) { 496 PassBuilder PB; 497 PB.printPassNames(OS); 498 } 499