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