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