Change allowsUnalignedMemoryAccesses to take type argument since some targets
[llvm/avr.git] / lib / VMCore / PassManager.cpp
blob8c427849e71c38f67da0ad9a63d30a9e70906082
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/Streams.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/System/Threading.h"
26 #include "llvm/Analysis/Dominators.h"
27 #include "llvm-c/Core.h"
28 #include <algorithm>
29 #include <cstdio>
30 #include <map>
31 using namespace llvm;
33 // See PassManagers.h for Pass Manager infrastructure overview.
35 namespace llvm {
37 //===----------------------------------------------------------------------===//
38 // Pass debugging information. Often it is useful to find out what pass is
39 // running when a crash occurs in a utility. When this library is compiled with
40 // debugging on, a command line option (--debug-pass) is enabled that causes the
41 // pass name to be printed before it executes.
44 // Different debug levels that can be enabled...
45 enum PassDebugLevel {
46 None, Arguments, Structure, Executions, Details
49 // Always verify dominfo if expensive checking is enabled.
50 #ifdef XDEBUG
51 bool VerifyDomInfo = true;
52 #else
53 bool VerifyDomInfo = false;
54 #endif
55 static cl::opt<bool,true>
56 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
57 cl::desc("Verify dominator info (time consuming)"));
59 static cl::opt<enum PassDebugLevel>
60 PassDebugging("debug-pass", cl::Hidden,
61 cl::desc("Print PassManager debugging information"),
62 cl::values(
63 clEnumVal(None , "disable debug output"),
64 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
65 clEnumVal(Structure , "print pass structure before run()"),
66 clEnumVal(Executions, "print pass name before it is executed"),
67 clEnumVal(Details , "print pass details when it is executed"),
68 clEnumValEnd));
69 } // End of llvm namespace
71 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
72 if (V == 0 && M == 0)
73 OS << "Releasing pass '";
74 else
75 OS << "Running pass '";
77 OS << P->getPassName() << "'";
79 if (M) {
80 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
81 return;
83 if (V == 0) {
84 OS << '\n';
85 return;
88 OS << " on ";
89 if (isa<Function>(V))
90 OS << "function";
91 else if (isa<BasicBlock>(V))
92 OS << "basic block";
93 else
94 OS << "value";
96 OS << " '";
97 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
98 OS << "'\n";
102 namespace {
104 //===----------------------------------------------------------------------===//
105 // BBPassManager
107 /// BBPassManager manages BasicBlockPass. It batches all the
108 /// pass together and sequence them to process one basic block before
109 /// processing next basic block.
110 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
111 public FunctionPass {
113 public:
114 static char ID;
115 explicit BBPassManager(int Depth)
116 : PMDataManager(Depth), FunctionPass(&ID) {}
118 /// Execute all of the passes scheduled for execution. Keep track of
119 /// whether any of the passes modifies the function, and if so, return true.
120 bool runOnFunction(Function &F);
122 /// Pass Manager itself does not invalidate any analysis info.
123 void getAnalysisUsage(AnalysisUsage &Info) const {
124 Info.setPreservesAll();
127 bool doInitialization(Module &M);
128 bool doInitialization(Function &F);
129 bool doFinalization(Module &M);
130 bool doFinalization(Function &F);
132 virtual const char *getPassName() const {
133 return "BasicBlock Pass Manager";
136 // Print passes managed by this manager
137 void dumpPassStructure(unsigned Offset) {
138 llvm::errs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
139 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
140 BasicBlockPass *BP = getContainedPass(Index);
141 BP->dumpPassStructure(Offset + 1);
142 dumpLastUses(BP, Offset+1);
146 BasicBlockPass *getContainedPass(unsigned N) {
147 assert(N < PassVector.size() && "Pass number out of range!");
148 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
149 return BP;
152 virtual PassManagerType getPassManagerType() const {
153 return PMT_BasicBlockPassManager;
157 char BBPassManager::ID = 0;
160 namespace llvm {
162 //===----------------------------------------------------------------------===//
163 // FunctionPassManagerImpl
165 /// FunctionPassManagerImpl manages FPPassManagers
166 class FunctionPassManagerImpl : public Pass,
167 public PMDataManager,
168 public PMTopLevelManager {
169 private:
170 bool wasRun;
171 public:
172 static char ID;
173 explicit FunctionPassManagerImpl(int Depth) :
174 Pass(&ID), PMDataManager(Depth),
175 PMTopLevelManager(TLM_Function), wasRun(false) { }
177 /// add - Add a pass to the queue of passes to run. This passes ownership of
178 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
179 /// will be destroyed as well, so there is no need to delete the pass. This
180 /// implies that all passes MUST be allocated with 'new'.
181 void add(Pass *P) {
182 schedulePass(P);
185 // Prepare for running an on the fly pass, freeing memory if needed
186 // from a previous run.
187 void releaseMemoryOnTheFly();
189 /// run - Execute all of the passes scheduled for execution. Keep track of
190 /// whether any of the passes modifies the module, and if so, return true.
191 bool run(Function &F);
193 /// doInitialization - Run all of the initializers for the function passes.
195 bool doInitialization(Module &M);
197 /// doFinalization - Run all of the finalizers for the function passes.
199 bool doFinalization(Module &M);
201 /// Pass Manager itself does not invalidate any analysis info.
202 void getAnalysisUsage(AnalysisUsage &Info) const {
203 Info.setPreservesAll();
206 inline void addTopLevelPass(Pass *P) {
208 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
210 // P is a immutable pass and it will be managed by this
211 // top level manager. Set up analysis resolver to connect them.
212 AnalysisResolver *AR = new AnalysisResolver(*this);
213 P->setResolver(AR);
214 initializeAnalysisImpl(P);
215 addImmutablePass(IP);
216 recordAvailableAnalysis(IP);
217 } else {
218 P->assignPassManager(activeStack);
223 FPPassManager *getContainedManager(unsigned N) {
224 assert(N < PassManagers.size() && "Pass number out of range!");
225 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
226 return FP;
230 char FunctionPassManagerImpl::ID = 0;
231 //===----------------------------------------------------------------------===//
232 // MPPassManager
234 /// MPPassManager manages ModulePasses and function pass managers.
235 /// It batches all Module passes and function pass managers together and
236 /// sequences them to process one module.
237 class MPPassManager : public Pass, public PMDataManager {
238 public:
239 static char ID;
240 explicit MPPassManager(int Depth) :
241 Pass(&ID), PMDataManager(Depth) { }
243 // Delete on the fly managers.
244 virtual ~MPPassManager() {
245 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
246 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
247 I != E; ++I) {
248 FunctionPassManagerImpl *FPP = I->second;
249 delete FPP;
253 /// run - Execute all of the passes scheduled for execution. Keep track of
254 /// whether any of the passes modifies the module, and if so, return true.
255 bool runOnModule(Module &M);
257 /// Pass Manager itself does not invalidate any analysis info.
258 void getAnalysisUsage(AnalysisUsage &Info) const {
259 Info.setPreservesAll();
262 /// Add RequiredPass into list of lower level passes required by pass P.
263 /// RequiredPass is run on the fly by Pass Manager when P requests it
264 /// through getAnalysis interface.
265 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
267 /// Return function pass corresponding to PassInfo PI, that is
268 /// required by module pass MP. Instantiate analysis pass, by using
269 /// its runOnFunction() for function F.
270 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
272 virtual const char *getPassName() const {
273 return "Module Pass Manager";
276 // Print passes managed by this manager
277 void dumpPassStructure(unsigned Offset) {
278 llvm::errs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
279 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
280 ModulePass *MP = getContainedPass(Index);
281 MP->dumpPassStructure(Offset + 1);
282 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
283 OnTheFlyManagers.find(MP);
284 if (I != OnTheFlyManagers.end())
285 I->second->dumpPassStructure(Offset + 2);
286 dumpLastUses(MP, Offset+1);
290 ModulePass *getContainedPass(unsigned N) {
291 assert(N < PassVector.size() && "Pass number out of range!");
292 return static_cast<ModulePass *>(PassVector[N]);
295 virtual PassManagerType getPassManagerType() const {
296 return PMT_ModulePassManager;
299 private:
300 /// Collection of on the fly FPPassManagers. These managers manage
301 /// function passes that are required by module passes.
302 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
305 char MPPassManager::ID = 0;
306 //===----------------------------------------------------------------------===//
307 // PassManagerImpl
310 /// PassManagerImpl manages MPPassManagers
311 class PassManagerImpl : public Pass,
312 public PMDataManager,
313 public PMTopLevelManager {
315 public:
316 static char ID;
317 explicit PassManagerImpl(int Depth) :
318 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
320 /// add - Add a pass to the queue of passes to run. This passes ownership of
321 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
322 /// will be destroyed as well, so there is no need to delete the pass. This
323 /// implies that all passes MUST be allocated with 'new'.
324 void add(Pass *P) {
325 schedulePass(P);
328 /// run - Execute all of the passes scheduled for execution. Keep track of
329 /// whether any of the passes modifies the module, and if so, return true.
330 bool run(Module &M);
332 /// Pass Manager itself does not invalidate any analysis info.
333 void getAnalysisUsage(AnalysisUsage &Info) const {
334 Info.setPreservesAll();
337 inline void addTopLevelPass(Pass *P) {
338 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
340 // P is a immutable pass and it will be managed by this
341 // top level manager. Set up analysis resolver to connect them.
342 AnalysisResolver *AR = new AnalysisResolver(*this);
343 P->setResolver(AR);
344 initializeAnalysisImpl(P);
345 addImmutablePass(IP);
346 recordAvailableAnalysis(IP);
347 } else {
348 P->assignPassManager(activeStack);
352 MPPassManager *getContainedManager(unsigned N) {
353 assert(N < PassManagers.size() && "Pass number out of range!");
354 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
355 return MP;
359 char PassManagerImpl::ID = 0;
360 } // End of llvm namespace
362 namespace {
364 //===----------------------------------------------------------------------===//
365 /// TimingInfo Class - This class is used to calculate information about the
366 /// amount of time each pass takes to execute. This only happens when
367 /// -time-passes is enabled on the command line.
370 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
372 class VISIBILITY_HIDDEN TimingInfo {
373 std::map<Pass*, Timer> TimingData;
374 TimerGroup TG;
376 public:
377 // Use 'create' member to get this.
378 TimingInfo() : TG("... Pass execution timing report ...") {}
380 // TimingDtor - Print out information about timing information
381 ~TimingInfo() {
382 // Delete all of the timers...
383 TimingData.clear();
384 // TimerGroup is deleted next, printing the report.
387 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
388 // to a non null value (if the -time-passes option is enabled) or it leaves it
389 // null. It may be called multiple times.
390 static void createTheTimeInfo();
392 void passStarted(Pass *P) {
393 if (dynamic_cast<PMDataManager *>(P))
394 return;
396 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
397 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
398 if (I == TimingData.end())
399 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
400 I->second.startTimer();
403 void passEnded(Pass *P) {
404 if (dynamic_cast<PMDataManager *>(P))
405 return;
407 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
408 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
409 assert(I != TimingData.end() && "passStarted/passEnded not nested right!");
410 I->second.stopTimer();
414 } // End of anon namespace
416 static TimingInfo *TheTimeInfo;
418 //===----------------------------------------------------------------------===//
419 // PMTopLevelManager implementation
421 /// Initialize top level manager. Create first pass manager.
422 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
423 if (t == TLM_Pass) {
424 MPPassManager *MPP = new MPPassManager(1);
425 MPP->setTopLevelManager(this);
426 addPassManager(MPP);
427 activeStack.push(MPP);
428 } else if (t == TLM_Function) {
429 FPPassManager *FPP = new FPPassManager(1);
430 FPP->setTopLevelManager(this);
431 addPassManager(FPP);
432 activeStack.push(FPP);
436 /// Set pass P as the last user of the given analysis passes.
437 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
438 Pass *P) {
439 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
440 E = AnalysisPasses.end(); I != E; ++I) {
441 Pass *AP = *I;
442 LastUser[AP] = P;
444 if (P == AP)
445 continue;
447 // If AP is the last user of other passes then make P last user of
448 // such passes.
449 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
450 LUE = LastUser.end(); LUI != LUE; ++LUI) {
451 if (LUI->second == AP)
452 // DenseMap iterator is not invalidated here because
453 // this is just updating exisitng entry.
454 LastUser[LUI->first] = P;
459 /// Collect passes whose last user is P
460 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
461 Pass *P) {
462 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
463 InversedLastUser.find(P);
464 if (DMI == InversedLastUser.end())
465 return;
467 SmallPtrSet<Pass *, 8> &LU = DMI->second;
468 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
469 E = LU.end(); I != E; ++I) {
470 LastUses.push_back(*I);
475 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
476 AnalysisUsage *AnUsage = NULL;
477 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
478 if (DMI != AnUsageMap.end())
479 AnUsage = DMI->second;
480 else {
481 AnUsage = new AnalysisUsage();
482 P->getAnalysisUsage(*AnUsage);
483 AnUsageMap[P] = AnUsage;
485 return AnUsage;
488 /// Schedule pass P for execution. Make sure that passes required by
489 /// P are run before P is run. Update analysis info maintained by
490 /// the manager. Remove dead passes. This is a recursive function.
491 void PMTopLevelManager::schedulePass(Pass *P) {
493 // TODO : Allocate function manager for this pass, other wise required set
494 // may be inserted into previous function manager
496 // Give pass a chance to prepare the stage.
497 P->preparePassManager(activeStack);
499 // If P is an analysis pass and it is available then do not
500 // generate the analysis again. Stale analysis info should not be
501 // available at this point.
502 if (P->getPassInfo() &&
503 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
504 delete P;
505 return;
508 AnalysisUsage *AnUsage = findAnalysisUsage(P);
510 bool checkAnalysis = true;
511 while (checkAnalysis) {
512 checkAnalysis = false;
514 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
515 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
516 E = RequiredSet.end(); I != E; ++I) {
518 Pass *AnalysisPass = findAnalysisPass(*I);
519 if (!AnalysisPass) {
520 AnalysisPass = (*I)->createPass();
521 if (P->getPotentialPassManagerType () ==
522 AnalysisPass->getPotentialPassManagerType())
523 // Schedule analysis pass that is managed by the same pass manager.
524 schedulePass(AnalysisPass);
525 else if (P->getPotentialPassManagerType () >
526 AnalysisPass->getPotentialPassManagerType()) {
527 // Schedule analysis pass that is managed by a new manager.
528 schedulePass(AnalysisPass);
529 // Recheck analysis passes to ensure that required analysises that
530 // are already checked are still available.
531 checkAnalysis = true;
533 else
534 // Do not schedule this analysis. Lower level analsyis
535 // passes are run on the fly.
536 delete AnalysisPass;
541 // Now all required passes are available.
542 addTopLevelPass(P);
545 /// Find the pass that implements Analysis AID. Search immutable
546 /// passes and all pass managers. If desired pass is not found
547 /// then return NULL.
548 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
550 Pass *P = NULL;
551 // Check pass managers
552 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
553 E = PassManagers.end(); P == NULL && I != E; ++I) {
554 PMDataManager *PMD = *I;
555 P = PMD->findAnalysisPass(AID, false);
558 // Check other pass managers
559 for (SmallVector<PMDataManager *, 8>::iterator
560 I = IndirectPassManagers.begin(),
561 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
562 P = (*I)->findAnalysisPass(AID, false);
564 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
565 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
566 const PassInfo *PI = (*I)->getPassInfo();
567 if (PI == AID)
568 P = *I;
570 // If Pass not found then check the interfaces implemented by Immutable Pass
571 if (!P) {
572 const std::vector<const PassInfo*> &ImmPI =
573 PI->getInterfacesImplemented();
574 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
575 P = *I;
579 return P;
582 // Print passes managed by this top level manager.
583 void PMTopLevelManager::dumpPasses() const {
585 if (PassDebugging < Structure)
586 return;
588 // Print out the immutable passes
589 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
590 ImmutablePasses[i]->dumpPassStructure(0);
593 // Every class that derives from PMDataManager also derives from Pass
594 // (sometimes indirectly), but there's no inheritance relationship
595 // between PMDataManager and Pass, so we have to dynamic_cast to get
596 // from a PMDataManager* to a Pass*.
597 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
598 E = PassManagers.end(); I != E; ++I)
599 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
602 void PMTopLevelManager::dumpArguments() const {
604 if (PassDebugging < Arguments)
605 return;
607 errs() << "Pass Arguments: ";
608 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
609 E = PassManagers.end(); I != E; ++I)
610 (*I)->dumpPassArguments();
611 errs() << "\n";
614 void PMTopLevelManager::initializeAllAnalysisInfo() {
615 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
616 E = PassManagers.end(); I != E; ++I)
617 (*I)->initializeAnalysisInfo();
619 // Initailize other pass managers
620 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
621 E = IndirectPassManagers.end(); I != E; ++I)
622 (*I)->initializeAnalysisInfo();
624 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
625 DME = LastUser.end(); DMI != DME; ++DMI) {
626 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
627 InversedLastUser.find(DMI->second);
628 if (InvDMI != InversedLastUser.end()) {
629 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
630 L.insert(DMI->first);
631 } else {
632 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
633 InversedLastUser[DMI->second] = L;
638 /// Destructor
639 PMTopLevelManager::~PMTopLevelManager() {
640 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
641 E = PassManagers.end(); I != E; ++I)
642 delete *I;
644 for (SmallVector<ImmutablePass *, 8>::iterator
645 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
646 delete *I;
648 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
649 DME = AnUsageMap.end(); DMI != DME; ++DMI)
650 delete DMI->second;
653 //===----------------------------------------------------------------------===//
654 // PMDataManager implementation
656 /// Augement AvailableAnalysis by adding analysis made available by pass P.
657 void PMDataManager::recordAvailableAnalysis(Pass *P) {
658 const PassInfo *PI = P->getPassInfo();
659 if (PI == 0) return;
661 AvailableAnalysis[PI] = P;
663 //This pass is the current implementation of all of the interfaces it
664 //implements as well.
665 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
666 for (unsigned i = 0, e = II.size(); i != e; ++i)
667 AvailableAnalysis[II[i]] = P;
670 // Return true if P preserves high level analysis used by other
671 // passes managed by this manager
672 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
673 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
674 if (AnUsage->getPreservesAll())
675 return true;
677 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
678 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
679 E = HigherLevelAnalysis.end(); I != E; ++I) {
680 Pass *P1 = *I;
681 if (!dynamic_cast<ImmutablePass*>(P1) &&
682 std::find(PreservedSet.begin(), PreservedSet.end(),
683 P1->getPassInfo()) ==
684 PreservedSet.end())
685 return false;
688 return true;
691 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
692 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
693 // Don't do this unless assertions are enabled.
694 #ifdef NDEBUG
695 return;
696 #endif
697 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
698 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
700 // Verify preserved analysis
701 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
702 E = PreservedSet.end(); I != E; ++I) {
703 AnalysisID AID = *I;
704 if (Pass *AP = findAnalysisPass(AID, true))
705 AP->verifyAnalysis();
709 /// verifyDomInfo - Verify dominator information if it is available.
710 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
711 if (!VerifyDomInfo || !P.getResolver())
712 return;
714 DominatorTree *DT = P.getAnalysisIfAvailable<DominatorTree>();
715 if (!DT)
716 return;
718 DominatorTree OtherDT;
719 OtherDT.getBase().recalculate(F);
720 if (DT->compare(OtherDT)) {
721 errs() << "Dominator Information for " << F.getName() << "\n";
722 errs() << "Pass '" << P.getPassName() << "'\n";
723 errs() << "----- Valid -----\n";
724 OtherDT.dump();
725 errs() << "----- Invalid -----\n";
726 DT->dump();
727 llvm_unreachable("Invalid dominator info");
730 DominanceFrontier *DF = P.getAnalysisIfAvailable<DominanceFrontier>();
731 if (!DF)
732 return;
734 DominanceFrontier OtherDF;
735 std::vector<BasicBlock*> DTRoots = DT->getRoots();
736 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
737 if (DF->compare(OtherDF)) {
738 errs() << "Dominator Information for " << F.getName() << "\n";
739 errs() << "Pass '" << P.getPassName() << "'\n";
740 errs() << "----- Valid -----\n";
741 OtherDF.dump();
742 errs() << "----- Invalid -----\n";
743 DF->dump();
744 llvm_unreachable("Invalid dominator info");
748 /// Remove Analysis not preserved by Pass P
749 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
750 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
751 if (AnUsage->getPreservesAll())
752 return;
754 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
755 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
756 E = AvailableAnalysis.end(); I != E; ) {
757 std::map<AnalysisID, Pass*>::iterator Info = I++;
758 if (!dynamic_cast<ImmutablePass*>(Info->second)
759 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
760 PreservedSet.end()) {
761 // Remove this analysis
762 if (PassDebugging >= Details) {
763 Pass *S = Info->second;
764 errs() << " -- '" << P->getPassName() << "' is not preserving '";
765 errs() << S->getPassName() << "'\n";
767 AvailableAnalysis.erase(Info);
771 // Check inherited analysis also. If P is not preserving analysis
772 // provided by parent manager then remove it here.
773 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
775 if (!InheritedAnalysis[Index])
776 continue;
778 for (std::map<AnalysisID, Pass*>::iterator
779 I = InheritedAnalysis[Index]->begin(),
780 E = InheritedAnalysis[Index]->end(); I != E; ) {
781 std::map<AnalysisID, Pass *>::iterator Info = I++;
782 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
783 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
784 PreservedSet.end())
785 // Remove this analysis
786 InheritedAnalysis[Index]->erase(Info);
791 /// Remove analysis passes that are not used any longer
792 void PMDataManager::removeDeadPasses(Pass *P, const StringRef &Msg,
793 enum PassDebuggingString DBG_STR) {
795 SmallVector<Pass *, 12> DeadPasses;
797 // If this is a on the fly manager then it does not have TPM.
798 if (!TPM)
799 return;
801 TPM->collectLastUses(DeadPasses, P);
803 if (PassDebugging >= Details && !DeadPasses.empty()) {
804 errs() << " -*- '" << P->getPassName();
805 errs() << "' is the last user of following pass instances.";
806 errs() << " Free these instances\n";
809 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
810 E = DeadPasses.end(); I != E; ++I) {
812 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
815 // If the pass crashes releasing memory, remember this.
816 PassManagerPrettyStackEntry X(*I);
818 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
819 (*I)->releaseMemory();
820 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
822 if (const PassInfo *PI = (*I)->getPassInfo()) {
823 std::map<AnalysisID, Pass*>::iterator Pos =
824 AvailableAnalysis.find(PI);
826 // It is possible that pass is already removed from the AvailableAnalysis
827 if (Pos != AvailableAnalysis.end())
828 AvailableAnalysis.erase(Pos);
830 // Remove all interfaces this pass implements, for which it is also
831 // listed as the available implementation.
832 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
833 for (unsigned i = 0, e = II.size(); i != e; ++i) {
834 Pos = AvailableAnalysis.find(II[i]);
835 if (Pos != AvailableAnalysis.end() && Pos->second == *I)
836 AvailableAnalysis.erase(Pos);
842 /// Add pass P into the PassVector. Update
843 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
844 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
845 // This manager is going to manage pass P. Set up analysis resolver
846 // to connect them.
847 AnalysisResolver *AR = new AnalysisResolver(*this);
848 P->setResolver(AR);
850 // If a FunctionPass F is the last user of ModulePass info M
851 // then the F's manager, not F, records itself as a last user of M.
852 SmallVector<Pass *, 12> TransferLastUses;
854 if (!ProcessAnalysis) {
855 // Add pass
856 PassVector.push_back(P);
857 return;
860 // At the moment, this pass is the last user of all required passes.
861 SmallVector<Pass *, 12> LastUses;
862 SmallVector<Pass *, 8> RequiredPasses;
863 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
865 unsigned PDepth = this->getDepth();
867 collectRequiredAnalysis(RequiredPasses,
868 ReqAnalysisNotAvailable, P);
869 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
870 E = RequiredPasses.end(); I != E; ++I) {
871 Pass *PRequired = *I;
872 unsigned RDepth = 0;
874 assert(PRequired->getResolver() && "Analysis Resolver is not set");
875 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
876 RDepth = DM.getDepth();
878 if (PDepth == RDepth)
879 LastUses.push_back(PRequired);
880 else if (PDepth > RDepth) {
881 // Let the parent claim responsibility of last use
882 TransferLastUses.push_back(PRequired);
883 // Keep track of higher level analysis used by this manager.
884 HigherLevelAnalysis.push_back(PRequired);
885 } else
886 llvm_unreachable("Unable to accomodate Required Pass");
889 // Set P as P's last user until someone starts using P.
890 // However, if P is a Pass Manager then it does not need
891 // to record its last user.
892 if (!dynamic_cast<PMDataManager *>(P))
893 LastUses.push_back(P);
894 TPM->setLastUser(LastUses, P);
896 if (!TransferLastUses.empty()) {
897 Pass *My_PM = dynamic_cast<Pass *>(this);
898 TPM->setLastUser(TransferLastUses, My_PM);
899 TransferLastUses.clear();
902 // Now, take care of required analysises that are not available.
903 for (SmallVector<AnalysisID, 8>::iterator
904 I = ReqAnalysisNotAvailable.begin(),
905 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
906 Pass *AnalysisPass = (*I)->createPass();
907 this->addLowerLevelRequiredPass(P, AnalysisPass);
910 // Take a note of analysis required and made available by this pass.
911 // Remove the analysis not preserved by this pass
912 removeNotPreservedAnalysis(P);
913 recordAvailableAnalysis(P);
915 // Add pass
916 PassVector.push_back(P);
920 /// Populate RP with analysis pass that are required by
921 /// pass P and are available. Populate RP_NotAvail with analysis
922 /// pass that are required by pass P but are not available.
923 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
924 SmallVector<AnalysisID, 8> &RP_NotAvail,
925 Pass *P) {
926 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
927 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
928 for (AnalysisUsage::VectorType::const_iterator
929 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
930 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
931 RP.push_back(AnalysisPass);
932 else
933 RP_NotAvail.push_back(*I);
936 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
937 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
938 E = IDs.end(); I != E; ++I) {
939 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
940 RP.push_back(AnalysisPass);
941 else
942 RP_NotAvail.push_back(*I);
946 // All Required analyses should be available to the pass as it runs! Here
947 // we fill in the AnalysisImpls member of the pass so that it can
948 // successfully use the getAnalysis() method to retrieve the
949 // implementations it needs.
951 void PMDataManager::initializeAnalysisImpl(Pass *P) {
952 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
954 for (AnalysisUsage::VectorType::const_iterator
955 I = AnUsage->getRequiredSet().begin(),
956 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
957 Pass *Impl = findAnalysisPass(*I, true);
958 if (Impl == 0)
959 // This may be analysis pass that is initialized on the fly.
960 // If that is not the case then it will raise an assert when it is used.
961 continue;
962 AnalysisResolver *AR = P->getResolver();
963 assert(AR && "Analysis Resolver is not set");
964 AR->addAnalysisImplsPair(*I, Impl);
968 /// Find the pass that implements Analysis AID. If desired pass is not found
969 /// then return NULL.
970 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
972 // Check if AvailableAnalysis map has one entry.
973 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
975 if (I != AvailableAnalysis.end())
976 return I->second;
978 // Search Parents through TopLevelManager
979 if (SearchParent)
980 return TPM->findAnalysisPass(AID);
982 return NULL;
985 // Print list of passes that are last used by P.
986 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
988 SmallVector<Pass *, 12> LUses;
990 // If this is a on the fly manager then it does not have TPM.
991 if (!TPM)
992 return;
994 TPM->collectLastUses(LUses, P);
996 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
997 E = LUses.end(); I != E; ++I) {
998 llvm::errs() << "--" << std::string(Offset*2, ' ');
999 (*I)->dumpPassStructure(0);
1003 void PMDataManager::dumpPassArguments() const {
1004 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1005 E = PassVector.end(); I != E; ++I) {
1006 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
1007 PMD->dumpPassArguments();
1008 else
1009 if (const PassInfo *PI = (*I)->getPassInfo())
1010 if (!PI->isAnalysisGroup())
1011 errs() << " -" << PI->getPassArgument();
1015 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1016 enum PassDebuggingString S2,
1017 const StringRef &Msg) {
1018 if (PassDebugging < Executions)
1019 return;
1020 errs() << (void*)this << std::string(getDepth()*2+1, ' ');
1021 switch (S1) {
1022 case EXECUTION_MSG:
1023 errs() << "Executing Pass '" << P->getPassName();
1024 break;
1025 case MODIFICATION_MSG:
1026 errs() << "Made Modification '" << P->getPassName();
1027 break;
1028 case FREEING_MSG:
1029 errs() << " Freeing Pass '" << P->getPassName();
1030 break;
1031 default:
1032 break;
1034 switch (S2) {
1035 case ON_BASICBLOCK_MSG:
1036 errs() << "' on BasicBlock '" << Msg << "'...\n";
1037 break;
1038 case ON_FUNCTION_MSG:
1039 errs() << "' on Function '" << Msg << "'...\n";
1040 break;
1041 case ON_MODULE_MSG:
1042 errs() << "' on Module '" << Msg << "'...\n";
1043 break;
1044 case ON_LOOP_MSG:
1045 errs() << "' on Loop " << Msg << "'...\n";
1046 break;
1047 case ON_CG_MSG:
1048 errs() << "' on Call Graph " << Msg << "'...\n";
1049 break;
1050 default:
1051 break;
1055 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1056 if (PassDebugging < Details)
1057 return;
1059 AnalysisUsage analysisUsage;
1060 P->getAnalysisUsage(analysisUsage);
1061 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1064 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1065 if (PassDebugging < Details)
1066 return;
1068 AnalysisUsage analysisUsage;
1069 P->getAnalysisUsage(analysisUsage);
1070 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1073 void PMDataManager::dumpAnalysisUsage(const StringRef &Msg, const Pass *P,
1074 const AnalysisUsage::VectorType &Set) const {
1075 assert(PassDebugging >= Details);
1076 if (Set.empty())
1077 return;
1078 errs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1079 for (unsigned i = 0; i != Set.size(); ++i) {
1080 if (i) errs() << ",";
1081 errs() << " " << Set[i]->getPassName();
1083 errs() << "\n";
1086 /// Add RequiredPass into list of lower level passes required by pass P.
1087 /// RequiredPass is run on the fly by Pass Manager when P requests it
1088 /// through getAnalysis interface.
1089 /// This should be handled by specific pass manager.
1090 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1091 if (TPM) {
1092 TPM->dumpArguments();
1093 TPM->dumpPasses();
1096 // Module Level pass may required Function Level analysis info
1097 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1098 // to provide this on demand. In that case, in Pass manager terminology,
1099 // module level pass is requiring lower level analysis info managed by
1100 // lower level pass manager.
1102 // When Pass manager is not able to order required analysis info, Pass manager
1103 // checks whether any lower level manager will be able to provide this
1104 // analysis info on demand or not.
1105 #ifndef NDEBUG
1106 errs() << "Unable to schedule '" << RequiredPass->getPassName();
1107 errs() << "' required by '" << P->getPassName() << "'\n";
1108 #endif
1109 llvm_unreachable("Unable to schedule pass");
1112 // Destructor
1113 PMDataManager::~PMDataManager() {
1114 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1115 E = PassVector.end(); I != E; ++I)
1116 delete *I;
1119 //===----------------------------------------------------------------------===//
1120 // NOTE: Is this the right place to define this method ?
1121 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1122 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1123 return PM.findAnalysisPass(ID, dir);
1126 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1127 Function &F) {
1128 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1131 //===----------------------------------------------------------------------===//
1132 // BBPassManager implementation
1134 /// Execute all of the passes scheduled for execution by invoking
1135 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1136 /// the function, and if so, return true.
1137 bool BBPassManager::runOnFunction(Function &F) {
1138 if (F.isDeclaration())
1139 return false;
1141 bool Changed = doInitialization(F);
1143 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1144 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1145 BasicBlockPass *BP = getContainedPass(Index);
1147 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1148 dumpRequiredSet(BP);
1150 initializeAnalysisImpl(BP);
1153 // If the pass crashes, remember this.
1154 PassManagerPrettyStackEntry X(BP, *I);
1156 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1157 Changed |= BP->runOnBasicBlock(*I);
1158 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1161 if (Changed)
1162 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1163 I->getName());
1164 dumpPreservedSet(BP);
1166 verifyPreservedAnalysis(BP);
1167 removeNotPreservedAnalysis(BP);
1168 recordAvailableAnalysis(BP);
1169 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1172 return Changed |= doFinalization(F);
1175 // Implement doInitialization and doFinalization
1176 bool BBPassManager::doInitialization(Module &M) {
1177 bool Changed = false;
1179 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1180 Changed |= getContainedPass(Index)->doInitialization(M);
1182 return Changed;
1185 bool BBPassManager::doFinalization(Module &M) {
1186 bool Changed = false;
1188 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1189 Changed |= getContainedPass(Index)->doFinalization(M);
1191 return Changed;
1194 bool BBPassManager::doInitialization(Function &F) {
1195 bool Changed = false;
1197 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1198 BasicBlockPass *BP = getContainedPass(Index);
1199 Changed |= BP->doInitialization(F);
1202 return Changed;
1205 bool BBPassManager::doFinalization(Function &F) {
1206 bool Changed = false;
1208 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1209 BasicBlockPass *BP = getContainedPass(Index);
1210 Changed |= BP->doFinalization(F);
1213 return Changed;
1217 //===----------------------------------------------------------------------===//
1218 // FunctionPassManager implementation
1220 /// Create new Function pass manager
1221 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1222 FPM = new FunctionPassManagerImpl(0);
1223 // FPM is the top level manager.
1224 FPM->setTopLevelManager(FPM);
1226 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1227 FPM->setResolver(AR);
1229 MP = P;
1232 FunctionPassManager::~FunctionPassManager() {
1233 delete FPM;
1236 /// add - Add a pass to the queue of passes to run. This passes
1237 /// ownership of the Pass to the PassManager. When the
1238 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1239 /// there is no need to delete the pass. (TODO delete passes.)
1240 /// This implies that all passes MUST be allocated with 'new'.
1241 void FunctionPassManager::add(Pass *P) {
1242 FPM->add(P);
1245 /// run - Execute all of the passes scheduled for execution. Keep
1246 /// track of whether any of the passes modifies the function, and if
1247 /// so, return true.
1249 bool FunctionPassManager::run(Function &F) {
1250 std::string errstr;
1251 if (MP->materializeFunction(&F, &errstr)) {
1252 llvm_report_error("Error reading bitcode file: " + errstr);
1254 return FPM->run(F);
1258 /// doInitialization - Run all of the initializers for the function passes.
1260 bool FunctionPassManager::doInitialization() {
1261 return FPM->doInitialization(*MP->getModule());
1264 /// doFinalization - Run all of the finalizers for the function passes.
1266 bool FunctionPassManager::doFinalization() {
1267 return FPM->doFinalization(*MP->getModule());
1270 //===----------------------------------------------------------------------===//
1271 // FunctionPassManagerImpl implementation
1273 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1274 bool Changed = false;
1276 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1277 Changed |= getContainedManager(Index)->doInitialization(M);
1279 return Changed;
1282 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1283 bool Changed = false;
1285 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1286 Changed |= getContainedManager(Index)->doFinalization(M);
1288 return Changed;
1291 /// cleanup - After running all passes, clean up pass manager cache.
1292 void FPPassManager::cleanup() {
1293 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1294 FunctionPass *FP = getContainedPass(Index);
1295 AnalysisResolver *AR = FP->getResolver();
1296 assert(AR && "Analysis Resolver is not set");
1297 AR->clearAnalysisImpls();
1301 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1302 if (!wasRun)
1303 return;
1304 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1305 FPPassManager *FPPM = getContainedManager(Index);
1306 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1307 FPPM->getContainedPass(Index)->releaseMemory();
1310 wasRun = false;
1313 // Execute all the passes managed by this top level manager.
1314 // Return true if any function is modified by a pass.
1315 bool FunctionPassManagerImpl::run(Function &F) {
1316 bool Changed = false;
1317 TimingInfo::createTheTimeInfo();
1319 dumpArguments();
1320 dumpPasses();
1322 initializeAllAnalysisInfo();
1323 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1324 Changed |= getContainedManager(Index)->runOnFunction(F);
1326 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1327 getContainedManager(Index)->cleanup();
1329 wasRun = true;
1330 return Changed;
1333 //===----------------------------------------------------------------------===//
1334 // FPPassManager implementation
1336 char FPPassManager::ID = 0;
1337 /// Print passes managed by this manager
1338 void FPPassManager::dumpPassStructure(unsigned Offset) {
1339 llvm::errs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1340 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1341 FunctionPass *FP = getContainedPass(Index);
1342 FP->dumpPassStructure(Offset + 1);
1343 dumpLastUses(FP, Offset+1);
1348 /// Execute all of the passes scheduled for execution by invoking
1349 /// runOnFunction method. Keep track of whether any of the passes modifies
1350 /// the function, and if so, return true.
1351 bool FPPassManager::runOnFunction(Function &F) {
1352 if (F.isDeclaration())
1353 return false;
1355 bool Changed = false;
1357 // Collect inherited analysis from Module level pass manager.
1358 populateInheritedAnalysis(TPM->activeStack);
1360 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1361 FunctionPass *FP = getContainedPass(Index);
1363 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1364 dumpRequiredSet(FP);
1366 initializeAnalysisImpl(FP);
1369 PassManagerPrettyStackEntry X(FP, F);
1371 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1372 Changed |= FP->runOnFunction(F);
1373 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1376 if (Changed)
1377 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1378 dumpPreservedSet(FP);
1380 verifyPreservedAnalysis(FP);
1381 removeNotPreservedAnalysis(FP);
1382 recordAvailableAnalysis(FP);
1383 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1385 // If dominator information is available then verify the info if requested.
1386 verifyDomInfo(*FP, F);
1388 return Changed;
1391 bool FPPassManager::runOnModule(Module &M) {
1392 bool Changed = doInitialization(M);
1394 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1395 runOnFunction(*I);
1397 return Changed |= doFinalization(M);
1400 bool FPPassManager::doInitialization(Module &M) {
1401 bool Changed = false;
1403 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1404 Changed |= getContainedPass(Index)->doInitialization(M);
1406 return Changed;
1409 bool FPPassManager::doFinalization(Module &M) {
1410 bool Changed = false;
1412 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1413 Changed |= getContainedPass(Index)->doFinalization(M);
1415 return Changed;
1418 //===----------------------------------------------------------------------===//
1419 // MPPassManager implementation
1421 /// Execute all of the passes scheduled for execution by invoking
1422 /// runOnModule method. Keep track of whether any of the passes modifies
1423 /// the module, and if so, return true.
1424 bool
1425 MPPassManager::runOnModule(Module &M) {
1426 bool Changed = false;
1428 // Initialize on-the-fly passes
1429 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1430 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1431 I != E; ++I) {
1432 FunctionPassManagerImpl *FPP = I->second;
1433 Changed |= FPP->doInitialization(M);
1436 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1437 ModulePass *MP = getContainedPass(Index);
1439 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1440 M.getModuleIdentifier().c_str());
1441 dumpRequiredSet(MP);
1443 initializeAnalysisImpl(MP);
1446 PassManagerPrettyStackEntry X(MP, M);
1447 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1448 Changed |= MP->runOnModule(M);
1449 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1452 if (Changed)
1453 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1454 M.getModuleIdentifier().c_str());
1455 dumpPreservedSet(MP);
1457 verifyPreservedAnalysis(MP);
1458 removeNotPreservedAnalysis(MP);
1459 recordAvailableAnalysis(MP);
1460 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1463 // Finalize on-the-fly passes
1464 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1465 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1466 I != E; ++I) {
1467 FunctionPassManagerImpl *FPP = I->second;
1468 // We don't know when is the last time an on-the-fly pass is run,
1469 // so we need to releaseMemory / finalize here
1470 FPP->releaseMemoryOnTheFly();
1471 Changed |= FPP->doFinalization(M);
1473 return Changed;
1476 /// Add RequiredPass into list of lower level passes required by pass P.
1477 /// RequiredPass is run on the fly by Pass Manager when P requests it
1478 /// through getAnalysis interface.
1479 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1480 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1481 "Unable to handle Pass that requires lower level Analysis pass");
1482 assert((P->getPotentialPassManagerType() <
1483 RequiredPass->getPotentialPassManagerType()) &&
1484 "Unable to handle Pass that requires lower level Analysis pass");
1486 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1487 if (!FPP) {
1488 FPP = new FunctionPassManagerImpl(0);
1489 // FPP is the top level manager.
1490 FPP->setTopLevelManager(FPP);
1492 OnTheFlyManagers[P] = FPP;
1494 FPP->add(RequiredPass);
1496 // Register P as the last user of RequiredPass.
1497 SmallVector<Pass *, 12> LU;
1498 LU.push_back(RequiredPass);
1499 FPP->setLastUser(LU, P);
1502 /// Return function pass corresponding to PassInfo PI, that is
1503 /// required by module pass MP. Instantiate analysis pass, by using
1504 /// its runOnFunction() for function F.
1505 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1506 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1507 assert(FPP && "Unable to find on the fly pass");
1509 FPP->releaseMemoryOnTheFly();
1510 FPP->run(F);
1511 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1515 //===----------------------------------------------------------------------===//
1516 // PassManagerImpl implementation
1518 /// run - Execute all of the passes scheduled for execution. Keep track of
1519 /// whether any of the passes modifies the module, and if so, return true.
1520 bool PassManagerImpl::run(Module &M) {
1521 bool Changed = false;
1522 TimingInfo::createTheTimeInfo();
1524 dumpArguments();
1525 dumpPasses();
1527 initializeAllAnalysisInfo();
1528 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1529 Changed |= getContainedManager(Index)->runOnModule(M);
1530 return Changed;
1533 //===----------------------------------------------------------------------===//
1534 // PassManager implementation
1536 /// Create new pass manager
1537 PassManager::PassManager() {
1538 PM = new PassManagerImpl(0);
1539 // PM is the top level manager
1540 PM->setTopLevelManager(PM);
1543 PassManager::~PassManager() {
1544 delete PM;
1547 /// add - Add a pass to the queue of passes to run. This passes ownership of
1548 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1549 /// will be destroyed as well, so there is no need to delete the pass. This
1550 /// implies that all passes MUST be allocated with 'new'.
1551 void PassManager::add(Pass *P) {
1552 PM->add(P);
1555 /// run - Execute all of the passes scheduled for execution. Keep track of
1556 /// whether any of the passes modifies the module, and if so, return true.
1557 bool PassManager::run(Module &M) {
1558 return PM->run(M);
1561 //===----------------------------------------------------------------------===//
1562 // TimingInfo Class - This class is used to calculate information about the
1563 // amount of time each pass takes to execute. This only happens with
1564 // -time-passes is enabled on the command line.
1566 bool llvm::TimePassesIsEnabled = false;
1567 static cl::opt<bool,true>
1568 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1569 cl::desc("Time each pass, printing elapsed time for each on exit"));
1571 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1572 // a non null value (if the -time-passes option is enabled) or it leaves it
1573 // null. It may be called multiple times.
1574 void TimingInfo::createTheTimeInfo() {
1575 if (!TimePassesIsEnabled || TheTimeInfo) return;
1577 // Constructed the first time this is called, iff -time-passes is enabled.
1578 // This guarantees that the object will be constructed before static globals,
1579 // thus it will be destroyed before them.
1580 static ManagedStatic<TimingInfo> TTI;
1581 TheTimeInfo = &*TTI;
1584 /// If TimingInfo is enabled then start pass timer.
1585 void llvm::StartPassTimer(Pass *P) {
1586 if (TheTimeInfo)
1587 TheTimeInfo->passStarted(P);
1590 /// If TimingInfo is enabled then stop pass timer.
1591 void llvm::StopPassTimer(Pass *P) {
1592 if (TheTimeInfo)
1593 TheTimeInfo->passEnded(P);
1596 //===----------------------------------------------------------------------===//
1597 // PMStack implementation
1600 // Pop Pass Manager from the stack and clear its analysis info.
1601 void PMStack::pop() {
1603 PMDataManager *Top = this->top();
1604 Top->initializeAnalysisInfo();
1606 S.pop_back();
1609 // Push PM on the stack and set its top level manager.
1610 void PMStack::push(PMDataManager *PM) {
1611 assert(PM && "Unable to push. Pass Manager expected");
1613 if (!this->empty()) {
1614 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1616 assert(TPM && "Unable to find top level manager");
1617 TPM->addIndirectPassManager(PM);
1618 PM->setTopLevelManager(TPM);
1621 S.push_back(PM);
1624 // Dump content of the pass manager stack.
1625 void PMStack::dump() {
1626 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1627 E = S.end(); I != E; ++I)
1628 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1630 if (!S.empty())
1631 printf("\n");
1634 /// Find appropriate Module Pass Manager in the PM Stack and
1635 /// add self into that manager.
1636 void ModulePass::assignPassManager(PMStack &PMS,
1637 PassManagerType PreferredType) {
1638 // Find Module Pass Manager
1639 while(!PMS.empty()) {
1640 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1641 if (TopPMType == PreferredType)
1642 break; // We found desired pass manager
1643 else if (TopPMType > PMT_ModulePassManager)
1644 PMS.pop(); // Pop children pass managers
1645 else
1646 break;
1648 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1649 PMS.top()->add(this);
1652 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1653 /// in the PM Stack and add self into that manager.
1654 void FunctionPass::assignPassManager(PMStack &PMS,
1655 PassManagerType PreferredType) {
1657 // Find Module Pass Manager
1658 while(!PMS.empty()) {
1659 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1660 PMS.pop();
1661 else
1662 break;
1664 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1666 // Create new Function Pass Manager
1667 if (!FPP) {
1668 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1669 PMDataManager *PMD = PMS.top();
1671 // [1] Create new Function Pass Manager
1672 FPP = new FPPassManager(PMD->getDepth() + 1);
1673 FPP->populateInheritedAnalysis(PMS);
1675 // [2] Set up new manager's top level manager
1676 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1677 TPM->addIndirectPassManager(FPP);
1679 // [3] Assign manager to manage this new manager. This may create
1680 // and push new managers into PMS
1681 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1683 // [4] Push new manager into PMS
1684 PMS.push(FPP);
1687 // Assign FPP as the manager of this pass.
1688 FPP->add(this);
1691 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1692 /// in the PM Stack and add self into that manager.
1693 void BasicBlockPass::assignPassManager(PMStack &PMS,
1694 PassManagerType PreferredType) {
1695 BBPassManager *BBP = NULL;
1697 // Basic Pass Manager is a leaf pass manager. It does not handle
1698 // any other pass manager.
1699 if (!PMS.empty())
1700 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1702 // If leaf manager is not Basic Block Pass manager then create new
1703 // basic Block Pass manager.
1705 if (!BBP) {
1706 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1707 PMDataManager *PMD = PMS.top();
1709 // [1] Create new Basic Block Manager
1710 BBP = new BBPassManager(PMD->getDepth() + 1);
1712 // [2] Set up new manager's top level manager
1713 // Basic Block Pass Manager does not live by itself
1714 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1715 TPM->addIndirectPassManager(BBP);
1717 // [3] Assign manager to manage this new manager. This may create
1718 // and push new managers into PMS
1719 BBP->assignPassManager(PMS);
1721 // [4] Push new manager into PMS
1722 PMS.push(BBP);
1725 // Assign BBP as the manager of this pass.
1726 BBP->add(this);
1729 PassManagerBase::~PassManagerBase() {}
1731 /*===-- C Bindings --------------------------------------------------------===*/
1733 LLVMPassManagerRef LLVMCreatePassManager() {
1734 return wrap(new PassManager());
1737 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1738 return wrap(new FunctionPassManager(unwrap(P)));
1741 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1742 return unwrap<PassManager>(PM)->run(*unwrap(M));
1745 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1746 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1749 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1750 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1753 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1754 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1757 void LLVMDisposePassManager(LLVMPassManagerRef PM) {
1758 delete unwrap(PM);