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