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