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