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