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