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