make -debug-pass=Executions show information about what call graph nodes
[llvm/avr.git] / lib / VMCore / PassManager.cpp
blobf2c9ea3b997e56acd49a6aa8a67e6f6737de3c44
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 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
71 /// or higher is specified.
72 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
73 return PassDebugging >= Executions;
79 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
80 if (V == 0 && M == 0)
81 OS << "Releasing pass '";
82 else
83 OS << "Running pass '";
85 OS << P->getPassName() << "'";
87 if (M) {
88 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
89 return;
91 if (V == 0) {
92 OS << '\n';
93 return;
96 OS << " on ";
97 if (isa<Function>(V))
98 OS << "function";
99 else if (isa<BasicBlock>(V))
100 OS << "basic block";
101 else
102 OS << "value";
104 OS << " '";
105 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
106 OS << "'\n";
110 namespace {
112 //===----------------------------------------------------------------------===//
113 // BBPassManager
115 /// BBPassManager manages BasicBlockPass. It batches all the
116 /// pass together and sequence them to process one basic block before
117 /// processing next basic block.
118 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
119 public FunctionPass {
121 public:
122 static char ID;
123 explicit BBPassManager(int Depth)
124 : PMDataManager(Depth), FunctionPass(&ID) {}
126 /// Execute all of the passes scheduled for execution. Keep track of
127 /// whether any of the passes modifies the function, and if so, return true.
128 bool runOnFunction(Function &F);
130 /// Pass Manager itself does not invalidate any analysis info.
131 void getAnalysisUsage(AnalysisUsage &Info) const {
132 Info.setPreservesAll();
135 bool doInitialization(Module &M);
136 bool doInitialization(Function &F);
137 bool doFinalization(Module &M);
138 bool doFinalization(Function &F);
140 virtual const char *getPassName() const {
141 return "BasicBlock Pass Manager";
144 // Print passes managed by this manager
145 void dumpPassStructure(unsigned Offset) {
146 llvm::errs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
147 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
148 BasicBlockPass *BP = getContainedPass(Index);
149 BP->dumpPassStructure(Offset + 1);
150 dumpLastUses(BP, Offset+1);
154 BasicBlockPass *getContainedPass(unsigned N) {
155 assert(N < PassVector.size() && "Pass number out of range!");
156 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
157 return BP;
160 virtual PassManagerType getPassManagerType() const {
161 return PMT_BasicBlockPassManager;
165 char BBPassManager::ID = 0;
168 namespace llvm {
170 //===----------------------------------------------------------------------===//
171 // FunctionPassManagerImpl
173 /// FunctionPassManagerImpl manages FPPassManagers
174 class FunctionPassManagerImpl : public Pass,
175 public PMDataManager,
176 public PMTopLevelManager {
177 private:
178 bool wasRun;
179 public:
180 static char ID;
181 explicit FunctionPassManagerImpl(int Depth) :
182 Pass(&ID), PMDataManager(Depth),
183 PMTopLevelManager(TLM_Function), wasRun(false) { }
185 /// add - Add a pass to the queue of passes to run. This passes ownership of
186 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
187 /// will be destroyed as well, so there is no need to delete the pass. This
188 /// implies that all passes MUST be allocated with 'new'.
189 void add(Pass *P) {
190 schedulePass(P);
193 // Prepare for running an on the fly pass, freeing memory if needed
194 // from a previous run.
195 void releaseMemoryOnTheFly();
197 /// run - Execute all of the passes scheduled for execution. Keep track of
198 /// whether any of the passes modifies the module, and if so, return true.
199 bool run(Function &F);
201 /// doInitialization - Run all of the initializers for the function passes.
203 bool doInitialization(Module &M);
205 /// doFinalization - Run all of the finalizers for the function passes.
207 bool doFinalization(Module &M);
209 /// Pass Manager itself does not invalidate any analysis info.
210 void getAnalysisUsage(AnalysisUsage &Info) const {
211 Info.setPreservesAll();
214 inline void addTopLevelPass(Pass *P) {
216 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
218 // P is a immutable pass and it will be managed by this
219 // top level manager. Set up analysis resolver to connect them.
220 AnalysisResolver *AR = new AnalysisResolver(*this);
221 P->setResolver(AR);
222 initializeAnalysisImpl(P);
223 addImmutablePass(IP);
224 recordAvailableAnalysis(IP);
225 } else {
226 P->assignPassManager(activeStack);
231 FPPassManager *getContainedManager(unsigned N) {
232 assert(N < PassManagers.size() && "Pass number out of range!");
233 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
234 return FP;
238 char FunctionPassManagerImpl::ID = 0;
239 //===----------------------------------------------------------------------===//
240 // MPPassManager
242 /// MPPassManager manages ModulePasses and function pass managers.
243 /// It batches all Module passes and function pass managers together and
244 /// sequences them to process one module.
245 class MPPassManager : public Pass, public PMDataManager {
246 public:
247 static char ID;
248 explicit MPPassManager(int Depth) :
249 Pass(&ID), PMDataManager(Depth) { }
251 // Delete on the fly managers.
252 virtual ~MPPassManager() {
253 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
254 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
255 I != E; ++I) {
256 FunctionPassManagerImpl *FPP = I->second;
257 delete FPP;
261 /// run - Execute all of the passes scheduled for execution. Keep track of
262 /// whether any of the passes modifies the module, and if so, return true.
263 bool runOnModule(Module &M);
265 /// Pass Manager itself does not invalidate any analysis info.
266 void getAnalysisUsage(AnalysisUsage &Info) const {
267 Info.setPreservesAll();
270 /// Add RequiredPass into list of lower level passes required by pass P.
271 /// RequiredPass is run on the fly by Pass Manager when P requests it
272 /// through getAnalysis interface.
273 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
275 /// Return function pass corresponding to PassInfo PI, that is
276 /// required by module pass MP. Instantiate analysis pass, by using
277 /// its runOnFunction() for function F.
278 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
280 virtual const char *getPassName() const {
281 return "Module Pass Manager";
284 // Print passes managed by this manager
285 void dumpPassStructure(unsigned Offset) {
286 llvm::errs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
287 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
288 ModulePass *MP = getContainedPass(Index);
289 MP->dumpPassStructure(Offset + 1);
290 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
291 OnTheFlyManagers.find(MP);
292 if (I != OnTheFlyManagers.end())
293 I->second->dumpPassStructure(Offset + 2);
294 dumpLastUses(MP, Offset+1);
298 ModulePass *getContainedPass(unsigned N) {
299 assert(N < PassVector.size() && "Pass number out of range!");
300 return static_cast<ModulePass *>(PassVector[N]);
303 virtual PassManagerType getPassManagerType() const {
304 return PMT_ModulePassManager;
307 private:
308 /// Collection of on the fly FPPassManagers. These managers manage
309 /// function passes that are required by module passes.
310 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
313 char MPPassManager::ID = 0;
314 //===----------------------------------------------------------------------===//
315 // PassManagerImpl
318 /// PassManagerImpl manages MPPassManagers
319 class PassManagerImpl : public Pass,
320 public PMDataManager,
321 public PMTopLevelManager {
323 public:
324 static char ID;
325 explicit PassManagerImpl(int Depth) :
326 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
328 /// add - Add a pass to the queue of passes to run. This passes ownership of
329 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
330 /// will be destroyed as well, so there is no need to delete the pass. This
331 /// implies that all passes MUST be allocated with 'new'.
332 void add(Pass *P) {
333 schedulePass(P);
336 /// run - Execute all of the passes scheduled for execution. Keep track of
337 /// whether any of the passes modifies the module, and if so, return true.
338 bool run(Module &M);
340 /// Pass Manager itself does not invalidate any analysis info.
341 void getAnalysisUsage(AnalysisUsage &Info) const {
342 Info.setPreservesAll();
345 inline void addTopLevelPass(Pass *P) {
346 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
348 // P is a immutable pass and it will be managed by this
349 // top level manager. Set up analysis resolver to connect them.
350 AnalysisResolver *AR = new AnalysisResolver(*this);
351 P->setResolver(AR);
352 initializeAnalysisImpl(P);
353 addImmutablePass(IP);
354 recordAvailableAnalysis(IP);
355 } else {
356 P->assignPassManager(activeStack);
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;
367 char PassManagerImpl::ID = 0;
368 } // End of llvm namespace
370 namespace {
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.
378 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
380 class VISIBILITY_HIDDEN TimingInfo {
381 std::map<Pass*, Timer> TimingData;
382 TimerGroup TG;
384 public:
385 // Use 'create' member to get this.
386 TimingInfo() : TG("... Pass execution timing report ...") {}
388 // TimingDtor - Print out information about timing information
389 ~TimingInfo() {
390 // Delete all of the timers...
391 TimingData.clear();
392 // TimerGroup is deleted next, printing the report.
395 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
396 // to a non null value (if the -time-passes option is enabled) or it leaves it
397 // null. It may be called multiple times.
398 static void createTheTimeInfo();
400 void passStarted(Pass *P) {
401 if (dynamic_cast<PMDataManager *>(P))
402 return;
404 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
405 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
406 if (I == TimingData.end())
407 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
408 I->second.startTimer();
411 void passEnded(Pass *P) {
412 if (dynamic_cast<PMDataManager *>(P))
413 return;
415 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
416 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
417 assert(I != TimingData.end() && "passStarted/passEnded not nested right!");
418 I->second.stopTimer();
422 } // End of anon namespace
424 static TimingInfo *TheTimeInfo;
426 //===----------------------------------------------------------------------===//
427 // PMTopLevelManager implementation
429 /// Initialize top level manager. Create first pass manager.
430 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
431 if (t == TLM_Pass) {
432 MPPassManager *MPP = new MPPassManager(1);
433 MPP->setTopLevelManager(this);
434 addPassManager(MPP);
435 activeStack.push(MPP);
436 } else if (t == TLM_Function) {
437 FPPassManager *FPP = new FPPassManager(1);
438 FPP->setTopLevelManager(this);
439 addPassManager(FPP);
440 activeStack.push(FPP);
444 /// Set pass P as the last user of the given analysis passes.
445 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
446 Pass *P) {
447 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
448 E = AnalysisPasses.end(); I != E; ++I) {
449 Pass *AP = *I;
450 LastUser[AP] = P;
452 if (P == AP)
453 continue;
455 // If AP is the last user of other passes then make P last user of
456 // such passes.
457 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
458 LUE = LastUser.end(); LUI != LUE; ++LUI) {
459 if (LUI->second == AP)
460 // DenseMap iterator is not invalidated here because
461 // this is just updating exisitng entry.
462 LastUser[LUI->first] = P;
467 /// Collect passes whose last user is P
468 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
469 Pass *P) {
470 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
471 InversedLastUser.find(P);
472 if (DMI == InversedLastUser.end())
473 return;
475 SmallPtrSet<Pass *, 8> &LU = DMI->second;
476 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
477 E = LU.end(); I != E; ++I) {
478 LastUses.push_back(*I);
483 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
484 AnalysisUsage *AnUsage = NULL;
485 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
486 if (DMI != AnUsageMap.end())
487 AnUsage = DMI->second;
488 else {
489 AnUsage = new AnalysisUsage();
490 P->getAnalysisUsage(*AnUsage);
491 AnUsageMap[P] = AnUsage;
493 return AnUsage;
496 /// Schedule pass P for execution. Make sure that passes required by
497 /// P are run before P is run. Update analysis info maintained by
498 /// the manager. Remove dead passes. This is a recursive function.
499 void PMTopLevelManager::schedulePass(Pass *P) {
501 // TODO : Allocate function manager for this pass, other wise required set
502 // may be inserted into previous function manager
504 // Give pass a chance to prepare the stage.
505 P->preparePassManager(activeStack);
507 // If P is an analysis pass and it is available then do not
508 // generate the analysis again. Stale analysis info should not be
509 // available at this point.
510 if (P->getPassInfo() &&
511 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
512 delete P;
513 return;
516 AnalysisUsage *AnUsage = findAnalysisUsage(P);
518 bool checkAnalysis = true;
519 while (checkAnalysis) {
520 checkAnalysis = false;
522 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
523 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
524 E = RequiredSet.end(); I != E; ++I) {
526 Pass *AnalysisPass = findAnalysisPass(*I);
527 if (!AnalysisPass) {
528 AnalysisPass = (*I)->createPass();
529 if (P->getPotentialPassManagerType () ==
530 AnalysisPass->getPotentialPassManagerType())
531 // Schedule analysis pass that is managed by the same pass manager.
532 schedulePass(AnalysisPass);
533 else if (P->getPotentialPassManagerType () >
534 AnalysisPass->getPotentialPassManagerType()) {
535 // Schedule analysis pass that is managed by a new manager.
536 schedulePass(AnalysisPass);
537 // Recheck analysis passes to ensure that required analysises that
538 // are already checked are still available.
539 checkAnalysis = true;
541 else
542 // Do not schedule this analysis. Lower level analsyis
543 // passes are run on the fly.
544 delete AnalysisPass;
549 // Now all required passes are available.
550 addTopLevelPass(P);
553 /// Find the pass that implements Analysis AID. Search immutable
554 /// passes and all pass managers. If desired pass is not found
555 /// then return NULL.
556 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
558 Pass *P = NULL;
559 // Check pass managers
560 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
561 E = PassManagers.end(); P == NULL && I != E; ++I) {
562 PMDataManager *PMD = *I;
563 P = PMD->findAnalysisPass(AID, false);
566 // Check other pass managers
567 for (SmallVector<PMDataManager *, 8>::iterator
568 I = IndirectPassManagers.begin(),
569 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
570 P = (*I)->findAnalysisPass(AID, false);
572 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
573 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
574 const PassInfo *PI = (*I)->getPassInfo();
575 if (PI == AID)
576 P = *I;
578 // If Pass not found then check the interfaces implemented by Immutable Pass
579 if (!P) {
580 const std::vector<const PassInfo*> &ImmPI =
581 PI->getInterfacesImplemented();
582 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
583 P = *I;
587 return P;
590 // Print passes managed by this top level manager.
591 void PMTopLevelManager::dumpPasses() const {
593 if (PassDebugging < Structure)
594 return;
596 // Print out the immutable passes
597 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
598 ImmutablePasses[i]->dumpPassStructure(0);
601 // Every class that derives from PMDataManager also derives from Pass
602 // (sometimes indirectly), but there's no inheritance relationship
603 // between PMDataManager and Pass, so we have to dynamic_cast to get
604 // from a PMDataManager* to a Pass*.
605 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
606 E = PassManagers.end(); I != E; ++I)
607 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
610 void PMTopLevelManager::dumpArguments() const {
612 if (PassDebugging < Arguments)
613 return;
615 errs() << "Pass Arguments: ";
616 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
617 E = PassManagers.end(); I != E; ++I)
618 (*I)->dumpPassArguments();
619 errs() << "\n";
622 void PMTopLevelManager::initializeAllAnalysisInfo() {
623 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
624 E = PassManagers.end(); I != E; ++I)
625 (*I)->initializeAnalysisInfo();
627 // Initailize other pass managers
628 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
629 E = IndirectPassManagers.end(); I != E; ++I)
630 (*I)->initializeAnalysisInfo();
632 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
633 DME = LastUser.end(); DMI != DME; ++DMI) {
634 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
635 InversedLastUser.find(DMI->second);
636 if (InvDMI != InversedLastUser.end()) {
637 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
638 L.insert(DMI->first);
639 } else {
640 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
641 InversedLastUser[DMI->second] = L;
646 /// Destructor
647 PMTopLevelManager::~PMTopLevelManager() {
648 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
649 E = PassManagers.end(); I != E; ++I)
650 delete *I;
652 for (SmallVector<ImmutablePass *, 8>::iterator
653 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
654 delete *I;
656 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
657 DME = AnUsageMap.end(); DMI != DME; ++DMI)
658 delete DMI->second;
661 //===----------------------------------------------------------------------===//
662 // PMDataManager implementation
664 /// Augement AvailableAnalysis by adding analysis made available by pass P.
665 void PMDataManager::recordAvailableAnalysis(Pass *P) {
666 const PassInfo *PI = P->getPassInfo();
667 if (PI == 0) return;
669 AvailableAnalysis[PI] = P;
671 //This pass is the current implementation of all of the interfaces it
672 //implements as well.
673 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
674 for (unsigned i = 0, e = II.size(); i != e; ++i)
675 AvailableAnalysis[II[i]] = P;
678 // Return true if P preserves high level analysis used by other
679 // passes managed by this manager
680 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
681 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
682 if (AnUsage->getPreservesAll())
683 return true;
685 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
686 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
687 E = HigherLevelAnalysis.end(); I != E; ++I) {
688 Pass *P1 = *I;
689 if (!dynamic_cast<ImmutablePass*>(P1) &&
690 std::find(PreservedSet.begin(), PreservedSet.end(),
691 P1->getPassInfo()) ==
692 PreservedSet.end())
693 return false;
696 return true;
699 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
700 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
701 // Don't do this unless assertions are enabled.
702 #ifdef NDEBUG
703 return;
704 #endif
705 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
706 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
708 // Verify preserved analysis
709 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
710 E = PreservedSet.end(); I != E; ++I) {
711 AnalysisID AID = *I;
712 if (Pass *AP = findAnalysisPass(AID, true))
713 AP->verifyAnalysis();
717 /// verifyDomInfo - Verify dominator information if it is available.
718 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
719 if (!VerifyDomInfo || !P.getResolver())
720 return;
722 DominatorTree *DT = P.getAnalysisIfAvailable<DominatorTree>();
723 if (!DT)
724 return;
726 DominatorTree OtherDT;
727 OtherDT.getBase().recalculate(F);
728 if (DT->compare(OtherDT)) {
729 errs() << "Dominator Information for " << F.getName() << "\n";
730 errs() << "Pass '" << P.getPassName() << "'\n";
731 errs() << "----- Valid -----\n";
732 OtherDT.dump();
733 errs() << "----- Invalid -----\n";
734 DT->dump();
735 llvm_unreachable("Invalid dominator info");
738 DominanceFrontier *DF = P.getAnalysisIfAvailable<DominanceFrontier>();
739 if (!DF)
740 return;
742 DominanceFrontier OtherDF;
743 std::vector<BasicBlock*> DTRoots = DT->getRoots();
744 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
745 if (DF->compare(OtherDF)) {
746 errs() << "Dominator Information for " << F.getName() << "\n";
747 errs() << "Pass '" << P.getPassName() << "'\n";
748 errs() << "----- Valid -----\n";
749 OtherDF.dump();
750 errs() << "----- Invalid -----\n";
751 DF->dump();
752 llvm_unreachable("Invalid dominator info");
756 /// Remove Analysis not preserved by Pass P
757 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
758 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
759 if (AnUsage->getPreservesAll())
760 return;
762 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
763 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
764 E = AvailableAnalysis.end(); I != E; ) {
765 std::map<AnalysisID, Pass*>::iterator Info = I++;
766 if (!dynamic_cast<ImmutablePass*>(Info->second)
767 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
768 PreservedSet.end()) {
769 // Remove this analysis
770 if (PassDebugging >= Details) {
771 Pass *S = Info->second;
772 errs() << " -- '" << P->getPassName() << "' is not preserving '";
773 errs() << S->getPassName() << "'\n";
775 AvailableAnalysis.erase(Info);
779 // Check inherited analysis also. If P is not preserving analysis
780 // provided by parent manager then remove it here.
781 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
783 if (!InheritedAnalysis[Index])
784 continue;
786 for (std::map<AnalysisID, Pass*>::iterator
787 I = InheritedAnalysis[Index]->begin(),
788 E = InheritedAnalysis[Index]->end(); I != E; ) {
789 std::map<AnalysisID, Pass *>::iterator Info = I++;
790 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
791 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
792 PreservedSet.end())
793 // Remove this analysis
794 InheritedAnalysis[Index]->erase(Info);
799 /// Remove analysis passes that are not used any longer
800 void PMDataManager::removeDeadPasses(Pass *P, const StringRef &Msg,
801 enum PassDebuggingString DBG_STR) {
803 SmallVector<Pass *, 12> DeadPasses;
805 // If this is a on the fly manager then it does not have TPM.
806 if (!TPM)
807 return;
809 TPM->collectLastUses(DeadPasses, P);
811 if (PassDebugging >= Details && !DeadPasses.empty()) {
812 errs() << " -*- '" << P->getPassName();
813 errs() << "' is the last user of following pass instances.";
814 errs() << " Free these instances\n";
817 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
818 E = DeadPasses.end(); I != E; ++I) {
820 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
823 // If the pass crashes releasing memory, remember this.
824 PassManagerPrettyStackEntry X(*I);
826 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
827 (*I)->releaseMemory();
828 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
830 if (const PassInfo *PI = (*I)->getPassInfo()) {
831 std::map<AnalysisID, Pass*>::iterator Pos =
832 AvailableAnalysis.find(PI);
834 // It is possible that pass is already removed from the AvailableAnalysis
835 if (Pos != AvailableAnalysis.end())
836 AvailableAnalysis.erase(Pos);
838 // Remove all interfaces this pass implements, for which it is also
839 // listed as the available implementation.
840 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
841 for (unsigned i = 0, e = II.size(); i != e; ++i) {
842 Pos = AvailableAnalysis.find(II[i]);
843 if (Pos != AvailableAnalysis.end() && Pos->second == *I)
844 AvailableAnalysis.erase(Pos);
850 /// Add pass P into the PassVector. Update
851 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
852 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
853 // This manager is going to manage pass P. Set up analysis resolver
854 // to connect them.
855 AnalysisResolver *AR = new AnalysisResolver(*this);
856 P->setResolver(AR);
858 // If a FunctionPass F is the last user of ModulePass info M
859 // then the F's manager, not F, records itself as a last user of M.
860 SmallVector<Pass *, 12> TransferLastUses;
862 if (!ProcessAnalysis) {
863 // Add pass
864 PassVector.push_back(P);
865 return;
868 // At the moment, this pass is the last user of all required passes.
869 SmallVector<Pass *, 12> LastUses;
870 SmallVector<Pass *, 8> RequiredPasses;
871 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
873 unsigned PDepth = this->getDepth();
875 collectRequiredAnalysis(RequiredPasses,
876 ReqAnalysisNotAvailable, P);
877 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
878 E = RequiredPasses.end(); I != E; ++I) {
879 Pass *PRequired = *I;
880 unsigned RDepth = 0;
882 assert(PRequired->getResolver() && "Analysis Resolver is not set");
883 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
884 RDepth = DM.getDepth();
886 if (PDepth == RDepth)
887 LastUses.push_back(PRequired);
888 else if (PDepth > RDepth) {
889 // Let the parent claim responsibility of last use
890 TransferLastUses.push_back(PRequired);
891 // Keep track of higher level analysis used by this manager.
892 HigherLevelAnalysis.push_back(PRequired);
893 } else
894 llvm_unreachable("Unable to accomodate Required Pass");
897 // Set P as P's last user until someone starts using P.
898 // However, if P is a Pass Manager then it does not need
899 // to record its last user.
900 if (!dynamic_cast<PMDataManager *>(P))
901 LastUses.push_back(P);
902 TPM->setLastUser(LastUses, P);
904 if (!TransferLastUses.empty()) {
905 Pass *My_PM = dynamic_cast<Pass *>(this);
906 TPM->setLastUser(TransferLastUses, My_PM);
907 TransferLastUses.clear();
910 // Now, take care of required analysises that are not available.
911 for (SmallVector<AnalysisID, 8>::iterator
912 I = ReqAnalysisNotAvailable.begin(),
913 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
914 Pass *AnalysisPass = (*I)->createPass();
915 this->addLowerLevelRequiredPass(P, AnalysisPass);
918 // Take a note of analysis required and made available by this pass.
919 // Remove the analysis not preserved by this pass
920 removeNotPreservedAnalysis(P);
921 recordAvailableAnalysis(P);
923 // Add pass
924 PassVector.push_back(P);
928 /// Populate RP with analysis pass that are required by
929 /// pass P and are available. Populate RP_NotAvail with analysis
930 /// pass that are required by pass P but are not available.
931 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
932 SmallVector<AnalysisID, 8> &RP_NotAvail,
933 Pass *P) {
934 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
935 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
936 for (AnalysisUsage::VectorType::const_iterator
937 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
938 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
939 RP.push_back(AnalysisPass);
940 else
941 RP_NotAvail.push_back(*I);
944 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
945 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
946 E = IDs.end(); I != E; ++I) {
947 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
948 RP.push_back(AnalysisPass);
949 else
950 RP_NotAvail.push_back(*I);
954 // All Required analyses should be available to the pass as it runs! Here
955 // we fill in the AnalysisImpls member of the pass so that it can
956 // successfully use the getAnalysis() method to retrieve the
957 // implementations it needs.
959 void PMDataManager::initializeAnalysisImpl(Pass *P) {
960 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
962 for (AnalysisUsage::VectorType::const_iterator
963 I = AnUsage->getRequiredSet().begin(),
964 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
965 Pass *Impl = findAnalysisPass(*I, true);
966 if (Impl == 0)
967 // This may be analysis pass that is initialized on the fly.
968 // If that is not the case then it will raise an assert when it is used.
969 continue;
970 AnalysisResolver *AR = P->getResolver();
971 assert(AR && "Analysis Resolver is not set");
972 AR->addAnalysisImplsPair(*I, Impl);
976 /// Find the pass that implements Analysis AID. If desired pass is not found
977 /// then return NULL.
978 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
980 // Check if AvailableAnalysis map has one entry.
981 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
983 if (I != AvailableAnalysis.end())
984 return I->second;
986 // Search Parents through TopLevelManager
987 if (SearchParent)
988 return TPM->findAnalysisPass(AID);
990 return NULL;
993 // Print list of passes that are last used by P.
994 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
996 SmallVector<Pass *, 12> LUses;
998 // If this is a on the fly manager then it does not have TPM.
999 if (!TPM)
1000 return;
1002 TPM->collectLastUses(LUses, P);
1004 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
1005 E = LUses.end(); I != E; ++I) {
1006 llvm::errs() << "--" << std::string(Offset*2, ' ');
1007 (*I)->dumpPassStructure(0);
1011 void PMDataManager::dumpPassArguments() const {
1012 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1013 E = PassVector.end(); I != E; ++I) {
1014 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
1015 PMD->dumpPassArguments();
1016 else
1017 if (const PassInfo *PI = (*I)->getPassInfo())
1018 if (!PI->isAnalysisGroup())
1019 errs() << " -" << PI->getPassArgument();
1023 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1024 enum PassDebuggingString S2,
1025 const StringRef &Msg) {
1026 if (PassDebugging < Executions)
1027 return;
1028 errs() << (void*)this << std::string(getDepth()*2+1, ' ');
1029 switch (S1) {
1030 case EXECUTION_MSG:
1031 errs() << "Executing Pass '" << P->getPassName();
1032 break;
1033 case MODIFICATION_MSG:
1034 errs() << "Made Modification '" << P->getPassName();
1035 break;
1036 case FREEING_MSG:
1037 errs() << " Freeing Pass '" << P->getPassName();
1038 break;
1039 default:
1040 break;
1042 switch (S2) {
1043 case ON_BASICBLOCK_MSG:
1044 errs() << "' on BasicBlock '" << Msg << "'...\n";
1045 break;
1046 case ON_FUNCTION_MSG:
1047 errs() << "' on Function '" << Msg << "'...\n";
1048 break;
1049 case ON_MODULE_MSG:
1050 errs() << "' on Module '" << Msg << "'...\n";
1051 break;
1052 case ON_LOOP_MSG:
1053 errs() << "' on Loop '" << Msg << "'...\n";
1054 break;
1055 case ON_CG_MSG:
1056 errs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1057 break;
1058 default:
1059 break;
1063 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1064 if (PassDebugging < Details)
1065 return;
1067 AnalysisUsage analysisUsage;
1068 P->getAnalysisUsage(analysisUsage);
1069 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1072 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1073 if (PassDebugging < Details)
1074 return;
1076 AnalysisUsage analysisUsage;
1077 P->getAnalysisUsage(analysisUsage);
1078 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1081 void PMDataManager::dumpAnalysisUsage(const StringRef &Msg, const Pass *P,
1082 const AnalysisUsage::VectorType &Set) const {
1083 assert(PassDebugging >= Details);
1084 if (Set.empty())
1085 return;
1086 errs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1087 for (unsigned i = 0; i != Set.size(); ++i) {
1088 if (i) errs() << ',';
1089 errs() << ' ' << Set[i]->getPassName();
1091 errs() << '\n';
1094 /// Add RequiredPass into list of lower level passes required by pass P.
1095 /// RequiredPass is run on the fly by Pass Manager when P requests it
1096 /// through getAnalysis interface.
1097 /// This should be handled by specific pass manager.
1098 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1099 if (TPM) {
1100 TPM->dumpArguments();
1101 TPM->dumpPasses();
1104 // Module Level pass may required Function Level analysis info
1105 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1106 // to provide this on demand. In that case, in Pass manager terminology,
1107 // module level pass is requiring lower level analysis info managed by
1108 // lower level pass manager.
1110 // When Pass manager is not able to order required analysis info, Pass manager
1111 // checks whether any lower level manager will be able to provide this
1112 // analysis info on demand or not.
1113 #ifndef NDEBUG
1114 errs() << "Unable to schedule '" << RequiredPass->getPassName();
1115 errs() << "' required by '" << P->getPassName() << "'\n";
1116 #endif
1117 llvm_unreachable("Unable to schedule pass");
1120 // Destructor
1121 PMDataManager::~PMDataManager() {
1122 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1123 E = PassVector.end(); I != E; ++I)
1124 delete *I;
1127 //===----------------------------------------------------------------------===//
1128 // NOTE: Is this the right place to define this method ?
1129 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1130 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1131 return PM.findAnalysisPass(ID, dir);
1134 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1135 Function &F) {
1136 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1139 //===----------------------------------------------------------------------===//
1140 // BBPassManager implementation
1142 /// Execute all of the passes scheduled for execution by invoking
1143 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1144 /// the function, and if so, return true.
1145 bool BBPassManager::runOnFunction(Function &F) {
1146 if (F.isDeclaration())
1147 return false;
1149 bool Changed = doInitialization(F);
1151 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1152 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1153 BasicBlockPass *BP = getContainedPass(Index);
1155 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1156 dumpRequiredSet(BP);
1158 initializeAnalysisImpl(BP);
1161 // If the pass crashes, remember this.
1162 PassManagerPrettyStackEntry X(BP, *I);
1164 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1165 Changed |= BP->runOnBasicBlock(*I);
1166 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1169 if (Changed)
1170 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1171 I->getName());
1172 dumpPreservedSet(BP);
1174 verifyPreservedAnalysis(BP);
1175 removeNotPreservedAnalysis(BP);
1176 recordAvailableAnalysis(BP);
1177 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1180 return Changed |= doFinalization(F);
1183 // Implement doInitialization and doFinalization
1184 bool BBPassManager::doInitialization(Module &M) {
1185 bool Changed = false;
1187 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1188 Changed |= getContainedPass(Index)->doInitialization(M);
1190 return Changed;
1193 bool BBPassManager::doFinalization(Module &M) {
1194 bool Changed = false;
1196 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1197 Changed |= getContainedPass(Index)->doFinalization(M);
1199 return Changed;
1202 bool BBPassManager::doInitialization(Function &F) {
1203 bool Changed = false;
1205 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1206 BasicBlockPass *BP = getContainedPass(Index);
1207 Changed |= BP->doInitialization(F);
1210 return Changed;
1213 bool BBPassManager::doFinalization(Function &F) {
1214 bool Changed = false;
1216 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1217 BasicBlockPass *BP = getContainedPass(Index);
1218 Changed |= BP->doFinalization(F);
1221 return Changed;
1225 //===----------------------------------------------------------------------===//
1226 // FunctionPassManager implementation
1228 /// Create new Function pass manager
1229 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1230 FPM = new FunctionPassManagerImpl(0);
1231 // FPM is the top level manager.
1232 FPM->setTopLevelManager(FPM);
1234 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1235 FPM->setResolver(AR);
1237 MP = P;
1240 FunctionPassManager::~FunctionPassManager() {
1241 delete FPM;
1244 /// add - Add a pass to the queue of passes to run. This passes
1245 /// ownership of the Pass to the PassManager. When the
1246 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1247 /// there is no need to delete the pass. (TODO delete passes.)
1248 /// This implies that all passes MUST be allocated with 'new'.
1249 void FunctionPassManager::add(Pass *P) {
1250 FPM->add(P);
1253 /// run - Execute all of the passes scheduled for execution. Keep
1254 /// track of whether any of the passes modifies the function, and if
1255 /// so, return true.
1257 bool FunctionPassManager::run(Function &F) {
1258 std::string errstr;
1259 if (MP->materializeFunction(&F, &errstr)) {
1260 llvm_report_error("Error reading bitcode file: " + errstr);
1262 return FPM->run(F);
1266 /// doInitialization - Run all of the initializers for the function passes.
1268 bool FunctionPassManager::doInitialization() {
1269 return FPM->doInitialization(*MP->getModule());
1272 /// doFinalization - Run all of the finalizers for the function passes.
1274 bool FunctionPassManager::doFinalization() {
1275 return FPM->doFinalization(*MP->getModule());
1278 //===----------------------------------------------------------------------===//
1279 // FunctionPassManagerImpl implementation
1281 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1282 bool Changed = false;
1284 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1285 Changed |= getContainedManager(Index)->doInitialization(M);
1287 return Changed;
1290 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1291 bool Changed = false;
1293 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1294 Changed |= getContainedManager(Index)->doFinalization(M);
1296 return Changed;
1299 /// cleanup - After running all passes, clean up pass manager cache.
1300 void FPPassManager::cleanup() {
1301 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1302 FunctionPass *FP = getContainedPass(Index);
1303 AnalysisResolver *AR = FP->getResolver();
1304 assert(AR && "Analysis Resolver is not set");
1305 AR->clearAnalysisImpls();
1309 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1310 if (!wasRun)
1311 return;
1312 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1313 FPPassManager *FPPM = getContainedManager(Index);
1314 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1315 FPPM->getContainedPass(Index)->releaseMemory();
1318 wasRun = false;
1321 // Execute all the passes managed by this top level manager.
1322 // Return true if any function is modified by a pass.
1323 bool FunctionPassManagerImpl::run(Function &F) {
1324 bool Changed = false;
1325 TimingInfo::createTheTimeInfo();
1327 dumpArguments();
1328 dumpPasses();
1330 initializeAllAnalysisInfo();
1331 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1332 Changed |= getContainedManager(Index)->runOnFunction(F);
1334 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1335 getContainedManager(Index)->cleanup();
1337 wasRun = true;
1338 return Changed;
1341 //===----------------------------------------------------------------------===//
1342 // FPPassManager implementation
1344 char FPPassManager::ID = 0;
1345 /// Print passes managed by this manager
1346 void FPPassManager::dumpPassStructure(unsigned Offset) {
1347 llvm::errs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1348 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1349 FunctionPass *FP = getContainedPass(Index);
1350 FP->dumpPassStructure(Offset + 1);
1351 dumpLastUses(FP, Offset+1);
1356 /// Execute all of the passes scheduled for execution by invoking
1357 /// runOnFunction method. Keep track of whether any of the passes modifies
1358 /// the function, and if so, return true.
1359 bool FPPassManager::runOnFunction(Function &F) {
1360 if (F.isDeclaration())
1361 return false;
1363 bool Changed = false;
1365 // Collect inherited analysis from Module level pass manager.
1366 populateInheritedAnalysis(TPM->activeStack);
1368 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1369 FunctionPass *FP = getContainedPass(Index);
1371 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1372 dumpRequiredSet(FP);
1374 initializeAnalysisImpl(FP);
1377 PassManagerPrettyStackEntry X(FP, F);
1379 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1380 Changed |= FP->runOnFunction(F);
1381 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1384 if (Changed)
1385 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1386 dumpPreservedSet(FP);
1388 verifyPreservedAnalysis(FP);
1389 removeNotPreservedAnalysis(FP);
1390 recordAvailableAnalysis(FP);
1391 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1393 // If dominator information is available then verify the info if requested.
1394 verifyDomInfo(*FP, F);
1396 return Changed;
1399 bool FPPassManager::runOnModule(Module &M) {
1400 bool Changed = doInitialization(M);
1402 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1403 runOnFunction(*I);
1405 return Changed |= doFinalization(M);
1408 bool FPPassManager::doInitialization(Module &M) {
1409 bool Changed = false;
1411 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1412 Changed |= getContainedPass(Index)->doInitialization(M);
1414 return Changed;
1417 bool FPPassManager::doFinalization(Module &M) {
1418 bool Changed = false;
1420 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1421 Changed |= getContainedPass(Index)->doFinalization(M);
1423 return Changed;
1426 //===----------------------------------------------------------------------===//
1427 // MPPassManager implementation
1429 /// Execute all of the passes scheduled for execution by invoking
1430 /// runOnModule method. Keep track of whether any of the passes modifies
1431 /// the module, and if so, return true.
1432 bool
1433 MPPassManager::runOnModule(Module &M) {
1434 bool Changed = false;
1436 // Initialize on-the-fly passes
1437 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1438 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1439 I != E; ++I) {
1440 FunctionPassManagerImpl *FPP = I->second;
1441 Changed |= FPP->doInitialization(M);
1444 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1445 ModulePass *MP = getContainedPass(Index);
1447 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1448 M.getModuleIdentifier().c_str());
1449 dumpRequiredSet(MP);
1451 initializeAnalysisImpl(MP);
1454 PassManagerPrettyStackEntry X(MP, M);
1455 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1456 Changed |= MP->runOnModule(M);
1457 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1460 if (Changed)
1461 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1462 M.getModuleIdentifier().c_str());
1463 dumpPreservedSet(MP);
1465 verifyPreservedAnalysis(MP);
1466 removeNotPreservedAnalysis(MP);
1467 recordAvailableAnalysis(MP);
1468 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1471 // Finalize on-the-fly passes
1472 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1473 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1474 I != E; ++I) {
1475 FunctionPassManagerImpl *FPP = I->second;
1476 // We don't know when is the last time an on-the-fly pass is run,
1477 // so we need to releaseMemory / finalize here
1478 FPP->releaseMemoryOnTheFly();
1479 Changed |= FPP->doFinalization(M);
1481 return Changed;
1484 /// Add RequiredPass into list of lower level passes required by pass P.
1485 /// RequiredPass is run on the fly by Pass Manager when P requests it
1486 /// through getAnalysis interface.
1487 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1488 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1489 "Unable to handle Pass that requires lower level Analysis pass");
1490 assert((P->getPotentialPassManagerType() <
1491 RequiredPass->getPotentialPassManagerType()) &&
1492 "Unable to handle Pass that requires lower level Analysis pass");
1494 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1495 if (!FPP) {
1496 FPP = new FunctionPassManagerImpl(0);
1497 // FPP is the top level manager.
1498 FPP->setTopLevelManager(FPP);
1500 OnTheFlyManagers[P] = FPP;
1502 FPP->add(RequiredPass);
1504 // Register P as the last user of RequiredPass.
1505 SmallVector<Pass *, 12> LU;
1506 LU.push_back(RequiredPass);
1507 FPP->setLastUser(LU, P);
1510 /// Return function pass corresponding to PassInfo PI, that is
1511 /// required by module pass MP. Instantiate analysis pass, by using
1512 /// its runOnFunction() for function F.
1513 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1514 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1515 assert(FPP && "Unable to find on the fly pass");
1517 FPP->releaseMemoryOnTheFly();
1518 FPP->run(F);
1519 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1523 //===----------------------------------------------------------------------===//
1524 // PassManagerImpl implementation
1526 /// run - Execute all of the passes scheduled for execution. Keep track of
1527 /// whether any of the passes modifies the module, and if so, return true.
1528 bool PassManagerImpl::run(Module &M) {
1529 bool Changed = false;
1530 TimingInfo::createTheTimeInfo();
1532 dumpArguments();
1533 dumpPasses();
1535 initializeAllAnalysisInfo();
1536 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1537 Changed |= getContainedManager(Index)->runOnModule(M);
1538 return Changed;
1541 //===----------------------------------------------------------------------===//
1542 // PassManager implementation
1544 /// Create new pass manager
1545 PassManager::PassManager() {
1546 PM = new PassManagerImpl(0);
1547 // PM is the top level manager
1548 PM->setTopLevelManager(PM);
1551 PassManager::~PassManager() {
1552 delete PM;
1555 /// add - Add a pass to the queue of passes to run. This passes ownership of
1556 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1557 /// will be destroyed as well, so there is no need to delete the pass. This
1558 /// implies that all passes MUST be allocated with 'new'.
1559 void PassManager::add(Pass *P) {
1560 PM->add(P);
1563 /// run - Execute all of the passes scheduled for execution. Keep track of
1564 /// whether any of the passes modifies the module, and if so, return true.
1565 bool PassManager::run(Module &M) {
1566 return PM->run(M);
1569 //===----------------------------------------------------------------------===//
1570 // TimingInfo Class - This class is used to calculate information about the
1571 // amount of time each pass takes to execute. This only happens with
1572 // -time-passes is enabled on the command line.
1574 bool llvm::TimePassesIsEnabled = false;
1575 static cl::opt<bool,true>
1576 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1577 cl::desc("Time each pass, printing elapsed time for each on exit"));
1579 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1580 // a non null value (if the -time-passes option is enabled) or it leaves it
1581 // null. It may be called multiple times.
1582 void TimingInfo::createTheTimeInfo() {
1583 if (!TimePassesIsEnabled || TheTimeInfo) return;
1585 // Constructed the first time this is called, iff -time-passes is enabled.
1586 // This guarantees that the object will be constructed before static globals,
1587 // thus it will be destroyed before them.
1588 static ManagedStatic<TimingInfo> TTI;
1589 TheTimeInfo = &*TTI;
1592 /// If TimingInfo is enabled then start pass timer.
1593 void llvm::StartPassTimer(Pass *P) {
1594 if (TheTimeInfo)
1595 TheTimeInfo->passStarted(P);
1598 /// If TimingInfo is enabled then stop pass timer.
1599 void llvm::StopPassTimer(Pass *P) {
1600 if (TheTimeInfo)
1601 TheTimeInfo->passEnded(P);
1604 //===----------------------------------------------------------------------===//
1605 // PMStack implementation
1608 // Pop Pass Manager from the stack and clear its analysis info.
1609 void PMStack::pop() {
1611 PMDataManager *Top = this->top();
1612 Top->initializeAnalysisInfo();
1614 S.pop_back();
1617 // Push PM on the stack and set its top level manager.
1618 void PMStack::push(PMDataManager *PM) {
1619 assert(PM && "Unable to push. Pass Manager expected");
1621 if (!this->empty()) {
1622 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1624 assert(TPM && "Unable to find top level manager");
1625 TPM->addIndirectPassManager(PM);
1626 PM->setTopLevelManager(TPM);
1629 S.push_back(PM);
1632 // Dump content of the pass manager stack.
1633 void PMStack::dump() {
1634 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1635 E = S.end(); I != E; ++I)
1636 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1638 if (!S.empty())
1639 printf("\n");
1642 /// Find appropriate Module Pass Manager in the PM Stack and
1643 /// add self into that manager.
1644 void ModulePass::assignPassManager(PMStack &PMS,
1645 PassManagerType PreferredType) {
1646 // Find Module Pass Manager
1647 while(!PMS.empty()) {
1648 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1649 if (TopPMType == PreferredType)
1650 break; // We found desired pass manager
1651 else if (TopPMType > PMT_ModulePassManager)
1652 PMS.pop(); // Pop children pass managers
1653 else
1654 break;
1656 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1657 PMS.top()->add(this);
1660 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1661 /// in the PM Stack and add self into that manager.
1662 void FunctionPass::assignPassManager(PMStack &PMS,
1663 PassManagerType PreferredType) {
1665 // Find Module Pass Manager
1666 while(!PMS.empty()) {
1667 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1668 PMS.pop();
1669 else
1670 break;
1672 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1674 // Create new Function Pass Manager
1675 if (!FPP) {
1676 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1677 PMDataManager *PMD = PMS.top();
1679 // [1] Create new Function Pass Manager
1680 FPP = new FPPassManager(PMD->getDepth() + 1);
1681 FPP->populateInheritedAnalysis(PMS);
1683 // [2] Set up new manager's top level manager
1684 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1685 TPM->addIndirectPassManager(FPP);
1687 // [3] Assign manager to manage this new manager. This may create
1688 // and push new managers into PMS
1689 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1691 // [4] Push new manager into PMS
1692 PMS.push(FPP);
1695 // Assign FPP as the manager of this pass.
1696 FPP->add(this);
1699 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1700 /// in the PM Stack and add self into that manager.
1701 void BasicBlockPass::assignPassManager(PMStack &PMS,
1702 PassManagerType PreferredType) {
1703 BBPassManager *BBP = NULL;
1705 // Basic Pass Manager is a leaf pass manager. It does not handle
1706 // any other pass manager.
1707 if (!PMS.empty())
1708 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1710 // If leaf manager is not Basic Block Pass manager then create new
1711 // basic Block Pass manager.
1713 if (!BBP) {
1714 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1715 PMDataManager *PMD = PMS.top();
1717 // [1] Create new Basic Block Manager
1718 BBP = new BBPassManager(PMD->getDepth() + 1);
1720 // [2] Set up new manager's top level manager
1721 // Basic Block Pass Manager does not live by itself
1722 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1723 TPM->addIndirectPassManager(BBP);
1725 // [3] Assign manager to manage this new manager. This may create
1726 // and push new managers into PMS
1727 BBP->assignPassManager(PMS);
1729 // [4] Push new manager into PMS
1730 PMS.push(BBP);
1733 // Assign BBP as the manager of this pass.
1734 BBP->add(this);
1737 PassManagerBase::~PassManagerBase() {}
1739 /*===-- C Bindings --------------------------------------------------------===*/
1741 LLVMPassManagerRef LLVMCreatePassManager() {
1742 return wrap(new PassManager());
1745 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1746 return wrap(new FunctionPassManager(unwrap(P)));
1749 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1750 return unwrap<PassManager>(PM)->run(*unwrap(M));
1753 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1754 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1757 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1758 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1761 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1762 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1765 void LLVMDisposePassManager(LLVMPassManagerRef PM) {
1766 delete unwrap(PM);