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