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