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