Fix comment for consistency sake.
[llvm/avr.git] / lib / VMCore / PassManager.cpp
blob375151f49ffd30acfd4fb583932eddf787fb7dd5
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.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/PassManagers.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/System/Mutex.h"
24 #include "llvm/System/Threading.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm-c/Core.h"
27 #include <algorithm>
28 #include <cstdio>
29 #include <map>
30 using namespace llvm;
32 // See PassManagers.h for Pass Manager infrastructure overview.
34 namespace llvm {
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.
43 // Different debug levels that can be enabled...
44 enum PassDebugLevel {
45 None, Arguments, Structure, Executions, Details
48 // Always verify dominfo if expensive checking is enabled.
49 #ifdef XDEBUG
50 bool VerifyDomInfo = true;
51 #else
52 bool VerifyDomInfo = false;
53 #endif
54 static cl::opt<bool,true>
55 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
56 cl::desc("Verify dominator info (time consuming)"));
58 static cl::opt<enum PassDebugLevel>
59 PassDebugging("debug-pass", cl::Hidden,
60 cl::desc("Print PassManager debugging information"),
61 cl::values(
62 clEnumVal(None , "disable debug output"),
63 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
64 clEnumVal(Structure , "print pass structure before run()"),
65 clEnumVal(Executions, "print pass name before it is executed"),
66 clEnumVal(Details , "print pass details when it is executed"),
67 clEnumValEnd));
68 } // End of llvm namespace
70 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
71 if (V == 0 && M == 0)
72 OS << "Releasing pass '";
73 else
74 OS << "Running pass '";
76 OS << P->getPassName() << "'";
78 if (M) {
79 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
80 return;
82 if (V == 0) {
83 OS << '\n';
84 return;
87 OS << " on ";
88 if (isa<Function>(V))
89 OS << "function";
90 else if (isa<BasicBlock>(V))
91 OS << "basic block";
92 else
93 OS << "value";
95 OS << " '";
96 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
97 OS << "'\n";
101 namespace {
103 //===----------------------------------------------------------------------===//
104 // BBPassManager
106 /// BBPassManager manages BasicBlockPass. It batches all the
107 /// pass together and sequence them to process one basic block before
108 /// processing next basic block.
109 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
110 public FunctionPass {
112 public:
113 static char ID;
114 explicit BBPassManager(int Depth)
115 : PMDataManager(Depth), FunctionPass(&ID) {}
117 /// Execute all of the passes scheduled for execution. Keep track of
118 /// whether any of the passes modifies the function, and if so, return true.
119 bool runOnFunction(Function &F);
121 /// Pass Manager itself does not invalidate any analysis info.
122 void getAnalysisUsage(AnalysisUsage &Info) const {
123 Info.setPreservesAll();
126 bool doInitialization(Module &M);
127 bool doInitialization(Function &F);
128 bool doFinalization(Module &M);
129 bool doFinalization(Function &F);
131 virtual const char *getPassName() const {
132 return "BasicBlock Pass Manager";
135 // Print passes managed by this manager
136 void dumpPassStructure(unsigned Offset) {
137 llvm::errs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
138 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
139 BasicBlockPass *BP = getContainedPass(Index);
140 BP->dumpPassStructure(Offset + 1);
141 dumpLastUses(BP, Offset+1);
145 BasicBlockPass *getContainedPass(unsigned N) {
146 assert(N < PassVector.size() && "Pass number out of range!");
147 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
148 return BP;
151 virtual PassManagerType getPassManagerType() const {
152 return PMT_BasicBlockPassManager;
156 char BBPassManager::ID = 0;
159 namespace llvm {
161 //===----------------------------------------------------------------------===//
162 // FunctionPassManagerImpl
164 /// FunctionPassManagerImpl manages FPPassManagers
165 class FunctionPassManagerImpl : public Pass,
166 public PMDataManager,
167 public PMTopLevelManager {
168 private:
169 bool wasRun;
170 public:
171 static char ID;
172 explicit FunctionPassManagerImpl(int Depth) :
173 Pass(&ID), PMDataManager(Depth),
174 PMTopLevelManager(TLM_Function), wasRun(false) { }
176 /// add - Add a pass to the queue of passes to run. This passes ownership of
177 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
178 /// will be destroyed as well, so there is no need to delete the pass. This
179 /// implies that all passes MUST be allocated with 'new'.
180 void add(Pass *P) {
181 schedulePass(P);
184 // Prepare for running an on the fly pass, freeing memory if needed
185 // from a previous run.
186 void releaseMemoryOnTheFly();
188 /// run - Execute all of the passes scheduled for execution. Keep track of
189 /// whether any of the passes modifies the module, and if so, return true.
190 bool run(Function &F);
192 /// doInitialization - Run all of the initializers for the function passes.
194 bool doInitialization(Module &M);
196 /// doFinalization - Run all of the finalizers for the function passes.
198 bool doFinalization(Module &M);
200 /// Pass Manager itself does not invalidate any analysis info.
201 void getAnalysisUsage(AnalysisUsage &Info) const {
202 Info.setPreservesAll();
205 inline void addTopLevelPass(Pass *P) {
207 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
209 // P is a immutable pass and it will be managed by this
210 // top level manager. Set up analysis resolver to connect them.
211 AnalysisResolver *AR = new AnalysisResolver(*this);
212 P->setResolver(AR);
213 initializeAnalysisImpl(P);
214 addImmutablePass(IP);
215 recordAvailableAnalysis(IP);
216 } else {
217 P->assignPassManager(activeStack);
222 FPPassManager *getContainedManager(unsigned N) {
223 assert(N < PassManagers.size() && "Pass number out of range!");
224 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
225 return FP;
229 char FunctionPassManagerImpl::ID = 0;
230 //===----------------------------------------------------------------------===//
231 // MPPassManager
233 /// MPPassManager manages ModulePasses and function pass managers.
234 /// It batches all Module passes and function pass managers together and
235 /// sequences them to process one module.
236 class MPPassManager : public Pass, public PMDataManager {
237 public:
238 static char ID;
239 explicit MPPassManager(int Depth) :
240 Pass(&ID), PMDataManager(Depth) { }
242 // Delete on the fly managers.
243 virtual ~MPPassManager() {
244 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
245 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
246 I != E; ++I) {
247 FunctionPassManagerImpl *FPP = I->second;
248 delete FPP;
252 /// run - Execute all of the passes scheduled for execution. Keep track of
253 /// whether any of the passes modifies the module, and if so, return true.
254 bool runOnModule(Module &M);
256 /// Pass Manager itself does not invalidate any analysis info.
257 void getAnalysisUsage(AnalysisUsage &Info) const {
258 Info.setPreservesAll();
261 /// Add RequiredPass into list of lower level passes required by pass P.
262 /// RequiredPass is run on the fly by Pass Manager when P requests it
263 /// through getAnalysis interface.
264 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
266 /// Return function pass corresponding to PassInfo PI, that is
267 /// required by module pass MP. Instantiate analysis pass, by using
268 /// its runOnFunction() for function F.
269 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
271 virtual const char *getPassName() const {
272 return "Module Pass Manager";
275 // Print passes managed by this manager
276 void dumpPassStructure(unsigned Offset) {
277 llvm::errs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
278 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
279 ModulePass *MP = getContainedPass(Index);
280 MP->dumpPassStructure(Offset + 1);
281 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
282 OnTheFlyManagers.find(MP);
283 if (I != OnTheFlyManagers.end())
284 I->second->dumpPassStructure(Offset + 2);
285 dumpLastUses(MP, Offset+1);
289 ModulePass *getContainedPass(unsigned N) {
290 assert(N < PassVector.size() && "Pass number out of range!");
291 return static_cast<ModulePass *>(PassVector[N]);
294 virtual PassManagerType getPassManagerType() const {
295 return PMT_ModulePassManager;
298 private:
299 /// Collection of on the fly FPPassManagers. These managers manage
300 /// function passes that are required by module passes.
301 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
304 char MPPassManager::ID = 0;
305 //===----------------------------------------------------------------------===//
306 // PassManagerImpl
309 /// PassManagerImpl manages MPPassManagers
310 class PassManagerImpl : public Pass,
311 public PMDataManager,
312 public PMTopLevelManager {
314 public:
315 static char ID;
316 explicit PassManagerImpl(int Depth) :
317 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
319 /// add - Add a pass to the queue of passes to run. This passes ownership of
320 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
321 /// will be destroyed as well, so there is no need to delete the pass. This
322 /// implies that all passes MUST be allocated with 'new'.
323 void add(Pass *P) {
324 schedulePass(P);
327 /// run - Execute all of the passes scheduled for execution. Keep track of
328 /// whether any of the passes modifies the module, and if so, return true.
329 bool run(Module &M);
331 /// Pass Manager itself does not invalidate any analysis info.
332 void getAnalysisUsage(AnalysisUsage &Info) const {
333 Info.setPreservesAll();
336 inline void addTopLevelPass(Pass *P) {
337 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
339 // P is a immutable pass and it will be managed by this
340 // top level manager. Set up analysis resolver to connect them.
341 AnalysisResolver *AR = new AnalysisResolver(*this);
342 P->setResolver(AR);
343 initializeAnalysisImpl(P);
344 addImmutablePass(IP);
345 recordAvailableAnalysis(IP);
346 } else {
347 P->assignPassManager(activeStack);
351 MPPassManager *getContainedManager(unsigned N) {
352 assert(N < PassManagers.size() && "Pass number out of range!");
353 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
354 return MP;
358 char PassManagerImpl::ID = 0;
359 } // End of llvm namespace
361 namespace {
363 //===----------------------------------------------------------------------===//
364 /// TimingInfo Class - This class is used to calculate information about the
365 /// amount of time each pass takes to execute. This only happens when
366 /// -time-passes is enabled on the command line.
369 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
371 class VISIBILITY_HIDDEN TimingInfo {
372 std::map<Pass*, Timer> TimingData;
373 TimerGroup TG;
375 public:
376 // Use 'create' member to get this.
377 TimingInfo() : TG("... Pass execution timing report ...") {}
379 // TimingDtor - Print out information about timing information
380 ~TimingInfo() {
381 // Delete all of the timers...
382 TimingData.clear();
383 // TimerGroup is deleted next, printing the report.
386 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
387 // to a non null value (if the -time-passes option is enabled) or it leaves it
388 // null. It may be called multiple times.
389 static void createTheTimeInfo();
391 void passStarted(Pass *P) {
392 if (dynamic_cast<PMDataManager *>(P))
393 return;
395 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
396 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
397 if (I == TimingData.end())
398 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
399 I->second.startTimer();
402 void passEnded(Pass *P) {
403 if (dynamic_cast<PMDataManager *>(P))
404 return;
406 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
407 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
408 assert(I != TimingData.end() && "passStarted/passEnded not nested right!");
409 I->second.stopTimer();
413 } // End of anon namespace
415 static TimingInfo *TheTimeInfo;
417 //===----------------------------------------------------------------------===//
418 // PMTopLevelManager implementation
420 /// Initialize top level manager. Create first pass manager.
421 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
422 if (t == TLM_Pass) {
423 MPPassManager *MPP = new MPPassManager(1);
424 MPP->setTopLevelManager(this);
425 addPassManager(MPP);
426 activeStack.push(MPP);
427 } else if (t == TLM_Function) {
428 FPPassManager *FPP = new FPPassManager(1);
429 FPP->setTopLevelManager(this);
430 addPassManager(FPP);
431 activeStack.push(FPP);
435 /// Set pass P as the last user of the given analysis passes.
436 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
437 Pass *P) {
438 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
439 E = AnalysisPasses.end(); I != E; ++I) {
440 Pass *AP = *I;
441 LastUser[AP] = P;
443 if (P == AP)
444 continue;
446 // If AP is the last user of other passes then make P last user of
447 // such passes.
448 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
449 LUE = LastUser.end(); LUI != LUE; ++LUI) {
450 if (LUI->second == AP)
451 // DenseMap iterator is not invalidated here because
452 // this is just updating exisitng entry.
453 LastUser[LUI->first] = P;
458 /// Collect passes whose last user is P
459 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
460 Pass *P) {
461 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
462 InversedLastUser.find(P);
463 if (DMI == InversedLastUser.end())
464 return;
466 SmallPtrSet<Pass *, 8> &LU = DMI->second;
467 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
468 E = LU.end(); I != E; ++I) {
469 LastUses.push_back(*I);
474 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
475 AnalysisUsage *AnUsage = NULL;
476 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
477 if (DMI != AnUsageMap.end())
478 AnUsage = DMI->second;
479 else {
480 AnUsage = new AnalysisUsage();
481 P->getAnalysisUsage(*AnUsage);
482 AnUsageMap[P] = AnUsage;
484 return AnUsage;
487 /// Schedule pass P for execution. Make sure that passes required by
488 /// P are run before P is run. Update analysis info maintained by
489 /// the manager. Remove dead passes. This is a recursive function.
490 void PMTopLevelManager::schedulePass(Pass *P) {
492 // TODO : Allocate function manager for this pass, other wise required set
493 // may be inserted into previous function manager
495 // Give pass a chance to prepare the stage.
496 P->preparePassManager(activeStack);
498 // If P is an analysis pass and it is available then do not
499 // generate the analysis again. Stale analysis info should not be
500 // available at this point.
501 if (P->getPassInfo() &&
502 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
503 delete P;
504 return;
507 AnalysisUsage *AnUsage = findAnalysisUsage(P);
509 bool checkAnalysis = true;
510 while (checkAnalysis) {
511 checkAnalysis = false;
513 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
514 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
515 E = RequiredSet.end(); I != E; ++I) {
517 Pass *AnalysisPass = findAnalysisPass(*I);
518 if (!AnalysisPass) {
519 AnalysisPass = (*I)->createPass();
520 if (P->getPotentialPassManagerType () ==
521 AnalysisPass->getPotentialPassManagerType())
522 // Schedule analysis pass that is managed by the same pass manager.
523 schedulePass(AnalysisPass);
524 else if (P->getPotentialPassManagerType () >
525 AnalysisPass->getPotentialPassManagerType()) {
526 // Schedule analysis pass that is managed by a new manager.
527 schedulePass(AnalysisPass);
528 // Recheck analysis passes to ensure that required analysises that
529 // are already checked are still available.
530 checkAnalysis = true;
532 else
533 // Do not schedule this analysis. Lower level analsyis
534 // passes are run on the fly.
535 delete AnalysisPass;
540 // Now all required passes are available.
541 addTopLevelPass(P);
544 /// Find the pass that implements Analysis AID. Search immutable
545 /// passes and all pass managers. If desired pass is not found
546 /// then return NULL.
547 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
549 Pass *P = NULL;
550 // Check pass managers
551 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
552 E = PassManagers.end(); P == NULL && I != E; ++I) {
553 PMDataManager *PMD = *I;
554 P = PMD->findAnalysisPass(AID, false);
557 // Check other pass managers
558 for (SmallVector<PMDataManager *, 8>::iterator
559 I = IndirectPassManagers.begin(),
560 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
561 P = (*I)->findAnalysisPass(AID, false);
563 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
564 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
565 const PassInfo *PI = (*I)->getPassInfo();
566 if (PI == AID)
567 P = *I;
569 // If Pass not found then check the interfaces implemented by Immutable Pass
570 if (!P) {
571 const std::vector<const PassInfo*> &ImmPI =
572 PI->getInterfacesImplemented();
573 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
574 P = *I;
578 return P;
581 // Print passes managed by this top level manager.
582 void PMTopLevelManager::dumpPasses() const {
584 if (PassDebugging < Structure)
585 return;
587 // Print out the immutable passes
588 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
589 ImmutablePasses[i]->dumpPassStructure(0);
592 // Every class that derives from PMDataManager also derives from Pass
593 // (sometimes indirectly), but there's no inheritance relationship
594 // between PMDataManager and Pass, so we have to dynamic_cast to get
595 // from a PMDataManager* to a Pass*.
596 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
597 E = PassManagers.end(); I != E; ++I)
598 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
601 void PMTopLevelManager::dumpArguments() const {
603 if (PassDebugging < Arguments)
604 return;
606 errs() << "Pass Arguments: ";
607 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
608 E = PassManagers.end(); I != E; ++I)
609 (*I)->dumpPassArguments();
610 errs() << "\n";
613 void PMTopLevelManager::initializeAllAnalysisInfo() {
614 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
615 E = PassManagers.end(); I != E; ++I)
616 (*I)->initializeAnalysisInfo();
618 // Initailize other pass managers
619 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
620 E = IndirectPassManagers.end(); I != E; ++I)
621 (*I)->initializeAnalysisInfo();
623 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
624 DME = LastUser.end(); DMI != DME; ++DMI) {
625 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
626 InversedLastUser.find(DMI->second);
627 if (InvDMI != InversedLastUser.end()) {
628 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
629 L.insert(DMI->first);
630 } else {
631 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
632 InversedLastUser[DMI->second] = L;
637 /// Destructor
638 PMTopLevelManager::~PMTopLevelManager() {
639 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
640 E = PassManagers.end(); I != E; ++I)
641 delete *I;
643 for (SmallVector<ImmutablePass *, 8>::iterator
644 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
645 delete *I;
647 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
648 DME = AnUsageMap.end(); DMI != DME; ++DMI)
649 delete DMI->second;
652 //===----------------------------------------------------------------------===//
653 // PMDataManager implementation
655 /// Augement AvailableAnalysis by adding analysis made available by pass P.
656 void PMDataManager::recordAvailableAnalysis(Pass *P) {
657 const PassInfo *PI = P->getPassInfo();
658 if (PI == 0) return;
660 AvailableAnalysis[PI] = P;
662 //This pass is the current implementation of all of the interfaces it
663 //implements as well.
664 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
665 for (unsigned i = 0, e = II.size(); i != e; ++i)
666 AvailableAnalysis[II[i]] = P;
669 // Return true if P preserves high level analysis used by other
670 // passes managed by this manager
671 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
672 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
673 if (AnUsage->getPreservesAll())
674 return true;
676 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
677 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
678 E = HigherLevelAnalysis.end(); I != E; ++I) {
679 Pass *P1 = *I;
680 if (!dynamic_cast<ImmutablePass*>(P1) &&
681 std::find(PreservedSet.begin(), PreservedSet.end(),
682 P1->getPassInfo()) ==
683 PreservedSet.end())
684 return false;
687 return true;
690 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
691 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
692 // Don't do this unless assertions are enabled.
693 #ifdef NDEBUG
694 return;
695 #endif
696 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
697 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
699 // Verify preserved analysis
700 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
701 E = PreservedSet.end(); I != E; ++I) {
702 AnalysisID AID = *I;
703 if (Pass *AP = findAnalysisPass(AID, true))
704 AP->verifyAnalysis();
708 /// verifyDomInfo - Verify dominator information if it is available.
709 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
710 if (!VerifyDomInfo || !P.getResolver())
711 return;
713 DominatorTree *DT = P.getAnalysisIfAvailable<DominatorTree>();
714 if (!DT)
715 return;
717 DominatorTree OtherDT;
718 OtherDT.getBase().recalculate(F);
719 if (DT->compare(OtherDT)) {
720 errs() << "Dominator Information for " << F.getName() << "\n";
721 errs() << "Pass '" << P.getPassName() << "'\n";
722 errs() << "----- Valid -----\n";
723 OtherDT.dump();
724 errs() << "----- Invalid -----\n";
725 DT->dump();
726 llvm_unreachable("Invalid dominator info");
729 DominanceFrontier *DF = P.getAnalysisIfAvailable<DominanceFrontier>();
730 if (!DF)
731 return;
733 DominanceFrontier OtherDF;
734 std::vector<BasicBlock*> DTRoots = DT->getRoots();
735 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
736 if (DF->compare(OtherDF)) {
737 errs() << "Dominator Information for " << F.getName() << "\n";
738 errs() << "Pass '" << P.getPassName() << "'\n";
739 errs() << "----- Valid -----\n";
740 OtherDF.dump();
741 errs() << "----- Invalid -----\n";
742 DF->dump();
743 llvm_unreachable("Invalid dominator info");
747 /// Remove Analysis not preserved by Pass P
748 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
749 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
750 if (AnUsage->getPreservesAll())
751 return;
753 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
754 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
755 E = AvailableAnalysis.end(); I != E; ) {
756 std::map<AnalysisID, Pass*>::iterator Info = I++;
757 if (!dynamic_cast<ImmutablePass*>(Info->second)
758 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
759 PreservedSet.end()) {
760 // Remove this analysis
761 if (PassDebugging >= Details) {
762 Pass *S = Info->second;
763 errs() << " -- '" << P->getPassName() << "' is not preserving '";
764 errs() << S->getPassName() << "'\n";
766 AvailableAnalysis.erase(Info);
770 // Check inherited analysis also. If P is not preserving analysis
771 // provided by parent manager then remove it here.
772 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
774 if (!InheritedAnalysis[Index])
775 continue;
777 for (std::map<AnalysisID, Pass*>::iterator
778 I = InheritedAnalysis[Index]->begin(),
779 E = InheritedAnalysis[Index]->end(); I != E; ) {
780 std::map<AnalysisID, Pass *>::iterator Info = I++;
781 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
782 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
783 PreservedSet.end())
784 // Remove this analysis
785 InheritedAnalysis[Index]->erase(Info);
790 /// Remove analysis passes that are not used any longer
791 void PMDataManager::removeDeadPasses(Pass *P, const StringRef &Msg,
792 enum PassDebuggingString DBG_STR) {
794 SmallVector<Pass *, 12> DeadPasses;
796 // If this is a on the fly manager then it does not have TPM.
797 if (!TPM)
798 return;
800 TPM->collectLastUses(DeadPasses, P);
802 if (PassDebugging >= Details && !DeadPasses.empty()) {
803 errs() << " -*- '" << P->getPassName();
804 errs() << "' is the last user of following pass instances.";
805 errs() << " Free these instances\n";
808 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
809 E = DeadPasses.end(); I != E; ++I) {
811 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
814 // If the pass crashes releasing memory, remember this.
815 PassManagerPrettyStackEntry X(*I);
817 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
818 (*I)->releaseMemory();
819 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
821 if (const PassInfo *PI = (*I)->getPassInfo()) {
822 std::map<AnalysisID, Pass*>::iterator Pos =
823 AvailableAnalysis.find(PI);
825 // It is possible that pass is already removed from the AvailableAnalysis
826 if (Pos != AvailableAnalysis.end())
827 AvailableAnalysis.erase(Pos);
829 // Remove all interfaces this pass implements, for which it is also
830 // listed as the available implementation.
831 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
832 for (unsigned i = 0, e = II.size(); i != e; ++i) {
833 Pos = AvailableAnalysis.find(II[i]);
834 if (Pos != AvailableAnalysis.end() && Pos->second == *I)
835 AvailableAnalysis.erase(Pos);
841 /// Add pass P into the PassVector. Update
842 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
843 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
844 // This manager is going to manage pass P. Set up analysis resolver
845 // to connect them.
846 AnalysisResolver *AR = new AnalysisResolver(*this);
847 P->setResolver(AR);
849 // If a FunctionPass F is the last user of ModulePass info M
850 // then the F's manager, not F, records itself as a last user of M.
851 SmallVector<Pass *, 12> TransferLastUses;
853 if (!ProcessAnalysis) {
854 // Add pass
855 PassVector.push_back(P);
856 return;
859 // At the moment, this pass is the last user of all required passes.
860 SmallVector<Pass *, 12> LastUses;
861 SmallVector<Pass *, 8> RequiredPasses;
862 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
864 unsigned PDepth = this->getDepth();
866 collectRequiredAnalysis(RequiredPasses,
867 ReqAnalysisNotAvailable, P);
868 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
869 E = RequiredPasses.end(); I != E; ++I) {
870 Pass *PRequired = *I;
871 unsigned RDepth = 0;
873 assert(PRequired->getResolver() && "Analysis Resolver is not set");
874 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
875 RDepth = DM.getDepth();
877 if (PDepth == RDepth)
878 LastUses.push_back(PRequired);
879 else if (PDepth > RDepth) {
880 // Let the parent claim responsibility of last use
881 TransferLastUses.push_back(PRequired);
882 // Keep track of higher level analysis used by this manager.
883 HigherLevelAnalysis.push_back(PRequired);
884 } else
885 llvm_unreachable("Unable to accomodate Required Pass");
888 // Set P as P's last user until someone starts using P.
889 // However, if P is a Pass Manager then it does not need
890 // to record its last user.
891 if (!dynamic_cast<PMDataManager *>(P))
892 LastUses.push_back(P);
893 TPM->setLastUser(LastUses, P);
895 if (!TransferLastUses.empty()) {
896 Pass *My_PM = dynamic_cast<Pass *>(this);
897 TPM->setLastUser(TransferLastUses, My_PM);
898 TransferLastUses.clear();
901 // Now, take care of required analysises that are not available.
902 for (SmallVector<AnalysisID, 8>::iterator
903 I = ReqAnalysisNotAvailable.begin(),
904 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
905 Pass *AnalysisPass = (*I)->createPass();
906 this->addLowerLevelRequiredPass(P, AnalysisPass);
909 // Take a note of analysis required and made available by this pass.
910 // Remove the analysis not preserved by this pass
911 removeNotPreservedAnalysis(P);
912 recordAvailableAnalysis(P);
914 // Add pass
915 PassVector.push_back(P);
919 /// Populate RP with analysis pass that are required by
920 /// pass P and are available. Populate RP_NotAvail with analysis
921 /// pass that are required by pass P but are not available.
922 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
923 SmallVector<AnalysisID, 8> &RP_NotAvail,
924 Pass *P) {
925 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
926 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
927 for (AnalysisUsage::VectorType::const_iterator
928 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
929 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
930 RP.push_back(AnalysisPass);
931 else
932 RP_NotAvail.push_back(*I);
935 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
936 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
937 E = IDs.end(); I != E; ++I) {
938 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
939 RP.push_back(AnalysisPass);
940 else
941 RP_NotAvail.push_back(*I);
945 // All Required analyses should be available to the pass as it runs! Here
946 // we fill in the AnalysisImpls member of the pass so that it can
947 // successfully use the getAnalysis() method to retrieve the
948 // implementations it needs.
950 void PMDataManager::initializeAnalysisImpl(Pass *P) {
951 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
953 for (AnalysisUsage::VectorType::const_iterator
954 I = AnUsage->getRequiredSet().begin(),
955 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
956 Pass *Impl = findAnalysisPass(*I, true);
957 if (Impl == 0)
958 // This may be analysis pass that is initialized on the fly.
959 // If that is not the case then it will raise an assert when it is used.
960 continue;
961 AnalysisResolver *AR = P->getResolver();
962 assert(AR && "Analysis Resolver is not set");
963 AR->addAnalysisImplsPair(*I, Impl);
967 /// Find the pass that implements Analysis AID. If desired pass is not found
968 /// then return NULL.
969 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
971 // Check if AvailableAnalysis map has one entry.
972 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
974 if (I != AvailableAnalysis.end())
975 return I->second;
977 // Search Parents through TopLevelManager
978 if (SearchParent)
979 return TPM->findAnalysisPass(AID);
981 return NULL;
984 // Print list of passes that are last used by P.
985 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
987 SmallVector<Pass *, 12> LUses;
989 // If this is a on the fly manager then it does not have TPM.
990 if (!TPM)
991 return;
993 TPM->collectLastUses(LUses, P);
995 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
996 E = LUses.end(); I != E; ++I) {
997 llvm::errs() << "--" << std::string(Offset*2, ' ');
998 (*I)->dumpPassStructure(0);
1002 void PMDataManager::dumpPassArguments() const {
1003 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1004 E = PassVector.end(); I != E; ++I) {
1005 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
1006 PMD->dumpPassArguments();
1007 else
1008 if (const PassInfo *PI = (*I)->getPassInfo())
1009 if (!PI->isAnalysisGroup())
1010 errs() << " -" << PI->getPassArgument();
1014 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1015 enum PassDebuggingString S2,
1016 const StringRef &Msg) {
1017 if (PassDebugging < Executions)
1018 return;
1019 errs() << (void*)this << std::string(getDepth()*2+1, ' ');
1020 switch (S1) {
1021 case EXECUTION_MSG:
1022 errs() << "Executing Pass '" << P->getPassName();
1023 break;
1024 case MODIFICATION_MSG:
1025 errs() << "Made Modification '" << P->getPassName();
1026 break;
1027 case FREEING_MSG:
1028 errs() << " Freeing Pass '" << P->getPassName();
1029 break;
1030 default:
1031 break;
1033 switch (S2) {
1034 case ON_BASICBLOCK_MSG:
1035 errs() << "' on BasicBlock '" << Msg << "'...\n";
1036 break;
1037 case ON_FUNCTION_MSG:
1038 errs() << "' on Function '" << Msg << "'...\n";
1039 break;
1040 case ON_MODULE_MSG:
1041 errs() << "' on Module '" << Msg << "'...\n";
1042 break;
1043 case ON_LOOP_MSG:
1044 errs() << "' on Loop " << Msg << "'...\n";
1045 break;
1046 case ON_CG_MSG:
1047 errs() << "' on Call Graph " << Msg << "'...\n";
1048 break;
1049 default:
1050 break;
1054 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1055 if (PassDebugging < Details)
1056 return;
1058 AnalysisUsage analysisUsage;
1059 P->getAnalysisUsage(analysisUsage);
1060 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1063 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1064 if (PassDebugging < Details)
1065 return;
1067 AnalysisUsage analysisUsage;
1068 P->getAnalysisUsage(analysisUsage);
1069 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1072 void PMDataManager::dumpAnalysisUsage(const StringRef &Msg, const Pass *P,
1073 const AnalysisUsage::VectorType &Set) const {
1074 assert(PassDebugging >= Details);
1075 if (Set.empty())
1076 return;
1077 errs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1078 for (unsigned i = 0; i != Set.size(); ++i) {
1079 if (i) errs() << ",";
1080 errs() << " " << Set[i]->getPassName();
1082 errs() << "\n";
1085 /// Add RequiredPass into list of lower level passes required by pass P.
1086 /// RequiredPass is run on the fly by Pass Manager when P requests it
1087 /// through getAnalysis interface.
1088 /// This should be handled by specific pass manager.
1089 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1090 if (TPM) {
1091 TPM->dumpArguments();
1092 TPM->dumpPasses();
1095 // Module Level pass may required Function Level analysis info
1096 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1097 // to provide this on demand. In that case, in Pass manager terminology,
1098 // module level pass is requiring lower level analysis info managed by
1099 // lower level pass manager.
1101 // When Pass manager is not able to order required analysis info, Pass manager
1102 // checks whether any lower level manager will be able to provide this
1103 // analysis info on demand or not.
1104 #ifndef NDEBUG
1105 errs() << "Unable to schedule '" << RequiredPass->getPassName();
1106 errs() << "' required by '" << P->getPassName() << "'\n";
1107 #endif
1108 llvm_unreachable("Unable to schedule pass");
1111 // Destructor
1112 PMDataManager::~PMDataManager() {
1113 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1114 E = PassVector.end(); I != E; ++I)
1115 delete *I;
1118 //===----------------------------------------------------------------------===//
1119 // NOTE: Is this the right place to define this method ?
1120 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1121 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1122 return PM.findAnalysisPass(ID, dir);
1125 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1126 Function &F) {
1127 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1130 //===----------------------------------------------------------------------===//
1131 // BBPassManager implementation
1133 /// Execute all of the passes scheduled for execution by invoking
1134 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1135 /// the function, and if so, return true.
1136 bool BBPassManager::runOnFunction(Function &F) {
1137 if (F.isDeclaration())
1138 return false;
1140 bool Changed = doInitialization(F);
1142 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1143 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1144 BasicBlockPass *BP = getContainedPass(Index);
1146 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1147 dumpRequiredSet(BP);
1149 initializeAnalysisImpl(BP);
1152 // If the pass crashes, remember this.
1153 PassManagerPrettyStackEntry X(BP, *I);
1155 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1156 Changed |= BP->runOnBasicBlock(*I);
1157 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1160 if (Changed)
1161 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1162 I->getName());
1163 dumpPreservedSet(BP);
1165 verifyPreservedAnalysis(BP);
1166 removeNotPreservedAnalysis(BP);
1167 recordAvailableAnalysis(BP);
1168 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1171 return Changed |= doFinalization(F);
1174 // Implement doInitialization and doFinalization
1175 bool BBPassManager::doInitialization(Module &M) {
1176 bool Changed = false;
1178 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1179 Changed |= getContainedPass(Index)->doInitialization(M);
1181 return Changed;
1184 bool BBPassManager::doFinalization(Module &M) {
1185 bool Changed = false;
1187 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1188 Changed |= getContainedPass(Index)->doFinalization(M);
1190 return Changed;
1193 bool BBPassManager::doInitialization(Function &F) {
1194 bool Changed = false;
1196 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1197 BasicBlockPass *BP = getContainedPass(Index);
1198 Changed |= BP->doInitialization(F);
1201 return Changed;
1204 bool BBPassManager::doFinalization(Function &F) {
1205 bool Changed = false;
1207 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1208 BasicBlockPass *BP = getContainedPass(Index);
1209 Changed |= BP->doFinalization(F);
1212 return Changed;
1216 //===----------------------------------------------------------------------===//
1217 // FunctionPassManager implementation
1219 /// Create new Function pass manager
1220 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1221 FPM = new FunctionPassManagerImpl(0);
1222 // FPM is the top level manager.
1223 FPM->setTopLevelManager(FPM);
1225 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1226 FPM->setResolver(AR);
1228 MP = P;
1231 FunctionPassManager::~FunctionPassManager() {
1232 delete FPM;
1235 /// add - Add a pass to the queue of passes to run. This passes
1236 /// ownership of the Pass to the PassManager. When the
1237 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1238 /// there is no need to delete the pass. (TODO delete passes.)
1239 /// This implies that all passes MUST be allocated with 'new'.
1240 void FunctionPassManager::add(Pass *P) {
1241 FPM->add(P);
1244 /// run - Execute all of the passes scheduled for execution. Keep
1245 /// track of whether any of the passes modifies the function, and if
1246 /// so, return true.
1248 bool FunctionPassManager::run(Function &F) {
1249 std::string errstr;
1250 if (MP->materializeFunction(&F, &errstr)) {
1251 llvm_report_error("Error reading bitcode file: " + errstr);
1253 return FPM->run(F);
1257 /// doInitialization - Run all of the initializers for the function passes.
1259 bool FunctionPassManager::doInitialization() {
1260 return FPM->doInitialization(*MP->getModule());
1263 /// doFinalization - Run all of the finalizers for the function passes.
1265 bool FunctionPassManager::doFinalization() {
1266 return FPM->doFinalization(*MP->getModule());
1269 //===----------------------------------------------------------------------===//
1270 // FunctionPassManagerImpl implementation
1272 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1273 bool Changed = false;
1275 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1276 Changed |= getContainedManager(Index)->doInitialization(M);
1278 return Changed;
1281 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1282 bool Changed = false;
1284 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1285 Changed |= getContainedManager(Index)->doFinalization(M);
1287 return Changed;
1290 /// cleanup - After running all passes, clean up pass manager cache.
1291 void FPPassManager::cleanup() {
1292 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1293 FunctionPass *FP = getContainedPass(Index);
1294 AnalysisResolver *AR = FP->getResolver();
1295 assert(AR && "Analysis Resolver is not set");
1296 AR->clearAnalysisImpls();
1300 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1301 if (!wasRun)
1302 return;
1303 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1304 FPPassManager *FPPM = getContainedManager(Index);
1305 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1306 FPPM->getContainedPass(Index)->releaseMemory();
1309 wasRun = false;
1312 // Execute all the passes managed by this top level manager.
1313 // Return true if any function is modified by a pass.
1314 bool FunctionPassManagerImpl::run(Function &F) {
1315 bool Changed = false;
1316 TimingInfo::createTheTimeInfo();
1318 dumpArguments();
1319 dumpPasses();
1321 initializeAllAnalysisInfo();
1322 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1323 Changed |= getContainedManager(Index)->runOnFunction(F);
1325 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1326 getContainedManager(Index)->cleanup();
1328 wasRun = true;
1329 return Changed;
1332 //===----------------------------------------------------------------------===//
1333 // FPPassManager implementation
1335 char FPPassManager::ID = 0;
1336 /// Print passes managed by this manager
1337 void FPPassManager::dumpPassStructure(unsigned Offset) {
1338 llvm::errs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1339 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1340 FunctionPass *FP = getContainedPass(Index);
1341 FP->dumpPassStructure(Offset + 1);
1342 dumpLastUses(FP, Offset+1);
1347 /// Execute all of the passes scheduled for execution by invoking
1348 /// runOnFunction method. Keep track of whether any of the passes modifies
1349 /// the function, and if so, return true.
1350 bool FPPassManager::runOnFunction(Function &F) {
1351 if (F.isDeclaration())
1352 return false;
1354 bool Changed = false;
1356 // Collect inherited analysis from Module level pass manager.
1357 populateInheritedAnalysis(TPM->activeStack);
1359 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1360 FunctionPass *FP = getContainedPass(Index);
1362 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1363 dumpRequiredSet(FP);
1365 initializeAnalysisImpl(FP);
1368 PassManagerPrettyStackEntry X(FP, F);
1370 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1371 Changed |= FP->runOnFunction(F);
1372 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1375 if (Changed)
1376 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1377 dumpPreservedSet(FP);
1379 verifyPreservedAnalysis(FP);
1380 removeNotPreservedAnalysis(FP);
1381 recordAvailableAnalysis(FP);
1382 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1384 // If dominator information is available then verify the info if requested.
1385 verifyDomInfo(*FP, F);
1387 return Changed;
1390 bool FPPassManager::runOnModule(Module &M) {
1391 bool Changed = doInitialization(M);
1393 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1394 runOnFunction(*I);
1396 return Changed |= doFinalization(M);
1399 bool FPPassManager::doInitialization(Module &M) {
1400 bool Changed = false;
1402 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1403 Changed |= getContainedPass(Index)->doInitialization(M);
1405 return Changed;
1408 bool FPPassManager::doFinalization(Module &M) {
1409 bool Changed = false;
1411 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1412 Changed |= getContainedPass(Index)->doFinalization(M);
1414 return Changed;
1417 //===----------------------------------------------------------------------===//
1418 // MPPassManager implementation
1420 /// Execute all of the passes scheduled for execution by invoking
1421 /// runOnModule method. Keep track of whether any of the passes modifies
1422 /// the module, and if so, return true.
1423 bool
1424 MPPassManager::runOnModule(Module &M) {
1425 bool Changed = false;
1427 // Initialize on-the-fly passes
1428 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1429 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1430 I != E; ++I) {
1431 FunctionPassManagerImpl *FPP = I->second;
1432 Changed |= FPP->doInitialization(M);
1435 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1436 ModulePass *MP = getContainedPass(Index);
1438 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1439 M.getModuleIdentifier().c_str());
1440 dumpRequiredSet(MP);
1442 initializeAnalysisImpl(MP);
1445 PassManagerPrettyStackEntry X(MP, M);
1446 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1447 Changed |= MP->runOnModule(M);
1448 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1451 if (Changed)
1452 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1453 M.getModuleIdentifier().c_str());
1454 dumpPreservedSet(MP);
1456 verifyPreservedAnalysis(MP);
1457 removeNotPreservedAnalysis(MP);
1458 recordAvailableAnalysis(MP);
1459 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1462 // Finalize on-the-fly passes
1463 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1464 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1465 I != E; ++I) {
1466 FunctionPassManagerImpl *FPP = I->second;
1467 // We don't know when is the last time an on-the-fly pass is run,
1468 // so we need to releaseMemory / finalize here
1469 FPP->releaseMemoryOnTheFly();
1470 Changed |= FPP->doFinalization(M);
1472 return Changed;
1475 /// Add RequiredPass into list of lower level passes required by pass P.
1476 /// RequiredPass is run on the fly by Pass Manager when P requests it
1477 /// through getAnalysis interface.
1478 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1479 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1480 "Unable to handle Pass that requires lower level Analysis pass");
1481 assert((P->getPotentialPassManagerType() <
1482 RequiredPass->getPotentialPassManagerType()) &&
1483 "Unable to handle Pass that requires lower level Analysis pass");
1485 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1486 if (!FPP) {
1487 FPP = new FunctionPassManagerImpl(0);
1488 // FPP is the top level manager.
1489 FPP->setTopLevelManager(FPP);
1491 OnTheFlyManagers[P] = FPP;
1493 FPP->add(RequiredPass);
1495 // Register P as the last user of RequiredPass.
1496 SmallVector<Pass *, 12> LU;
1497 LU.push_back(RequiredPass);
1498 FPP->setLastUser(LU, P);
1501 /// Return function pass corresponding to PassInfo PI, that is
1502 /// required by module pass MP. Instantiate analysis pass, by using
1503 /// its runOnFunction() for function F.
1504 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1505 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1506 assert(FPP && "Unable to find on the fly pass");
1508 FPP->releaseMemoryOnTheFly();
1509 FPP->run(F);
1510 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1514 //===----------------------------------------------------------------------===//
1515 // PassManagerImpl implementation
1517 /// run - Execute all of the passes scheduled for execution. Keep track of
1518 /// whether any of the passes modifies the module, and if so, return true.
1519 bool PassManagerImpl::run(Module &M) {
1520 bool Changed = false;
1521 TimingInfo::createTheTimeInfo();
1523 dumpArguments();
1524 dumpPasses();
1526 initializeAllAnalysisInfo();
1527 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1528 Changed |= getContainedManager(Index)->runOnModule(M);
1529 return Changed;
1532 //===----------------------------------------------------------------------===//
1533 // PassManager implementation
1535 /// Create new pass manager
1536 PassManager::PassManager() {
1537 PM = new PassManagerImpl(0);
1538 // PM is the top level manager
1539 PM->setTopLevelManager(PM);
1542 PassManager::~PassManager() {
1543 delete PM;
1546 /// add - Add a pass to the queue of passes to run. This passes ownership of
1547 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1548 /// will be destroyed as well, so there is no need to delete the pass. This
1549 /// implies that all passes MUST be allocated with 'new'.
1550 void PassManager::add(Pass *P) {
1551 PM->add(P);
1554 /// run - Execute all of the passes scheduled for execution. Keep track of
1555 /// whether any of the passes modifies the module, and if so, return true.
1556 bool PassManager::run(Module &M) {
1557 return PM->run(M);
1560 //===----------------------------------------------------------------------===//
1561 // TimingInfo Class - This class is used to calculate information about the
1562 // amount of time each pass takes to execute. This only happens with
1563 // -time-passes is enabled on the command line.
1565 bool llvm::TimePassesIsEnabled = false;
1566 static cl::opt<bool,true>
1567 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1568 cl::desc("Time each pass, printing elapsed time for each on exit"));
1570 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1571 // a non null value (if the -time-passes option is enabled) or it leaves it
1572 // null. It may be called multiple times.
1573 void TimingInfo::createTheTimeInfo() {
1574 if (!TimePassesIsEnabled || TheTimeInfo) return;
1576 // Constructed the first time this is called, iff -time-passes is enabled.
1577 // This guarantees that the object will be constructed before static globals,
1578 // thus it will be destroyed before them.
1579 static ManagedStatic<TimingInfo> TTI;
1580 TheTimeInfo = &*TTI;
1583 /// If TimingInfo is enabled then start pass timer.
1584 void llvm::StartPassTimer(Pass *P) {
1585 if (TheTimeInfo)
1586 TheTimeInfo->passStarted(P);
1589 /// If TimingInfo is enabled then stop pass timer.
1590 void llvm::StopPassTimer(Pass *P) {
1591 if (TheTimeInfo)
1592 TheTimeInfo->passEnded(P);
1595 //===----------------------------------------------------------------------===//
1596 // PMStack implementation
1599 // Pop Pass Manager from the stack and clear its analysis info.
1600 void PMStack::pop() {
1602 PMDataManager *Top = this->top();
1603 Top->initializeAnalysisInfo();
1605 S.pop_back();
1608 // Push PM on the stack and set its top level manager.
1609 void PMStack::push(PMDataManager *PM) {
1610 assert(PM && "Unable to push. Pass Manager expected");
1612 if (!this->empty()) {
1613 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1615 assert(TPM && "Unable to find top level manager");
1616 TPM->addIndirectPassManager(PM);
1617 PM->setTopLevelManager(TPM);
1620 S.push_back(PM);
1623 // Dump content of the pass manager stack.
1624 void PMStack::dump() {
1625 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1626 E = S.end(); I != E; ++I)
1627 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1629 if (!S.empty())
1630 printf("\n");
1633 /// Find appropriate Module Pass Manager in the PM Stack and
1634 /// add self into that manager.
1635 void ModulePass::assignPassManager(PMStack &PMS,
1636 PassManagerType PreferredType) {
1637 // Find Module Pass Manager
1638 while(!PMS.empty()) {
1639 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1640 if (TopPMType == PreferredType)
1641 break; // We found desired pass manager
1642 else if (TopPMType > PMT_ModulePassManager)
1643 PMS.pop(); // Pop children pass managers
1644 else
1645 break;
1647 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1648 PMS.top()->add(this);
1651 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1652 /// in the PM Stack and add self into that manager.
1653 void FunctionPass::assignPassManager(PMStack &PMS,
1654 PassManagerType PreferredType) {
1656 // Find Module Pass Manager
1657 while(!PMS.empty()) {
1658 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1659 PMS.pop();
1660 else
1661 break;
1663 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1665 // Create new Function Pass Manager
1666 if (!FPP) {
1667 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1668 PMDataManager *PMD = PMS.top();
1670 // [1] Create new Function Pass Manager
1671 FPP = new FPPassManager(PMD->getDepth() + 1);
1672 FPP->populateInheritedAnalysis(PMS);
1674 // [2] Set up new manager's top level manager
1675 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1676 TPM->addIndirectPassManager(FPP);
1678 // [3] Assign manager to manage this new manager. This may create
1679 // and push new managers into PMS
1680 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1682 // [4] Push new manager into PMS
1683 PMS.push(FPP);
1686 // Assign FPP as the manager of this pass.
1687 FPP->add(this);
1690 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1691 /// in the PM Stack and add self into that manager.
1692 void BasicBlockPass::assignPassManager(PMStack &PMS,
1693 PassManagerType PreferredType) {
1694 BBPassManager *BBP = NULL;
1696 // Basic Pass Manager is a leaf pass manager. It does not handle
1697 // any other pass manager.
1698 if (!PMS.empty())
1699 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1701 // If leaf manager is not Basic Block Pass manager then create new
1702 // basic Block Pass manager.
1704 if (!BBP) {
1705 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1706 PMDataManager *PMD = PMS.top();
1708 // [1] Create new Basic Block Manager
1709 BBP = new BBPassManager(PMD->getDepth() + 1);
1711 // [2] Set up new manager's top level manager
1712 // Basic Block Pass Manager does not live by itself
1713 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1714 TPM->addIndirectPassManager(BBP);
1716 // [3] Assign manager to manage this new manager. This may create
1717 // and push new managers into PMS
1718 BBP->assignPassManager(PMS);
1720 // [4] Push new manager into PMS
1721 PMS.push(BBP);
1724 // Assign BBP as the manager of this pass.
1725 BBP->add(this);
1728 PassManagerBase::~PassManagerBase() {}
1730 /*===-- C Bindings --------------------------------------------------------===*/
1732 LLVMPassManagerRef LLVMCreatePassManager() {
1733 return wrap(new PassManager());
1736 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1737 return wrap(new FunctionPassManager(unwrap(P)));
1740 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1741 return unwrap<PassManager>(PM)->run(*unwrap(M));
1744 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1745 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1748 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1749 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1752 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1753 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1756 void LLVMDisposePassManager(LLVMPassManagerRef PM) {
1757 delete unwrap(PM);