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