1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the legacy LLVM Pass Manager infrastructure. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/LegacyPassManager.h" 15 #include "llvm/ADT/Statistic.h" 16 #include "llvm/IR/IRPrintingPasses.h" 17 #include "llvm/IR/LLVMContext.h" 18 #include "llvm/IR/LegacyPassManagers.h" 19 #include "llvm/IR/LegacyPassNameParser.h" 20 #include "llvm/IR/Module.h" 21 #include "llvm/Support/Chrono.h" 22 #include "llvm/Support/CommandLine.h" 23 #include "llvm/Support/Debug.h" 24 #include "llvm/Support/Error.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include "llvm/Support/ManagedStatic.h" 27 #include "llvm/Support/Mutex.h" 28 #include "llvm/Support/Timer.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include <algorithm> 31 #include <map> 32 #include <unordered_set> 33 using namespace llvm; 34 using namespace llvm::legacy; 35 36 // See PassManagers.h for Pass Manager infrastructure overview. 37 38 //===----------------------------------------------------------------------===// 39 // Pass debugging information. Often it is useful to find out what pass is 40 // running when a crash occurs in a utility. When this library is compiled with 41 // debugging on, a command line option (--debug-pass) is enabled that causes the 42 // pass name to be printed before it executes. 43 // 44 45 namespace { 46 // Different debug levels that can be enabled... 47 enum PassDebugLevel { 48 Disabled, Arguments, Structure, Executions, Details 49 }; 50 } 51 52 static cl::opt<enum PassDebugLevel> 53 PassDebugging("debug-pass", cl::Hidden, 54 cl::desc("Print PassManager debugging information"), 55 cl::values( 56 clEnumVal(Disabled , "disable debug output"), 57 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"), 58 clEnumVal(Structure , "print pass structure before run()"), 59 clEnumVal(Executions, "print pass name before it is executed"), 60 clEnumVal(Details , "print pass details when it is executed"))); 61 62 namespace { 63 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser> 64 PassOptionList; 65 } 66 67 // Print IR out before/after specified passes. 68 static PassOptionList 69 PrintBefore("print-before", 70 llvm::cl::desc("Print IR before specified passes"), 71 cl::Hidden); 72 73 static PassOptionList 74 PrintAfter("print-after", 75 llvm::cl::desc("Print IR after specified passes"), 76 cl::Hidden); 77 78 static cl::opt<bool> 79 PrintBeforeAll("print-before-all", 80 llvm::cl::desc("Print IR before each pass"), 81 cl::init(false)); 82 static cl::opt<bool> 83 PrintAfterAll("print-after-all", 84 llvm::cl::desc("Print IR after each pass"), 85 cl::init(false)); 86 87 static cl::list<std::string> 88 PrintFuncsList("filter-print-funcs", cl::value_desc("function names"), 89 cl::desc("Only print IR for functions whose name " 90 "match this for all print-[before|after][-all] " 91 "options"), 92 cl::CommaSeparated); 93 94 /// This is a helper to determine whether to print IR before or 95 /// after a pass. 96 97 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI, 98 PassOptionList &PassesToPrint) { 99 for (auto *PassInf : PassesToPrint) { 100 if (PassInf) 101 if (PassInf->getPassArgument() == PI->getPassArgument()) { 102 return true; 103 } 104 } 105 return false; 106 } 107 108 /// This is a utility to check whether a pass should have IR dumped 109 /// before it. 110 static bool ShouldPrintBeforePass(const PassInfo *PI) { 111 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore); 112 } 113 114 /// This is a utility to check whether a pass should have IR dumped 115 /// after it. 116 static bool ShouldPrintAfterPass(const PassInfo *PI) { 117 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter); 118 } 119 120 bool llvm::isFunctionInPrintList(StringRef FunctionName) { 121 static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(), 122 PrintFuncsList.end()); 123 return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName); 124 } 125 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions 126 /// or higher is specified. 127 bool PMDataManager::isPassDebuggingExecutionsOrMore() const { 128 return PassDebugging >= Executions; 129 } 130 131 132 133 134 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const { 135 if (!V && !M) 136 OS << "Releasing pass '"; 137 else 138 OS << "Running pass '"; 139 140 OS << P->getPassName() << "'"; 141 142 if (M) { 143 OS << " on module '" << M->getModuleIdentifier() << "'.\n"; 144 return; 145 } 146 if (!V) { 147 OS << '\n'; 148 return; 149 } 150 151 OS << " on "; 152 if (isa<Function>(V)) 153 OS << "function"; 154 else if (isa<BasicBlock>(V)) 155 OS << "basic block"; 156 else 157 OS << "value"; 158 159 OS << " '"; 160 V->printAsOperand(OS, /*PrintTy=*/false, M); 161 OS << "'\n"; 162 } 163 164 165 namespace { 166 //===----------------------------------------------------------------------===// 167 // BBPassManager 168 // 169 /// BBPassManager manages BasicBlockPass. It batches all the 170 /// pass together and sequence them to process one basic block before 171 /// processing next basic block. 172 class BBPassManager : public PMDataManager, public FunctionPass { 173 174 public: 175 static char ID; 176 explicit BBPassManager() 177 : PMDataManager(), FunctionPass(ID) {} 178 179 /// Execute all of the passes scheduled for execution. Keep track of 180 /// whether any of the passes modifies the function, and if so, return true. 181 bool runOnFunction(Function &F) override; 182 183 /// Pass Manager itself does not invalidate any analysis info. 184 void getAnalysisUsage(AnalysisUsage &Info) const override { 185 Info.setPreservesAll(); 186 } 187 188 bool doInitialization(Module &M) override; 189 bool doInitialization(Function &F); 190 bool doFinalization(Module &M) override; 191 bool doFinalization(Function &F); 192 193 PMDataManager *getAsPMDataManager() override { return this; } 194 Pass *getAsPass() override { return this; } 195 196 StringRef getPassName() const override { return "BasicBlock Pass Manager"; } 197 198 // Print passes managed by this manager 199 void dumpPassStructure(unsigned Offset) override { 200 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n"; 201 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 202 BasicBlockPass *BP = getContainedPass(Index); 203 BP->dumpPassStructure(Offset + 1); 204 dumpLastUses(BP, Offset+1); 205 } 206 } 207 208 BasicBlockPass *getContainedPass(unsigned N) { 209 assert(N < PassVector.size() && "Pass number out of range!"); 210 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]); 211 return BP; 212 } 213 214 PassManagerType getPassManagerType() const override { 215 return PMT_BasicBlockPassManager; 216 } 217 }; 218 219 char BBPassManager::ID = 0; 220 } // End anonymous namespace 221 222 namespace llvm { 223 namespace legacy { 224 //===----------------------------------------------------------------------===// 225 // FunctionPassManagerImpl 226 // 227 /// FunctionPassManagerImpl manages FPPassManagers 228 class FunctionPassManagerImpl : public Pass, 229 public PMDataManager, 230 public PMTopLevelManager { 231 virtual void anchor(); 232 private: 233 bool wasRun; 234 public: 235 static char ID; 236 explicit FunctionPassManagerImpl() : 237 Pass(PT_PassManager, ID), PMDataManager(), 238 PMTopLevelManager(new FPPassManager()), wasRun(false) {} 239 240 /// \copydoc FunctionPassManager::add() 241 void add(Pass *P) { 242 schedulePass(P); 243 } 244 245 /// createPrinterPass - Get a function printer pass. 246 Pass *createPrinterPass(raw_ostream &O, 247 const std::string &Banner) const override { 248 return createPrintFunctionPass(O, Banner); 249 } 250 251 // Prepare for running an on the fly pass, freeing memory if needed 252 // from a previous run. 253 void releaseMemoryOnTheFly(); 254 255 /// run - Execute all of the passes scheduled for execution. Keep track of 256 /// whether any of the passes modifies the module, and if so, return true. 257 bool run(Function &F); 258 259 /// doInitialization - Run all of the initializers for the function passes. 260 /// 261 bool doInitialization(Module &M) override; 262 263 /// doFinalization - Run all of the finalizers for the function passes. 264 /// 265 bool doFinalization(Module &M) override; 266 267 268 PMDataManager *getAsPMDataManager() override { return this; } 269 Pass *getAsPass() override { return this; } 270 PassManagerType getTopLevelPassManagerType() override { 271 return PMT_FunctionPassManager; 272 } 273 274 /// Pass Manager itself does not invalidate any analysis info. 275 void getAnalysisUsage(AnalysisUsage &Info) const override { 276 Info.setPreservesAll(); 277 } 278 279 FPPassManager *getContainedManager(unsigned N) { 280 assert(N < PassManagers.size() && "Pass number out of range!"); 281 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]); 282 return FP; 283 } 284 }; 285 286 void FunctionPassManagerImpl::anchor() {} 287 288 char FunctionPassManagerImpl::ID = 0; 289 } // End of legacy namespace 290 } // End of llvm namespace 291 292 namespace { 293 //===----------------------------------------------------------------------===// 294 // MPPassManager 295 // 296 /// MPPassManager manages ModulePasses and function pass managers. 297 /// It batches all Module passes and function pass managers together and 298 /// sequences them to process one module. 299 class MPPassManager : public Pass, public PMDataManager { 300 public: 301 static char ID; 302 explicit MPPassManager() : 303 Pass(PT_PassManager, ID), PMDataManager() { } 304 305 // Delete on the fly managers. 306 ~MPPassManager() override { 307 for (auto &OnTheFlyManager : OnTheFlyManagers) { 308 FunctionPassManagerImpl *FPP = OnTheFlyManager.second; 309 delete FPP; 310 } 311 } 312 313 /// createPrinterPass - Get a module printer pass. 314 Pass *createPrinterPass(raw_ostream &O, 315 const std::string &Banner) const override { 316 return createPrintModulePass(O, Banner); 317 } 318 319 /// run - Execute all of the passes scheduled for execution. Keep track of 320 /// whether any of the passes modifies the module, and if so, return true. 321 bool runOnModule(Module &M); 322 323 using llvm::Pass::doInitialization; 324 using llvm::Pass::doFinalization; 325 326 /// Pass Manager itself does not invalidate any analysis info. 327 void getAnalysisUsage(AnalysisUsage &Info) const override { 328 Info.setPreservesAll(); 329 } 330 331 /// Add RequiredPass into list of lower level passes required by pass P. 332 /// RequiredPass is run on the fly by Pass Manager when P requests it 333 /// through getAnalysis interface. 334 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override; 335 336 /// Return function pass corresponding to PassInfo PI, that is 337 /// required by module pass MP. Instantiate analysis pass, by using 338 /// its runOnFunction() for function F. 339 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override; 340 341 StringRef getPassName() const override { return "Module Pass Manager"; } 342 343 PMDataManager *getAsPMDataManager() override { return this; } 344 Pass *getAsPass() override { return this; } 345 346 // Print passes managed by this manager 347 void dumpPassStructure(unsigned Offset) override { 348 dbgs().indent(Offset*2) << "ModulePass Manager\n"; 349 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 350 ModulePass *MP = getContainedPass(Index); 351 MP->dumpPassStructure(Offset + 1); 352 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I = 353 OnTheFlyManagers.find(MP); 354 if (I != OnTheFlyManagers.end()) 355 I->second->dumpPassStructure(Offset + 2); 356 dumpLastUses(MP, Offset+1); 357 } 358 } 359 360 ModulePass *getContainedPass(unsigned N) { 361 assert(N < PassVector.size() && "Pass number out of range!"); 362 return static_cast<ModulePass *>(PassVector[N]); 363 } 364 365 PassManagerType getPassManagerType() const override { 366 return PMT_ModulePassManager; 367 } 368 369 private: 370 /// Collection of on the fly FPPassManagers. These managers manage 371 /// function passes that are required by module passes. 372 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers; 373 }; 374 375 char MPPassManager::ID = 0; 376 } // End anonymous namespace 377 378 namespace llvm { 379 namespace legacy { 380 //===----------------------------------------------------------------------===// 381 // PassManagerImpl 382 // 383 384 /// PassManagerImpl manages MPPassManagers 385 class PassManagerImpl : public Pass, 386 public PMDataManager, 387 public PMTopLevelManager { 388 virtual void anchor(); 389 390 public: 391 static char ID; 392 explicit PassManagerImpl() : 393 Pass(PT_PassManager, ID), PMDataManager(), 394 PMTopLevelManager(new MPPassManager()) {} 395 396 /// \copydoc PassManager::add() 397 void add(Pass *P) { 398 schedulePass(P); 399 } 400 401 /// createPrinterPass - Get a module printer pass. 402 Pass *createPrinterPass(raw_ostream &O, 403 const std::string &Banner) const override { 404 return createPrintModulePass(O, Banner); 405 } 406 407 /// run - Execute all of the passes scheduled for execution. Keep track of 408 /// whether any of the passes modifies the module, and if so, return true. 409 bool run(Module &M); 410 411 using llvm::Pass::doInitialization; 412 using llvm::Pass::doFinalization; 413 414 /// Pass Manager itself does not invalidate any analysis info. 415 void getAnalysisUsage(AnalysisUsage &Info) const override { 416 Info.setPreservesAll(); 417 } 418 419 PMDataManager *getAsPMDataManager() override { return this; } 420 Pass *getAsPass() override { return this; } 421 PassManagerType getTopLevelPassManagerType() override { 422 return PMT_ModulePassManager; 423 } 424 425 MPPassManager *getContainedManager(unsigned N) { 426 assert(N < PassManagers.size() && "Pass number out of range!"); 427 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]); 428 return MP; 429 } 430 }; 431 432 void PassManagerImpl::anchor() {} 433 434 char PassManagerImpl::ID = 0; 435 } // End of legacy namespace 436 } // End of llvm namespace 437 438 namespace { 439 440 //===----------------------------------------------------------------------===// 441 /// TimingInfo Class - This class is used to calculate information about the 442 /// amount of time each pass takes to execute. This only happens when 443 /// -time-passes is enabled on the command line. 444 /// 445 446 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex; 447 448 class TimingInfo { 449 DenseMap<Pass*, Timer*> TimingData; 450 TimerGroup TG; 451 public: 452 // Use 'create' member to get this. 453 TimingInfo() : TG("pass", "... Pass execution timing report ...") {} 454 455 // TimingDtor - Print out information about timing information 456 ~TimingInfo() { 457 // Delete all of the timers, which accumulate their info into the 458 // TimerGroup. 459 for (auto &I : TimingData) 460 delete I.second; 461 // TimerGroup is deleted next, printing the report. 462 } 463 464 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer 465 // to a non-null value (if the -time-passes option is enabled) or it leaves it 466 // null. It may be called multiple times. 467 static void createTheTimeInfo(); 468 469 // print - Prints out timing information and then resets the timers. 470 void print() { 471 TG.print(*CreateInfoOutputFile()); 472 } 473 474 /// getPassTimer - Return the timer for the specified pass if it exists. 475 Timer *getPassTimer(Pass *P) { 476 if (P->getAsPMDataManager()) 477 return nullptr; 478 479 sys::SmartScopedLock<true> Lock(*TimingInfoMutex); 480 Timer *&T = TimingData[P]; 481 if (!T) { 482 StringRef PassName = P->getPassName(); 483 T = new Timer(PassName, PassName, TG); 484 } 485 return T; 486 } 487 }; 488 489 } // End of anon namespace 490 491 static TimingInfo *TheTimeInfo; 492 493 //===----------------------------------------------------------------------===// 494 // PMTopLevelManager implementation 495 496 /// Initialize top level manager. Create first pass manager. 497 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) { 498 PMDM->setTopLevelManager(this); 499 addPassManager(PMDM); 500 activeStack.push(PMDM); 501 } 502 503 /// Set pass P as the last user of the given analysis passes. 504 void 505 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) { 506 unsigned PDepth = 0; 507 if (P->getResolver()) 508 PDepth = P->getResolver()->getPMDataManager().getDepth(); 509 510 for (Pass *AP : AnalysisPasses) { 511 LastUser[AP] = P; 512 513 if (P == AP) 514 continue; 515 516 // Update the last users of passes that are required transitive by AP. 517 AnalysisUsage *AnUsage = findAnalysisUsage(AP); 518 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet(); 519 SmallVector<Pass *, 12> LastUses; 520 SmallVector<Pass *, 12> LastPMUses; 521 for (AnalysisID ID : IDs) { 522 Pass *AnalysisPass = findAnalysisPass(ID); 523 assert(AnalysisPass && "Expected analysis pass to exist."); 524 AnalysisResolver *AR = AnalysisPass->getResolver(); 525 assert(AR && "Expected analysis resolver to exist."); 526 unsigned APDepth = AR->getPMDataManager().getDepth(); 527 528 if (PDepth == APDepth) 529 LastUses.push_back(AnalysisPass); 530 else if (PDepth > APDepth) 531 LastPMUses.push_back(AnalysisPass); 532 } 533 534 setLastUser(LastUses, P); 535 536 // If this pass has a corresponding pass manager, push higher level 537 // analysis to this pass manager. 538 if (P->getResolver()) 539 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass()); 540 541 542 // If AP is the last user of other passes then make P last user of 543 // such passes. 544 for (auto LU : LastUser) { 545 if (LU.second == AP) 546 // DenseMap iterator is not invalidated here because 547 // this is just updating existing entries. 548 LastUser[LU.first] = P; 549 } 550 } 551 } 552 553 /// Collect passes whose last user is P 554 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses, 555 Pass *P) { 556 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI = 557 InversedLastUser.find(P); 558 if (DMI == InversedLastUser.end()) 559 return; 560 561 SmallPtrSet<Pass *, 8> &LU = DMI->second; 562 for (Pass *LUP : LU) { 563 LastUses.push_back(LUP); 564 } 565 566 } 567 568 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) { 569 AnalysisUsage *AnUsage = nullptr; 570 auto DMI = AnUsageMap.find(P); 571 if (DMI != AnUsageMap.end()) 572 AnUsage = DMI->second; 573 else { 574 // Look up the analysis usage from the pass instance (different instances 575 // of the same pass can produce different results), but unique the 576 // resulting object to reduce memory usage. This helps to greatly reduce 577 // memory usage when we have many instances of only a few pass types 578 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set 579 // of dependencies. 580 AnalysisUsage AU; 581 P->getAnalysisUsage(AU); 582 583 AUFoldingSetNode* Node = nullptr; 584 FoldingSetNodeID ID; 585 AUFoldingSetNode::Profile(ID, AU); 586 void *IP = nullptr; 587 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP)) 588 Node = N; 589 else { 590 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU); 591 UniqueAnalysisUsages.InsertNode(Node, IP); 592 } 593 assert(Node && "cached analysis usage must be non null"); 594 595 AnUsageMap[P] = &Node->AU; 596 AnUsage = &Node->AU; 597 } 598 return AnUsage; 599 } 600 601 /// Schedule pass P for execution. Make sure that passes required by 602 /// P are run before P is run. Update analysis info maintained by 603 /// the manager. Remove dead passes. This is a recursive function. 604 void PMTopLevelManager::schedulePass(Pass *P) { 605 606 // TODO : Allocate function manager for this pass, other wise required set 607 // may be inserted into previous function manager 608 609 // Give pass a chance to prepare the stage. 610 P->preparePassManager(activeStack); 611 612 // If P is an analysis pass and it is available then do not 613 // generate the analysis again. Stale analysis info should not be 614 // available at this point. 615 const PassInfo *PI = findAnalysisPassInfo(P->getPassID()); 616 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) { 617 delete P; 618 return; 619 } 620 621 AnalysisUsage *AnUsage = findAnalysisUsage(P); 622 623 bool checkAnalysis = true; 624 while (checkAnalysis) { 625 checkAnalysis = false; 626 627 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet(); 628 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(), 629 E = RequiredSet.end(); I != E; ++I) { 630 631 Pass *AnalysisPass = findAnalysisPass(*I); 632 if (!AnalysisPass) { 633 const PassInfo *PI = findAnalysisPassInfo(*I); 634 635 if (!PI) { 636 // Pass P is not in the global PassRegistry 637 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n"; 638 dbgs() << "Verify if there is a pass dependency cycle." << "\n"; 639 dbgs() << "Required Passes:" << "\n"; 640 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(), 641 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) { 642 Pass *AnalysisPass2 = findAnalysisPass(*I2); 643 if (AnalysisPass2) { 644 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n"; 645 } else { 646 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n"; 647 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n"; 648 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n"; 649 } 650 } 651 } 652 653 assert(PI && "Expected required passes to be initialized"); 654 AnalysisPass = PI->createPass(); 655 if (P->getPotentialPassManagerType () == 656 AnalysisPass->getPotentialPassManagerType()) 657 // Schedule analysis pass that is managed by the same pass manager. 658 schedulePass(AnalysisPass); 659 else if (P->getPotentialPassManagerType () > 660 AnalysisPass->getPotentialPassManagerType()) { 661 // Schedule analysis pass that is managed by a new manager. 662 schedulePass(AnalysisPass); 663 // Recheck analysis passes to ensure that required analyses that 664 // are already checked are still available. 665 checkAnalysis = true; 666 } else 667 // Do not schedule this analysis. Lower level analysis 668 // passes are run on the fly. 669 delete AnalysisPass; 670 } 671 } 672 } 673 674 // Now all required passes are available. 675 if (ImmutablePass *IP = P->getAsImmutablePass()) { 676 // P is a immutable pass and it will be managed by this 677 // top level manager. Set up analysis resolver to connect them. 678 PMDataManager *DM = getAsPMDataManager(); 679 AnalysisResolver *AR = new AnalysisResolver(*DM); 680 P->setResolver(AR); 681 DM->initializeAnalysisImpl(P); 682 addImmutablePass(IP); 683 DM->recordAvailableAnalysis(IP); 684 return; 685 } 686 687 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) { 688 Pass *PP = P->createPrinterPass( 689 dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str()); 690 PP->assignPassManager(activeStack, getTopLevelPassManagerType()); 691 } 692 693 // Add the requested pass to the best available pass manager. 694 P->assignPassManager(activeStack, getTopLevelPassManagerType()); 695 696 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) { 697 Pass *PP = P->createPrinterPass( 698 dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str()); 699 PP->assignPassManager(activeStack, getTopLevelPassManagerType()); 700 } 701 } 702 703 /// Find the pass that implements Analysis AID. Search immutable 704 /// passes and all pass managers. If desired pass is not found 705 /// then return NULL. 706 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) { 707 // For immutable passes we have a direct mapping from ID to pass, so check 708 // that first. 709 if (Pass *P = ImmutablePassMap.lookup(AID)) 710 return P; 711 712 // Check pass managers 713 for (PMDataManager *PassManager : PassManagers) 714 if (Pass *P = PassManager->findAnalysisPass(AID, false)) 715 return P; 716 717 // Check other pass managers 718 for (PMDataManager *IndirectPassManager : IndirectPassManagers) 719 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false)) 720 return P; 721 722 return nullptr; 723 } 724 725 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const { 726 const PassInfo *&PI = AnalysisPassInfos[AID]; 727 if (!PI) 728 PI = PassRegistry::getPassRegistry()->getPassInfo(AID); 729 else 730 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) && 731 "The pass info pointer changed for an analysis ID!"); 732 733 return PI; 734 } 735 736 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) { 737 P->initializePass(); 738 ImmutablePasses.push_back(P); 739 740 // Add this pass to the map from its analysis ID. We clobber any prior runs 741 // of the pass in the map so that the last one added is the one found when 742 // doing lookups. 743 AnalysisID AID = P->getPassID(); 744 ImmutablePassMap[AID] = P; 745 746 // Also add any interfaces implemented by the immutable pass to the map for 747 // fast lookup. 748 const PassInfo *PassInf = findAnalysisPassInfo(AID); 749 assert(PassInf && "Expected all immutable passes to be initialized"); 750 for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented()) 751 ImmutablePassMap[ImmPI->getTypeInfo()] = P; 752 } 753 754 // Print passes managed by this top level manager. 755 void PMTopLevelManager::dumpPasses() const { 756 757 if (PassDebugging < Structure) 758 return; 759 760 // Print out the immutable passes 761 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) { 762 ImmutablePasses[i]->dumpPassStructure(0); 763 } 764 765 // Every class that derives from PMDataManager also derives from Pass 766 // (sometimes indirectly), but there's no inheritance relationship 767 // between PMDataManager and Pass, so we have to getAsPass to get 768 // from a PMDataManager* to a Pass*. 769 for (PMDataManager *Manager : PassManagers) 770 Manager->getAsPass()->dumpPassStructure(1); 771 } 772 773 void PMTopLevelManager::dumpArguments() const { 774 775 if (PassDebugging < Arguments) 776 return; 777 778 dbgs() << "Pass Arguments: "; 779 for (ImmutablePass *P : ImmutablePasses) 780 if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) { 781 assert(PI && "Expected all immutable passes to be initialized"); 782 if (!PI->isAnalysisGroup()) 783 dbgs() << " -" << PI->getPassArgument(); 784 } 785 for (PMDataManager *PM : PassManagers) 786 PM->dumpPassArguments(); 787 dbgs() << "\n"; 788 } 789 790 void PMTopLevelManager::initializeAllAnalysisInfo() { 791 for (PMDataManager *PM : PassManagers) 792 PM->initializeAnalysisInfo(); 793 794 // Initailize other pass managers 795 for (PMDataManager *IPM : IndirectPassManagers) 796 IPM->initializeAnalysisInfo(); 797 798 for (auto LU : LastUser) { 799 SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second]; 800 L.insert(LU.first); 801 } 802 } 803 804 /// Destructor 805 PMTopLevelManager::~PMTopLevelManager() { 806 for (PMDataManager *PM : PassManagers) 807 delete PM; 808 809 for (ImmutablePass *P : ImmutablePasses) 810 delete P; 811 } 812 813 //===----------------------------------------------------------------------===// 814 // PMDataManager implementation 815 816 /// Augement AvailableAnalysis by adding analysis made available by pass P. 817 void PMDataManager::recordAvailableAnalysis(Pass *P) { 818 AnalysisID PI = P->getPassID(); 819 820 AvailableAnalysis[PI] = P; 821 822 assert(!AvailableAnalysis.empty()); 823 824 // This pass is the current implementation of all of the interfaces it 825 // implements as well. 826 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI); 827 if (!PInf) return; 828 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented(); 829 for (unsigned i = 0, e = II.size(); i != e; ++i) 830 AvailableAnalysis[II[i]->getTypeInfo()] = P; 831 } 832 833 // Return true if P preserves high level analysis used by other 834 // passes managed by this manager 835 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) { 836 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P); 837 if (AnUsage->getPreservesAll()) 838 return true; 839 840 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet(); 841 for (Pass *P1 : HigherLevelAnalysis) { 842 if (P1->getAsImmutablePass() == nullptr && 843 !is_contained(PreservedSet, P1->getPassID())) 844 return false; 845 } 846 847 return true; 848 } 849 850 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P. 851 void PMDataManager::verifyPreservedAnalysis(Pass *P) { 852 // Don't do this unless assertions are enabled. 853 #ifdef NDEBUG 854 return; 855 #endif 856 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P); 857 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet(); 858 859 // Verify preserved analysis 860 for (AnalysisID AID : PreservedSet) { 861 if (Pass *AP = findAnalysisPass(AID, true)) { 862 TimeRegion PassTimer(getPassTimer(AP)); 863 AP->verifyAnalysis(); 864 } 865 } 866 } 867 868 /// Remove Analysis not preserved by Pass P 869 void PMDataManager::removeNotPreservedAnalysis(Pass *P) { 870 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P); 871 if (AnUsage->getPreservesAll()) 872 return; 873 874 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet(); 875 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(), 876 E = AvailableAnalysis.end(); I != E; ) { 877 DenseMap<AnalysisID, Pass*>::iterator Info = I++; 878 if (Info->second->getAsImmutablePass() == nullptr && 879 !is_contained(PreservedSet, Info->first)) { 880 // Remove this analysis 881 if (PassDebugging >= Details) { 882 Pass *S = Info->second; 883 dbgs() << " -- '" << P->getPassName() << "' is not preserving '"; 884 dbgs() << S->getPassName() << "'\n"; 885 } 886 AvailableAnalysis.erase(Info); 887 } 888 } 889 890 // Check inherited analysis also. If P is not preserving analysis 891 // provided by parent manager then remove it here. 892 for (unsigned Index = 0; Index < PMT_Last; ++Index) { 893 894 if (!InheritedAnalysis[Index]) 895 continue; 896 897 for (DenseMap<AnalysisID, Pass*>::iterator 898 I = InheritedAnalysis[Index]->begin(), 899 E = InheritedAnalysis[Index]->end(); I != E; ) { 900 DenseMap<AnalysisID, Pass *>::iterator Info = I++; 901 if (Info->second->getAsImmutablePass() == nullptr && 902 !is_contained(PreservedSet, Info->first)) { 903 // Remove this analysis 904 if (PassDebugging >= Details) { 905 Pass *S = Info->second; 906 dbgs() << " -- '" << P->getPassName() << "' is not preserving '"; 907 dbgs() << S->getPassName() << "'\n"; 908 } 909 InheritedAnalysis[Index]->erase(Info); 910 } 911 } 912 } 913 } 914 915 /// Remove analysis passes that are not used any longer 916 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg, 917 enum PassDebuggingString DBG_STR) { 918 919 SmallVector<Pass *, 12> DeadPasses; 920 921 // If this is a on the fly manager then it does not have TPM. 922 if (!TPM) 923 return; 924 925 TPM->collectLastUses(DeadPasses, P); 926 927 if (PassDebugging >= Details && !DeadPasses.empty()) { 928 dbgs() << " -*- '" << P->getPassName(); 929 dbgs() << "' is the last user of following pass instances."; 930 dbgs() << " Free these instances\n"; 931 } 932 933 for (Pass *P : DeadPasses) 934 freePass(P, Msg, DBG_STR); 935 } 936 937 void PMDataManager::freePass(Pass *P, StringRef Msg, 938 enum PassDebuggingString DBG_STR) { 939 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg); 940 941 { 942 // If the pass crashes releasing memory, remember this. 943 PassManagerPrettyStackEntry X(P); 944 TimeRegion PassTimer(getPassTimer(P)); 945 946 P->releaseMemory(); 947 } 948 949 AnalysisID PI = P->getPassID(); 950 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) { 951 // Remove the pass itself (if it is not already removed). 952 AvailableAnalysis.erase(PI); 953 954 // Remove all interfaces this pass implements, for which it is also 955 // listed as the available implementation. 956 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented(); 957 for (unsigned i = 0, e = II.size(); i != e; ++i) { 958 DenseMap<AnalysisID, Pass*>::iterator Pos = 959 AvailableAnalysis.find(II[i]->getTypeInfo()); 960 if (Pos != AvailableAnalysis.end() && Pos->second == P) 961 AvailableAnalysis.erase(Pos); 962 } 963 } 964 } 965 966 /// Add pass P into the PassVector. Update 967 /// AvailableAnalysis appropriately if ProcessAnalysis is true. 968 void PMDataManager::add(Pass *P, bool ProcessAnalysis) { 969 // This manager is going to manage pass P. Set up analysis resolver 970 // to connect them. 971 AnalysisResolver *AR = new AnalysisResolver(*this); 972 P->setResolver(AR); 973 974 // If a FunctionPass F is the last user of ModulePass info M 975 // then the F's manager, not F, records itself as a last user of M. 976 SmallVector<Pass *, 12> TransferLastUses; 977 978 if (!ProcessAnalysis) { 979 // Add pass 980 PassVector.push_back(P); 981 return; 982 } 983 984 // At the moment, this pass is the last user of all required passes. 985 SmallVector<Pass *, 12> LastUses; 986 SmallVector<Pass *, 8> UsedPasses; 987 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable; 988 989 unsigned PDepth = this->getDepth(); 990 991 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P); 992 for (Pass *PUsed : UsedPasses) { 993 unsigned RDepth = 0; 994 995 assert(PUsed->getResolver() && "Analysis Resolver is not set"); 996 PMDataManager &DM = PUsed->getResolver()->getPMDataManager(); 997 RDepth = DM.getDepth(); 998 999 if (PDepth == RDepth) 1000 LastUses.push_back(PUsed); 1001 else if (PDepth > RDepth) { 1002 // Let the parent claim responsibility of last use 1003 TransferLastUses.push_back(PUsed); 1004 // Keep track of higher level analysis used by this manager. 1005 HigherLevelAnalysis.push_back(PUsed); 1006 } else 1007 llvm_unreachable("Unable to accommodate Used Pass"); 1008 } 1009 1010 // Set P as P's last user until someone starts using P. 1011 // However, if P is a Pass Manager then it does not need 1012 // to record its last user. 1013 if (!P->getAsPMDataManager()) 1014 LastUses.push_back(P); 1015 TPM->setLastUser(LastUses, P); 1016 1017 if (!TransferLastUses.empty()) { 1018 Pass *My_PM = getAsPass(); 1019 TPM->setLastUser(TransferLastUses, My_PM); 1020 TransferLastUses.clear(); 1021 } 1022 1023 // Now, take care of required analyses that are not available. 1024 for (AnalysisID ID : ReqAnalysisNotAvailable) { 1025 const PassInfo *PI = TPM->findAnalysisPassInfo(ID); 1026 Pass *AnalysisPass = PI->createPass(); 1027 this->addLowerLevelRequiredPass(P, AnalysisPass); 1028 } 1029 1030 // Take a note of analysis required and made available by this pass. 1031 // Remove the analysis not preserved by this pass 1032 removeNotPreservedAnalysis(P); 1033 recordAvailableAnalysis(P); 1034 1035 // Add pass 1036 PassVector.push_back(P); 1037 } 1038 1039 1040 /// Populate UP with analysis pass that are used or required by 1041 /// pass P and are available. Populate RP_NotAvail with analysis 1042 /// pass that are required by pass P but are not available. 1043 void PMDataManager::collectRequiredAndUsedAnalyses( 1044 SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail, 1045 Pass *P) { 1046 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P); 1047 1048 for (const auto &UsedID : AnUsage->getUsedSet()) 1049 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true)) 1050 UP.push_back(AnalysisPass); 1051 1052 for (const auto &RequiredID : AnUsage->getRequiredSet()) 1053 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true)) 1054 UP.push_back(AnalysisPass); 1055 else 1056 RP_NotAvail.push_back(RequiredID); 1057 1058 for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet()) 1059 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true)) 1060 UP.push_back(AnalysisPass); 1061 else 1062 RP_NotAvail.push_back(RequiredID); 1063 } 1064 1065 // All Required analyses should be available to the pass as it runs! Here 1066 // we fill in the AnalysisImpls member of the pass so that it can 1067 // successfully use the getAnalysis() method to retrieve the 1068 // implementations it needs. 1069 // 1070 void PMDataManager::initializeAnalysisImpl(Pass *P) { 1071 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P); 1072 1073 for (AnalysisUsage::VectorType::const_iterator 1074 I = AnUsage->getRequiredSet().begin(), 1075 E = AnUsage->getRequiredSet().end(); I != E; ++I) { 1076 Pass *Impl = findAnalysisPass(*I, true); 1077 if (!Impl) 1078 // This may be analysis pass that is initialized on the fly. 1079 // If that is not the case then it will raise an assert when it is used. 1080 continue; 1081 AnalysisResolver *AR = P->getResolver(); 1082 assert(AR && "Analysis Resolver is not set"); 1083 AR->addAnalysisImplsPair(*I, Impl); 1084 } 1085 } 1086 1087 /// Find the pass that implements Analysis AID. If desired pass is not found 1088 /// then return NULL. 1089 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) { 1090 1091 // Check if AvailableAnalysis map has one entry. 1092 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID); 1093 1094 if (I != AvailableAnalysis.end()) 1095 return I->second; 1096 1097 // Search Parents through TopLevelManager 1098 if (SearchParent) 1099 return TPM->findAnalysisPass(AID); 1100 1101 return nullptr; 1102 } 1103 1104 // Print list of passes that are last used by P. 1105 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{ 1106 1107 SmallVector<Pass *, 12> LUses; 1108 1109 // If this is a on the fly manager then it does not have TPM. 1110 if (!TPM) 1111 return; 1112 1113 TPM->collectLastUses(LUses, P); 1114 1115 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(), 1116 E = LUses.end(); I != E; ++I) { 1117 dbgs() << "--" << std::string(Offset*2, ' '); 1118 (*I)->dumpPassStructure(0); 1119 } 1120 } 1121 1122 void PMDataManager::dumpPassArguments() const { 1123 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(), 1124 E = PassVector.end(); I != E; ++I) { 1125 if (PMDataManager *PMD = (*I)->getAsPMDataManager()) 1126 PMD->dumpPassArguments(); 1127 else 1128 if (const PassInfo *PI = 1129 TPM->findAnalysisPassInfo((*I)->getPassID())) 1130 if (!PI->isAnalysisGroup()) 1131 dbgs() << " -" << PI->getPassArgument(); 1132 } 1133 } 1134 1135 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1, 1136 enum PassDebuggingString S2, 1137 StringRef Msg) { 1138 if (PassDebugging < Executions) 1139 return; 1140 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this 1141 << std::string(getDepth() * 2 + 1, ' '); 1142 switch (S1) { 1143 case EXECUTION_MSG: 1144 dbgs() << "Executing Pass '" << P->getPassName(); 1145 break; 1146 case MODIFICATION_MSG: 1147 dbgs() << "Made Modification '" << P->getPassName(); 1148 break; 1149 case FREEING_MSG: 1150 dbgs() << " Freeing Pass '" << P->getPassName(); 1151 break; 1152 default: 1153 break; 1154 } 1155 switch (S2) { 1156 case ON_BASICBLOCK_MSG: 1157 dbgs() << "' on BasicBlock '" << Msg << "'...\n"; 1158 break; 1159 case ON_FUNCTION_MSG: 1160 dbgs() << "' on Function '" << Msg << "'...\n"; 1161 break; 1162 case ON_MODULE_MSG: 1163 dbgs() << "' on Module '" << Msg << "'...\n"; 1164 break; 1165 case ON_REGION_MSG: 1166 dbgs() << "' on Region '" << Msg << "'...\n"; 1167 break; 1168 case ON_LOOP_MSG: 1169 dbgs() << "' on Loop '" << Msg << "'...\n"; 1170 break; 1171 case ON_CG_MSG: 1172 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n"; 1173 break; 1174 default: 1175 break; 1176 } 1177 } 1178 1179 void PMDataManager::dumpRequiredSet(const Pass *P) const { 1180 if (PassDebugging < Details) 1181 return; 1182 1183 AnalysisUsage analysisUsage; 1184 P->getAnalysisUsage(analysisUsage); 1185 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet()); 1186 } 1187 1188 void PMDataManager::dumpPreservedSet(const Pass *P) const { 1189 if (PassDebugging < Details) 1190 return; 1191 1192 AnalysisUsage analysisUsage; 1193 P->getAnalysisUsage(analysisUsage); 1194 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet()); 1195 } 1196 1197 void PMDataManager::dumpUsedSet(const Pass *P) const { 1198 if (PassDebugging < Details) 1199 return; 1200 1201 AnalysisUsage analysisUsage; 1202 P->getAnalysisUsage(analysisUsage); 1203 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet()); 1204 } 1205 1206 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P, 1207 const AnalysisUsage::VectorType &Set) const { 1208 assert(PassDebugging >= Details); 1209 if (Set.empty()) 1210 return; 1211 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:"; 1212 for (unsigned i = 0; i != Set.size(); ++i) { 1213 if (i) dbgs() << ','; 1214 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]); 1215 if (!PInf) { 1216 // Some preserved passes, such as AliasAnalysis, may not be initialized by 1217 // all drivers. 1218 dbgs() << " Uninitialized Pass"; 1219 continue; 1220 } 1221 dbgs() << ' ' << PInf->getPassName(); 1222 } 1223 dbgs() << '\n'; 1224 } 1225 1226 /// Add RequiredPass into list of lower level passes required by pass P. 1227 /// RequiredPass is run on the fly by Pass Manager when P requests it 1228 /// through getAnalysis interface. 1229 /// This should be handled by specific pass manager. 1230 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) { 1231 if (TPM) { 1232 TPM->dumpArguments(); 1233 TPM->dumpPasses(); 1234 } 1235 1236 // Module Level pass may required Function Level analysis info 1237 // (e.g. dominator info). Pass manager uses on the fly function pass manager 1238 // to provide this on demand. In that case, in Pass manager terminology, 1239 // module level pass is requiring lower level analysis info managed by 1240 // lower level pass manager. 1241 1242 // When Pass manager is not able to order required analysis info, Pass manager 1243 // checks whether any lower level manager will be able to provide this 1244 // analysis info on demand or not. 1245 #ifndef NDEBUG 1246 dbgs() << "Unable to schedule '" << RequiredPass->getPassName(); 1247 dbgs() << "' required by '" << P->getPassName() << "'\n"; 1248 #endif 1249 llvm_unreachable("Unable to schedule pass"); 1250 } 1251 1252 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) { 1253 llvm_unreachable("Unable to find on the fly pass"); 1254 } 1255 1256 // Destructor 1257 PMDataManager::~PMDataManager() { 1258 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(), 1259 E = PassVector.end(); I != E; ++I) 1260 delete *I; 1261 } 1262 1263 //===----------------------------------------------------------------------===// 1264 // NOTE: Is this the right place to define this method ? 1265 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist. 1266 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const { 1267 return PM.findAnalysisPass(ID, dir); 1268 } 1269 1270 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI, 1271 Function &F) { 1272 return PM.getOnTheFlyPass(P, AnalysisPI, F); 1273 } 1274 1275 //===----------------------------------------------------------------------===// 1276 // BBPassManager implementation 1277 1278 /// Execute all of the passes scheduled for execution by invoking 1279 /// runOnBasicBlock method. Keep track of whether any of the passes modifies 1280 /// the function, and if so, return true. 1281 bool BBPassManager::runOnFunction(Function &F) { 1282 if (F.isDeclaration()) 1283 return false; 1284 1285 bool Changed = doInitialization(F); 1286 1287 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) 1288 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 1289 BasicBlockPass *BP = getContainedPass(Index); 1290 bool LocalChanged = false; 1291 1292 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName()); 1293 dumpRequiredSet(BP); 1294 1295 initializeAnalysisImpl(BP); 1296 1297 { 1298 // If the pass crashes, remember this. 1299 PassManagerPrettyStackEntry X(BP, *I); 1300 TimeRegion PassTimer(getPassTimer(BP)); 1301 1302 LocalChanged |= BP->runOnBasicBlock(*I); 1303 } 1304 1305 Changed |= LocalChanged; 1306 if (LocalChanged) 1307 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG, 1308 I->getName()); 1309 dumpPreservedSet(BP); 1310 dumpUsedSet(BP); 1311 1312 verifyPreservedAnalysis(BP); 1313 removeNotPreservedAnalysis(BP); 1314 recordAvailableAnalysis(BP); 1315 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG); 1316 } 1317 1318 return doFinalization(F) || Changed; 1319 } 1320 1321 // Implement doInitialization and doFinalization 1322 bool BBPassManager::doInitialization(Module &M) { 1323 bool Changed = false; 1324 1325 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) 1326 Changed |= getContainedPass(Index)->doInitialization(M); 1327 1328 return Changed; 1329 } 1330 1331 bool BBPassManager::doFinalization(Module &M) { 1332 bool Changed = false; 1333 1334 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index) 1335 Changed |= getContainedPass(Index)->doFinalization(M); 1336 1337 return Changed; 1338 } 1339 1340 bool BBPassManager::doInitialization(Function &F) { 1341 bool Changed = false; 1342 1343 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 1344 BasicBlockPass *BP = getContainedPass(Index); 1345 Changed |= BP->doInitialization(F); 1346 } 1347 1348 return Changed; 1349 } 1350 1351 bool BBPassManager::doFinalization(Function &F) { 1352 bool Changed = false; 1353 1354 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 1355 BasicBlockPass *BP = getContainedPass(Index); 1356 Changed |= BP->doFinalization(F); 1357 } 1358 1359 return Changed; 1360 } 1361 1362 1363 //===----------------------------------------------------------------------===// 1364 // FunctionPassManager implementation 1365 1366 /// Create new Function pass manager 1367 FunctionPassManager::FunctionPassManager(Module *m) : M(m) { 1368 FPM = new FunctionPassManagerImpl(); 1369 // FPM is the top level manager. 1370 FPM->setTopLevelManager(FPM); 1371 1372 AnalysisResolver *AR = new AnalysisResolver(*FPM); 1373 FPM->setResolver(AR); 1374 } 1375 1376 FunctionPassManager::~FunctionPassManager() { 1377 delete FPM; 1378 } 1379 1380 void FunctionPassManager::add(Pass *P) { 1381 FPM->add(P); 1382 } 1383 1384 /// run - Execute all of the passes scheduled for execution. Keep 1385 /// track of whether any of the passes modifies the function, and if 1386 /// so, return true. 1387 /// 1388 bool FunctionPassManager::run(Function &F) { 1389 handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) { 1390 report_fatal_error("Error reading bitcode file: " + EIB.message()); 1391 }); 1392 return FPM->run(F); 1393 } 1394 1395 1396 /// doInitialization - Run all of the initializers for the function passes. 1397 /// 1398 bool FunctionPassManager::doInitialization() { 1399 return FPM->doInitialization(*M); 1400 } 1401 1402 /// doFinalization - Run all of the finalizers for the function passes. 1403 /// 1404 bool FunctionPassManager::doFinalization() { 1405 return FPM->doFinalization(*M); 1406 } 1407 1408 //===----------------------------------------------------------------------===// 1409 // FunctionPassManagerImpl implementation 1410 // 1411 bool FunctionPassManagerImpl::doInitialization(Module &M) { 1412 bool Changed = false; 1413 1414 dumpArguments(); 1415 dumpPasses(); 1416 1417 for (ImmutablePass *ImPass : getImmutablePasses()) 1418 Changed |= ImPass->doInitialization(M); 1419 1420 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) 1421 Changed |= getContainedManager(Index)->doInitialization(M); 1422 1423 return Changed; 1424 } 1425 1426 bool FunctionPassManagerImpl::doFinalization(Module &M) { 1427 bool Changed = false; 1428 1429 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index) 1430 Changed |= getContainedManager(Index)->doFinalization(M); 1431 1432 for (ImmutablePass *ImPass : getImmutablePasses()) 1433 Changed |= ImPass->doFinalization(M); 1434 1435 return Changed; 1436 } 1437 1438 /// cleanup - After running all passes, clean up pass manager cache. 1439 void FPPassManager::cleanup() { 1440 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 1441 FunctionPass *FP = getContainedPass(Index); 1442 AnalysisResolver *AR = FP->getResolver(); 1443 assert(AR && "Analysis Resolver is not set"); 1444 AR->clearAnalysisImpls(); 1445 } 1446 } 1447 1448 void FunctionPassManagerImpl::releaseMemoryOnTheFly() { 1449 if (!wasRun) 1450 return; 1451 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) { 1452 FPPassManager *FPPM = getContainedManager(Index); 1453 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) { 1454 FPPM->getContainedPass(Index)->releaseMemory(); 1455 } 1456 } 1457 wasRun = false; 1458 } 1459 1460 // Execute all the passes managed by this top level manager. 1461 // Return true if any function is modified by a pass. 1462 bool FunctionPassManagerImpl::run(Function &F) { 1463 bool Changed = false; 1464 TimingInfo::createTheTimeInfo(); 1465 1466 initializeAllAnalysisInfo(); 1467 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) { 1468 Changed |= getContainedManager(Index)->runOnFunction(F); 1469 F.getContext().yield(); 1470 } 1471 1472 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) 1473 getContainedManager(Index)->cleanup(); 1474 1475 wasRun = true; 1476 return Changed; 1477 } 1478 1479 //===----------------------------------------------------------------------===// 1480 // FPPassManager implementation 1481 1482 char FPPassManager::ID = 0; 1483 /// Print passes managed by this manager 1484 void FPPassManager::dumpPassStructure(unsigned Offset) { 1485 dbgs().indent(Offset*2) << "FunctionPass Manager\n"; 1486 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 1487 FunctionPass *FP = getContainedPass(Index); 1488 FP->dumpPassStructure(Offset + 1); 1489 dumpLastUses(FP, Offset+1); 1490 } 1491 } 1492 1493 1494 /// Execute all of the passes scheduled for execution by invoking 1495 /// runOnFunction method. Keep track of whether any of the passes modifies 1496 /// the function, and if so, return true. 1497 bool FPPassManager::runOnFunction(Function &F) { 1498 if (F.isDeclaration()) 1499 return false; 1500 1501 bool Changed = false; 1502 1503 // Collect inherited analysis from Module level pass manager. 1504 populateInheritedAnalysis(TPM->activeStack); 1505 1506 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 1507 FunctionPass *FP = getContainedPass(Index); 1508 bool LocalChanged = false; 1509 1510 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName()); 1511 dumpRequiredSet(FP); 1512 1513 initializeAnalysisImpl(FP); 1514 1515 { 1516 PassManagerPrettyStackEntry X(FP, F); 1517 TimeRegion PassTimer(getPassTimer(FP)); 1518 1519 LocalChanged |= FP->runOnFunction(F); 1520 } 1521 1522 Changed |= LocalChanged; 1523 if (LocalChanged) 1524 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName()); 1525 dumpPreservedSet(FP); 1526 dumpUsedSet(FP); 1527 1528 verifyPreservedAnalysis(FP); 1529 removeNotPreservedAnalysis(FP); 1530 recordAvailableAnalysis(FP); 1531 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG); 1532 } 1533 return Changed; 1534 } 1535 1536 bool FPPassManager::runOnModule(Module &M) { 1537 bool Changed = false; 1538 1539 for (Function &F : M) 1540 Changed |= runOnFunction(F); 1541 1542 return Changed; 1543 } 1544 1545 bool FPPassManager::doInitialization(Module &M) { 1546 bool Changed = false; 1547 1548 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) 1549 Changed |= getContainedPass(Index)->doInitialization(M); 1550 1551 return Changed; 1552 } 1553 1554 bool FPPassManager::doFinalization(Module &M) { 1555 bool Changed = false; 1556 1557 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index) 1558 Changed |= getContainedPass(Index)->doFinalization(M); 1559 1560 return Changed; 1561 } 1562 1563 //===----------------------------------------------------------------------===// 1564 // MPPassManager implementation 1565 1566 /// Execute all of the passes scheduled for execution by invoking 1567 /// runOnModule method. Keep track of whether any of the passes modifies 1568 /// the module, and if so, return true. 1569 bool 1570 MPPassManager::runOnModule(Module &M) { 1571 bool Changed = false; 1572 1573 // Initialize on-the-fly passes 1574 for (auto &OnTheFlyManager : OnTheFlyManagers) { 1575 FunctionPassManagerImpl *FPP = OnTheFlyManager.second; 1576 Changed |= FPP->doInitialization(M); 1577 } 1578 1579 // Initialize module passes 1580 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) 1581 Changed |= getContainedPass(Index)->doInitialization(M); 1582 1583 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { 1584 ModulePass *MP = getContainedPass(Index); 1585 bool LocalChanged = false; 1586 1587 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier()); 1588 dumpRequiredSet(MP); 1589 1590 initializeAnalysisImpl(MP); 1591 1592 { 1593 PassManagerPrettyStackEntry X(MP, M); 1594 TimeRegion PassTimer(getPassTimer(MP)); 1595 1596 LocalChanged |= MP->runOnModule(M); 1597 } 1598 1599 Changed |= LocalChanged; 1600 if (LocalChanged) 1601 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG, 1602 M.getModuleIdentifier()); 1603 dumpPreservedSet(MP); 1604 dumpUsedSet(MP); 1605 1606 verifyPreservedAnalysis(MP); 1607 removeNotPreservedAnalysis(MP); 1608 recordAvailableAnalysis(MP); 1609 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG); 1610 } 1611 1612 // Finalize module passes 1613 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index) 1614 Changed |= getContainedPass(Index)->doFinalization(M); 1615 1616 // Finalize on-the-fly passes 1617 for (auto &OnTheFlyManager : OnTheFlyManagers) { 1618 FunctionPassManagerImpl *FPP = OnTheFlyManager.second; 1619 // We don't know when is the last time an on-the-fly pass is run, 1620 // so we need to releaseMemory / finalize here 1621 FPP->releaseMemoryOnTheFly(); 1622 Changed |= FPP->doFinalization(M); 1623 } 1624 1625 return Changed; 1626 } 1627 1628 /// Add RequiredPass into list of lower level passes required by pass P. 1629 /// RequiredPass is run on the fly by Pass Manager when P requests it 1630 /// through getAnalysis interface. 1631 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) { 1632 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager && 1633 "Unable to handle Pass that requires lower level Analysis pass"); 1634 assert((P->getPotentialPassManagerType() < 1635 RequiredPass->getPotentialPassManagerType()) && 1636 "Unable to handle Pass that requires lower level Analysis pass"); 1637 if (!RequiredPass) 1638 return; 1639 1640 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P]; 1641 if (!FPP) { 1642 FPP = new FunctionPassManagerImpl(); 1643 // FPP is the top level manager. 1644 FPP->setTopLevelManager(FPP); 1645 1646 OnTheFlyManagers[P] = FPP; 1647 } 1648 const PassInfo *RequiredPassPI = 1649 TPM->findAnalysisPassInfo(RequiredPass->getPassID()); 1650 1651 Pass *FoundPass = nullptr; 1652 if (RequiredPassPI && RequiredPassPI->isAnalysis()) { 1653 FoundPass = 1654 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID()); 1655 } 1656 if (!FoundPass) { 1657 FoundPass = RequiredPass; 1658 // This should be guaranteed to add RequiredPass to the passmanager given 1659 // that we checked for an available analysis above. 1660 FPP->add(RequiredPass); 1661 } 1662 // Register P as the last user of FoundPass or RequiredPass. 1663 SmallVector<Pass *, 1> LU; 1664 LU.push_back(FoundPass); 1665 FPP->setLastUser(LU, P); 1666 } 1667 1668 /// Return function pass corresponding to PassInfo PI, that is 1669 /// required by module pass MP. Instantiate analysis pass, by using 1670 /// its runOnFunction() for function F. 1671 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){ 1672 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP]; 1673 assert(FPP && "Unable to find on the fly pass"); 1674 1675 FPP->releaseMemoryOnTheFly(); 1676 FPP->run(F); 1677 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI); 1678 } 1679 1680 1681 //===----------------------------------------------------------------------===// 1682 // PassManagerImpl implementation 1683 1684 // 1685 /// run - Execute all of the passes scheduled for execution. Keep track of 1686 /// whether any of the passes modifies the module, and if so, return true. 1687 bool PassManagerImpl::run(Module &M) { 1688 bool Changed = false; 1689 TimingInfo::createTheTimeInfo(); 1690 1691 dumpArguments(); 1692 dumpPasses(); 1693 1694 for (ImmutablePass *ImPass : getImmutablePasses()) 1695 Changed |= ImPass->doInitialization(M); 1696 1697 initializeAllAnalysisInfo(); 1698 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) { 1699 Changed |= getContainedManager(Index)->runOnModule(M); 1700 M.getContext().yield(); 1701 } 1702 1703 for (ImmutablePass *ImPass : getImmutablePasses()) 1704 Changed |= ImPass->doFinalization(M); 1705 1706 return Changed; 1707 } 1708 1709 //===----------------------------------------------------------------------===// 1710 // PassManager implementation 1711 1712 /// Create new pass manager 1713 PassManager::PassManager() { 1714 PM = new PassManagerImpl(); 1715 // PM is the top level manager 1716 PM->setTopLevelManager(PM); 1717 } 1718 1719 PassManager::~PassManager() { 1720 delete PM; 1721 } 1722 1723 void PassManager::add(Pass *P) { 1724 PM->add(P); 1725 } 1726 1727 /// run - Execute all of the passes scheduled for execution. Keep track of 1728 /// whether any of the passes modifies the module, and if so, return true. 1729 bool PassManager::run(Module &M) { 1730 return PM->run(M); 1731 } 1732 1733 //===----------------------------------------------------------------------===// 1734 // TimingInfo implementation 1735 1736 bool llvm::TimePassesIsEnabled = false; 1737 static cl::opt<bool,true> 1738 EnableTiming("time-passes", cl::location(TimePassesIsEnabled), 1739 cl::desc("Time each pass, printing elapsed time for each on exit")); 1740 1741 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to 1742 // a non-null value (if the -time-passes option is enabled) or it leaves it 1743 // null. It may be called multiple times. 1744 void TimingInfo::createTheTimeInfo() { 1745 if (!TimePassesIsEnabled || TheTimeInfo) return; 1746 1747 // Constructed the first time this is called, iff -time-passes is enabled. 1748 // This guarantees that the object will be constructed before static globals, 1749 // thus it will be destroyed before them. 1750 static ManagedStatic<TimingInfo> TTI; 1751 TheTimeInfo = &*TTI; 1752 } 1753 1754 /// If TimingInfo is enabled then start pass timer. 1755 Timer *llvm::getPassTimer(Pass *P) { 1756 if (TheTimeInfo) 1757 return TheTimeInfo->getPassTimer(P); 1758 return nullptr; 1759 } 1760 1761 /// If timing is enabled, report the times collected up to now and then reset 1762 /// them. 1763 void llvm::reportAndResetTimings() { 1764 if (TheTimeInfo) 1765 TheTimeInfo->print(); 1766 } 1767 1768 //===----------------------------------------------------------------------===// 1769 // PMStack implementation 1770 // 1771 1772 // Pop Pass Manager from the stack and clear its analysis info. 1773 void PMStack::pop() { 1774 1775 PMDataManager *Top = this->top(); 1776 Top->initializeAnalysisInfo(); 1777 1778 S.pop_back(); 1779 } 1780 1781 // Push PM on the stack and set its top level manager. 1782 void PMStack::push(PMDataManager *PM) { 1783 assert(PM && "Unable to push. Pass Manager expected"); 1784 assert(PM->getDepth()==0 && "Pass Manager depth set too early"); 1785 1786 if (!this->empty()) { 1787 assert(PM->getPassManagerType() > this->top()->getPassManagerType() 1788 && "pushing bad pass manager to PMStack"); 1789 PMTopLevelManager *TPM = this->top()->getTopLevelManager(); 1790 1791 assert(TPM && "Unable to find top level manager"); 1792 TPM->addIndirectPassManager(PM); 1793 PM->setTopLevelManager(TPM); 1794 PM->setDepth(this->top()->getDepth()+1); 1795 } else { 1796 assert((PM->getPassManagerType() == PMT_ModulePassManager 1797 || PM->getPassManagerType() == PMT_FunctionPassManager) 1798 && "pushing bad pass manager to PMStack"); 1799 PM->setDepth(1); 1800 } 1801 1802 S.push_back(PM); 1803 } 1804 1805 // Dump content of the pass manager stack. 1806 LLVM_DUMP_METHOD void PMStack::dump() const { 1807 for (PMDataManager *Manager : S) 1808 dbgs() << Manager->getAsPass()->getPassName() << ' '; 1809 1810 if (!S.empty()) 1811 dbgs() << '\n'; 1812 } 1813 1814 /// Find appropriate Module Pass Manager in the PM Stack and 1815 /// add self into that manager. 1816 void ModulePass::assignPassManager(PMStack &PMS, 1817 PassManagerType PreferredType) { 1818 // Find Module Pass Manager 1819 while (!PMS.empty()) { 1820 PassManagerType TopPMType = PMS.top()->getPassManagerType(); 1821 if (TopPMType == PreferredType) 1822 break; // We found desired pass manager 1823 else if (TopPMType > PMT_ModulePassManager) 1824 PMS.pop(); // Pop children pass managers 1825 else 1826 break; 1827 } 1828 assert(!PMS.empty() && "Unable to find appropriate Pass Manager"); 1829 PMS.top()->add(this); 1830 } 1831 1832 /// Find appropriate Function Pass Manager or Call Graph Pass Manager 1833 /// in the PM Stack and add self into that manager. 1834 void FunctionPass::assignPassManager(PMStack &PMS, 1835 PassManagerType PreferredType) { 1836 1837 // Find Function Pass Manager 1838 while (!PMS.empty()) { 1839 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager) 1840 PMS.pop(); 1841 else 1842 break; 1843 } 1844 1845 // Create new Function Pass Manager if needed. 1846 FPPassManager *FPP; 1847 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) { 1848 FPP = (FPPassManager *)PMS.top(); 1849 } else { 1850 assert(!PMS.empty() && "Unable to create Function Pass Manager"); 1851 PMDataManager *PMD = PMS.top(); 1852 1853 // [1] Create new Function Pass Manager 1854 FPP = new FPPassManager(); 1855 FPP->populateInheritedAnalysis(PMS); 1856 1857 // [2] Set up new manager's top level manager 1858 PMTopLevelManager *TPM = PMD->getTopLevelManager(); 1859 TPM->addIndirectPassManager(FPP); 1860 1861 // [3] Assign manager to manage this new manager. This may create 1862 // and push new managers into PMS 1863 FPP->assignPassManager(PMS, PMD->getPassManagerType()); 1864 1865 // [4] Push new manager into PMS 1866 PMS.push(FPP); 1867 } 1868 1869 // Assign FPP as the manager of this pass. 1870 FPP->add(this); 1871 } 1872 1873 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager 1874 /// in the PM Stack and add self into that manager. 1875 void BasicBlockPass::assignPassManager(PMStack &PMS, 1876 PassManagerType PreferredType) { 1877 BBPassManager *BBP; 1878 1879 // Basic Pass Manager is a leaf pass manager. It does not handle 1880 // any other pass manager. 1881 if (!PMS.empty() && 1882 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) { 1883 BBP = (BBPassManager *)PMS.top(); 1884 } else { 1885 // If leaf manager is not Basic Block Pass manager then create new 1886 // basic Block Pass manager. 1887 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager"); 1888 PMDataManager *PMD = PMS.top(); 1889 1890 // [1] Create new Basic Block Manager 1891 BBP = new BBPassManager(); 1892 1893 // [2] Set up new manager's top level manager 1894 // Basic Block Pass Manager does not live by itself 1895 PMTopLevelManager *TPM = PMD->getTopLevelManager(); 1896 TPM->addIndirectPassManager(BBP); 1897 1898 // [3] Assign manager to manage this new manager. This may create 1899 // and push new managers into PMS 1900 BBP->assignPassManager(PMS, PreferredType); 1901 1902 // [4] Push new manager into PMS 1903 PMS.push(BBP); 1904 } 1905 1906 // Assign BBP as the manager of this pass. 1907 BBP->add(this); 1908 } 1909 1910 PassManagerBase::~PassManagerBase() {} 1911