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