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