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