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