Update module pass manager to support module passes that require
[oota-llvm.git] / lib / VMCore / PassManager.cpp
1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source 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/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include <algorithm>
23 #include <vector>
24 #include <map>
25
26 // See PassManagers.h for Pass Manager infrastructure overview.
27
28 namespace llvm {
29
30 //===----------------------------------------------------------------------===//
31 // Pass debugging information.  Often it is useful to find out what pass is
32 // running when a crash occurs in a utility.  When this library is compiled with
33 // debugging on, a command line option (--debug-pass) is enabled that causes the
34 // pass name to be printed before it executes.
35 //
36
37 // Different debug levels that can be enabled...
38 enum PassDebugLevel {
39   None, Arguments, Structure, Executions, Details
40 };
41
42 static cl::opt<enum PassDebugLevel>
43 PassDebugging("debug-pass", cl::Hidden,
44                   cl::desc("Print PassManager debugging information"),
45                   cl::values(
46   clEnumVal(None      , "disable debug output"),
47   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
48   clEnumVal(Structure , "print pass structure before run()"),
49   clEnumVal(Executions, "print pass name before it is executed"),
50   clEnumVal(Details   , "print pass details when it is executed"),
51                              clEnumValEnd));
52 } // End of llvm namespace
53
54 namespace {
55
56 //===----------------------------------------------------------------------===//
57 // BBPassManager
58 //
59 /// BBPassManager manages BasicBlockPass. It batches all the
60 /// pass together and sequence them to process one basic block before
61 /// processing next basic block.
62 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager, 
63                                         public FunctionPass {
64
65 public:
66   BBPassManager(int Depth) : PMDataManager(Depth) { }
67
68   /// Execute all of the passes scheduled for execution.  Keep track of
69   /// whether any of the passes modifies the function, and if so, return true.
70   bool runOnFunction(Function &F);
71
72   /// Pass Manager itself does not invalidate any analysis info.
73   void getAnalysisUsage(AnalysisUsage &Info) const {
74     Info.setPreservesAll();
75   }
76
77   bool doInitialization(Module &M);
78   bool doInitialization(Function &F);
79   bool doFinalization(Module &M);
80   bool doFinalization(Function &F);
81
82   virtual const char *getPassName() const {
83     return "BasicBlock Pass  Manager";
84   }
85
86   // Print passes managed by this manager
87   void dumpPassStructure(unsigned Offset) {
88     llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
89     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
90       BasicBlockPass *BP = getContainedPass(Index);
91       BP->dumpPassStructure(Offset + 1);
92       dumpLastUses(BP, Offset+1);
93     }
94   }
95
96   BasicBlockPass *getContainedPass(unsigned N) {
97     assert ( N < PassVector.size() && "Pass number out of range!");
98     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
99     return BP;
100   }
101
102   virtual PassManagerType getPassManagerType() const { 
103     return PMT_BasicBlockPassManager; 
104   }
105 };
106
107 }
108
109 namespace llvm {
110
111 //===----------------------------------------------------------------------===//
112 // FunctionPassManagerImpl
113 //
114 /// FunctionPassManagerImpl manages FPPassManagers
115 class FunctionPassManagerImpl : public Pass,
116                                 public PMDataManager,
117                                 public PMTopLevelManager {
118 public:
119
120   FunctionPassManagerImpl(int Depth) : PMDataManager(Depth),
121                                        PMTopLevelManager(TLM_Function) { }
122
123   /// add - Add a pass to the queue of passes to run.  This passes ownership of
124   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
125   /// will be destroyed as well, so there is no need to delete the pass.  This
126   /// implies that all passes MUST be allocated with 'new'.
127   void add(Pass *P) {
128     schedulePass(P);
129   }
130  
131   /// run - Execute all of the passes scheduled for execution.  Keep track of
132   /// whether any of the passes modifies the module, and if so, return true.
133   bool run(Function &F);
134
135   /// doInitialization - Run all of the initializers for the function passes.
136   ///
137   bool doInitialization(Module &M);
138   
139   /// doFinalization - Run all of the initializers for the function passes.
140   ///
141   bool doFinalization(Module &M);
142
143   /// Pass Manager itself does not invalidate any analysis info.
144   void getAnalysisUsage(AnalysisUsage &Info) const {
145     Info.setPreservesAll();
146   }
147
148   inline void addTopLevelPass(Pass *P) {
149
150     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
151       
152       // P is a immutable pass and it will be managed by this
153       // top level manager. Set up analysis resolver to connect them.
154       AnalysisResolver *AR = new AnalysisResolver(*this);
155       P->setResolver(AR);
156       initializeAnalysisImpl(P);
157       addImmutablePass(IP);
158       recordAvailableAnalysis(IP);
159     } else {
160       P->assignPassManager(activeStack);
161     }
162
163   }
164
165   FPPassManager *getContainedManager(unsigned N) {
166     assert ( N < PassManagers.size() && "Pass number out of range!");
167     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
168     return FP;
169   }
170
171 };
172
173 //===----------------------------------------------------------------------===//
174 // MPPassManager
175 //
176 /// MPPassManager manages ModulePasses and function pass managers.
177 /// It batches all Module passes  passes and function pass managers together and
178 /// sequence them to process one module.
179 class MPPassManager : public Pass, public PMDataManager {
180  
181 public:
182   MPPassManager(int Depth) : PMDataManager(Depth) { }
183   
184   /// run - Execute all of the passes scheduled for execution.  Keep track of
185   /// whether any of the passes modifies the module, and if so, return true.
186   bool runOnModule(Module &M);
187
188   /// Pass Manager itself does not invalidate any analysis info.
189   void getAnalysisUsage(AnalysisUsage &Info) const {
190     Info.setPreservesAll();
191   }
192
193   /// Add RequiredPass into list of lower level passes required by pass P.
194   /// RequiredPass is run on the fly by Pass Manager when P requests it
195   /// through getAnalysis interface.
196   virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
197
198   /// Return function pass corresponding to PassInfo PI, that is 
199   /// required by module pass MP. Instantiate analysis pass, by using
200   /// its runOnFunction() for function F.
201   virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
202
203   virtual const char *getPassName() const {
204     return "Module Pass Manager";
205   }
206
207   // Print passes managed by this manager
208   void dumpPassStructure(unsigned Offset) {
209     llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
210     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
211       ModulePass *MP = getContainedPass(Index);
212       MP->dumpPassStructure(Offset + 1);
213       dumpLastUses(MP, Offset+1);
214     }
215   }
216
217   ModulePass *getContainedPass(unsigned N) {
218     assert ( N < PassVector.size() && "Pass number out of range!");
219     ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
220     return MP;
221   }
222
223   virtual PassManagerType getPassManagerType() const { 
224     return PMT_ModulePassManager; 
225   }
226
227  private:
228   /// Collection of on the fly FPPassManagers. These managers manage
229   /// function passes that are required by module passes.
230   std::map<Pass *, FPPassManager *> OnTheFlyManagers;
231 };
232
233 //===----------------------------------------------------------------------===//
234 // PassManagerImpl
235 //
236 /// PassManagerImpl manages MPPassManagers
237 class PassManagerImpl : public Pass,
238                         public PMDataManager,
239                         public PMTopLevelManager {
240
241 public:
242
243   PassManagerImpl(int Depth) : PMDataManager(Depth),
244                                PMTopLevelManager(TLM_Pass) { }
245
246   /// add - Add a pass to the queue of passes to run.  This passes ownership of
247   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
248   /// will be destroyed as well, so there is no need to delete the pass.  This
249   /// implies that all passes MUST be allocated with 'new'.
250   void add(Pass *P) {
251     schedulePass(P);
252   }
253  
254   /// run - Execute all of the passes scheduled for execution.  Keep track of
255   /// whether any of the passes modifies the module, and if so, return true.
256   bool run(Module &M);
257
258   /// Pass Manager itself does not invalidate any analysis info.
259   void getAnalysisUsage(AnalysisUsage &Info) const {
260     Info.setPreservesAll();
261   }
262
263   inline void addTopLevelPass(Pass *P) {
264
265     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
266       
267       // P is a immutable pass and it will be managed by this
268       // top level manager. Set up analysis resolver to connect them.
269       AnalysisResolver *AR = new AnalysisResolver(*this);
270       P->setResolver(AR);
271       initializeAnalysisImpl(P);
272       addImmutablePass(IP);
273       recordAvailableAnalysis(IP);
274     } else {
275       P->assignPassManager(activeStack);
276     }
277
278   }
279
280   MPPassManager *getContainedManager(unsigned N) {
281     assert ( N < PassManagers.size() && "Pass number out of range!");
282     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
283     return MP;
284   }
285
286 };
287
288 } // End of llvm namespace
289
290 namespace {
291
292 //===----------------------------------------------------------------------===//
293 // TimingInfo Class - This class is used to calculate information about the
294 // amount of time each pass takes to execute.  This only happens when
295 // -time-passes is enabled on the command line.
296 //
297
298 class VISIBILITY_HIDDEN TimingInfo {
299   std::map<Pass*, Timer> TimingData;
300   TimerGroup TG;
301
302 public:
303   // Use 'create' member to get this.
304   TimingInfo() : TG("... Pass execution timing report ...") {}
305   
306   // TimingDtor - Print out information about timing information
307   ~TimingInfo() {
308     // Delete all of the timers...
309     TimingData.clear();
310     // TimerGroup is deleted next, printing the report.
311   }
312
313   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
314   // to a non null value (if the -time-passes option is enabled) or it leaves it
315   // null.  It may be called multiple times.
316   static void createTheTimeInfo();
317
318   void passStarted(Pass *P) {
319
320     if (dynamic_cast<PMDataManager *>(P)) 
321       return;
322
323     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
324     if (I == TimingData.end())
325       I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
326     I->second.startTimer();
327   }
328   void passEnded(Pass *P) {
329
330     if (dynamic_cast<PMDataManager *>(P)) 
331       return;
332
333     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
334     assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
335     I->second.stopTimer();
336   }
337 };
338
339 static TimingInfo *TheTimeInfo;
340
341 } // End of anon namespace
342
343 //===----------------------------------------------------------------------===//
344 // PMTopLevelManager implementation
345
346 /// Initialize top level manager. Create first pass manager.
347 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
348
349   if (t == TLM_Pass) {
350     MPPassManager *MPP = new MPPassManager(1);
351     MPP->setTopLevelManager(this);
352     addPassManager(MPP);
353     activeStack.push(MPP);
354   } 
355   else if (t == TLM_Function) {
356     FPPassManager *FPP = new FPPassManager(1);
357     FPP->setTopLevelManager(this);
358     addPassManager(FPP);
359     activeStack.push(FPP);
360   } 
361 }
362
363 /// Set pass P as the last user of the given analysis passes.
364 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses, 
365                                     Pass *P) {
366
367   for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
368          E = AnalysisPasses.end(); I != E; ++I) {
369     Pass *AP = *I;
370     LastUser[AP] = P;
371     
372     if (P == AP)
373       continue;
374
375     // If AP is the last user of other passes then make P last user of
376     // such passes.
377     for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
378            LUE = LastUser.end(); LUI != LUE; ++LUI) {
379       if (LUI->second == AP)
380         LastUser[LUI->first] = P;
381     }
382   }
383 }
384
385 /// Collect passes whose last user is P
386 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
387                                             Pass *P) {
388    for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
389           LUE = LastUser.end(); LUI != LUE; ++LUI)
390       if (LUI->second == P)
391         LastUses.push_back(LUI->first);
392 }
393
394 /// Schedule pass P for execution. Make sure that passes required by
395 /// P are run before P is run. Update analysis info maintained by
396 /// the manager. Remove dead passes. This is a recursive function.
397 void PMTopLevelManager::schedulePass(Pass *P) {
398
399   // TODO : Allocate function manager for this pass, other wise required set
400   // may be inserted into previous function manager
401
402   // If this Analysis is already requested by one of the previous pass
403   // and it is still available then do not insert new pass in the queue again.
404   if (findAnalysisPass(P->getPassInfo()))
405       return;
406
407   // Give pass a chance to prepare the stage.
408   P->preparePassManager(activeStack);
409
410   AnalysisUsage AnUsage;
411   P->getAnalysisUsage(AnUsage);
412   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
413   for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
414          E = RequiredSet.end(); I != E; ++I) {
415
416     Pass *AnalysisPass = findAnalysisPass(*I);
417     if (!AnalysisPass) {
418       AnalysisPass = (*I)->createPass();
419       // Schedule this analysis run first only if it is not a lower level
420       // analysis pass. Lower level analsyis passes are run on the fly.
421       if (P->getPotentialPassManagerType () >=
422           AnalysisPass->getPotentialPassManagerType())
423         schedulePass(AnalysisPass);
424       else
425         delete AnalysisPass;
426     }
427   }
428
429   // Now all required passes are available.
430   addTopLevelPass(P);
431 }
432
433 /// Find the pass that implements Analysis AID. Search immutable
434 /// passes and all pass managers. If desired pass is not found
435 /// then return NULL.
436 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
437
438   Pass *P = NULL;
439   // Check pass managers
440   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
441          E = PassManagers.end(); P == NULL && I != E; ++I) {
442     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
443     assert(PMD && "This is not a PassManager");
444     P = PMD->findAnalysisPass(AID, false);
445   }
446
447   // Check other pass managers
448   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
449          E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
450     P = (*I)->findAnalysisPass(AID, false);
451
452   for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
453          E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
454     const PassInfo *PI = (*I)->getPassInfo();
455     if (PI == AID)
456       P = *I;
457
458     // If Pass not found then check the interfaces implemented by Immutable Pass
459     if (!P) {
460       const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
461       if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
462         P = *I;
463     }
464   }
465
466   return P;
467 }
468
469 // Print passes managed by this top level manager.
470 void PMTopLevelManager::dumpPasses() const {
471
472   if (PassDebugging < Structure)
473     return;
474
475   // Print out the immutable passes
476   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
477     ImmutablePasses[i]->dumpPassStructure(0);
478   }
479   
480   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
481          E = PassManagers.end(); I != E; ++I)
482     (*I)->dumpPassStructure(1);
483 }
484
485 void PMTopLevelManager::dumpArguments() const {
486
487   if (PassDebugging < Arguments)
488     return;
489
490   cerr << "Pass Arguments: ";
491   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
492          E = PassManagers.end(); I != E; ++I) {
493     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
494     assert(PMD && "This is not a PassManager");
495     PMD->dumpPassArguments();
496   }
497   cerr << "\n";
498 }
499
500 void PMTopLevelManager::initializeAllAnalysisInfo() {
501   
502   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
503          E = PassManagers.end(); I != E; ++I) {
504     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
505     assert(PMD && "This is not a PassManager");
506     PMD->initializeAnalysisInfo();
507   }
508   
509   // Initailize other pass managers
510   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
511          E = IndirectPassManagers.end(); I != E; ++I)
512     (*I)->initializeAnalysisInfo();
513 }
514
515 /// Destructor
516 PMTopLevelManager::~PMTopLevelManager() {
517   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
518          E = PassManagers.end(); I != E; ++I)
519     delete *I;
520   
521   for (std::vector<ImmutablePass *>::iterator
522          I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
523     delete *I;
524   
525   PassManagers.clear();
526 }
527
528 //===----------------------------------------------------------------------===//
529 // PMDataManager implementation
530
531 /// Return true IFF pass P's required analysis set does not required new
532 /// manager.
533 bool PMDataManager::manageablePass(Pass *P) {
534
535   // TODO 
536   // If this pass is not preserving information that is required by a
537   // pass maintained by higher level pass manager then do not insert
538   // this pass into current manager. Use new manager. For example,
539   // For example, If FunctionPass F is not preserving ModulePass Info M1
540   // that is used by another ModulePass M2 then do not insert F in
541   // current function pass manager.
542   return true;
543 }
544
545 /// Augement AvailableAnalysis by adding analysis made available by pass P.
546 void PMDataManager::recordAvailableAnalysis(Pass *P) {
547                                                 
548   if (const PassInfo *PI = P->getPassInfo()) {
549     AvailableAnalysis[PI] = P;
550
551     //This pass is the current implementation of all of the interfaces it
552     //implements as well.
553     const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
554     for (unsigned i = 0, e = II.size(); i != e; ++i)
555       AvailableAnalysis[II[i]] = P;
556   }
557 }
558
559 // Return true if P preserves high level analysis used by other
560 // passes managed by this manager
561 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
562
563   AnalysisUsage AnUsage;
564   P->getAnalysisUsage(AnUsage);
565   
566   if (AnUsage.getPreservesAll())
567     return true;
568   
569   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
570   for (std::vector<Pass *>::iterator I = HigherLevelAnalysis.begin(),
571          E = HigherLevelAnalysis.end(); I  != E; ++I) {
572     Pass *P1 = *I;
573     if (!dynamic_cast<ImmutablePass*>(P1) 
574         && std::find(PreservedSet.begin(), PreservedSet.end(), P1->getPassInfo()) == 
575            PreservedSet.end())
576       return false;
577   }
578   
579   return true;
580 }
581
582 /// Remove Analyss not preserved by Pass P
583 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
584   AnalysisUsage AnUsage;
585   P->getAnalysisUsage(AnUsage);
586
587   if (AnUsage.getPreservesAll())
588     return;
589
590   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
591   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
592          E = AvailableAnalysis.end(); I != E; ) {
593     std::map<AnalysisID, Pass*>::iterator Info = I++;
594     if (!dynamic_cast<ImmutablePass*>(Info->second)
595         && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
596            PreservedSet.end())
597       // Remove this analysis
598       AvailableAnalysis.erase(Info);
599   }
600
601   // Check inherited analysis also. If P is not preserving analysis
602   // provided by parent manager then remove it here.
603   for (unsigned Index = 0; Index < PMT_Last; ++Index) {
604
605     if (!InheritedAnalysis[Index])
606       continue;
607
608     for (std::map<AnalysisID, Pass*>::iterator 
609            I = InheritedAnalysis[Index]->begin(),
610            E = InheritedAnalysis[Index]->end(); I != E; ) {
611       std::map<AnalysisID, Pass *>::iterator Info = I++;
612       if (!dynamic_cast<ImmutablePass*>(Info->second)
613           && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
614              PreservedSet.end())
615         // Remove this analysis
616         InheritedAnalysis[Index]->erase(Info);
617     }
618   }
619
620 }
621
622 /// Remove analysis passes that are not used any longer
623 void PMDataManager::removeDeadPasses(Pass *P, std::string Msg,
624                                      enum PassDebuggingString DBG_STR) {
625
626   std::vector<Pass *> DeadPasses;
627
628   if (!TPM)
629     return;
630
631   TPM->collectLastUses(DeadPasses, P);
632
633   for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
634          E = DeadPasses.end(); I != E; ++I) {
635
636     dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
637
638     if (TheTimeInfo) TheTimeInfo->passStarted(*I);
639     (*I)->releaseMemory();
640     if (TheTimeInfo) TheTimeInfo->passEnded(*I);
641
642     std::map<AnalysisID, Pass*>::iterator Pos = 
643       AvailableAnalysis.find((*I)->getPassInfo());
644     
645     // It is possible that pass is already removed from the AvailableAnalysis
646     if (Pos != AvailableAnalysis.end())
647       AvailableAnalysis.erase(Pos);
648   }
649 }
650
651 /// Add pass P into the PassVector. Update 
652 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
653 void PMDataManager::add(Pass *P, 
654                         bool ProcessAnalysis) {
655
656   // This manager is going to manage pass P. Set up analysis resolver
657   // to connect them.
658   AnalysisResolver *AR = new AnalysisResolver(*this);
659   P->setResolver(AR);
660
661   // If a FunctionPass F is the last user of ModulePass info M
662   // then the F's manager, not F, records itself as a last user of M.
663   std::vector<Pass *> TransferLastUses;
664
665   if (ProcessAnalysis) {
666
667     // At the moment, this pass is the last user of all required passes.
668     std::vector<Pass *> LastUses;
669     SmallVector<Pass *, 8> RequiredPasses;
670     SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
671
672     unsigned PDepth = this->getDepth();
673
674     collectRequiredAnalysis(RequiredPasses, 
675                             ReqAnalysisNotAvailable, P);
676     for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
677            E = RequiredPasses.end(); I != E; ++I) {
678       Pass *PRequired = *I;
679       unsigned RDepth = 0;
680
681       PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
682       RDepth = DM.getDepth();
683
684       if (PDepth == RDepth)
685         LastUses.push_back(PRequired);
686       else if (PDepth >  RDepth) {
687         // Let the parent claim responsibility of last use
688         TransferLastUses.push_back(PRequired);
689         // Keep track of higher level analysis used by this manager.
690         HigherLevelAnalysis.push_back(PRequired);
691       } else 
692         assert (0 && "Unable to accomodate Required Pass");
693     }
694
695     // Set P as P's last user until someone starts using P.
696     // However, if P is a Pass Manager then it does not need
697     // to record its last user.
698     if (!dynamic_cast<PMDataManager *>(P))
699       LastUses.push_back(P);
700     TPM->setLastUser(LastUses, P);
701
702     if (!TransferLastUses.empty()) {
703       Pass *My_PM = dynamic_cast<Pass *>(this);
704       TPM->setLastUser(TransferLastUses, My_PM);
705       TransferLastUses.clear();
706     }
707
708     // Now, take care of required analysises that are not available.
709     for (SmallVector<AnalysisID, 8>::iterator 
710            I = ReqAnalysisNotAvailable.begin(), 
711            E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
712       Pass *AnalysisPass = (*I)->createPass();
713       this->addLowerLevelRequiredPass(P, AnalysisPass);
714     }
715
716     // Take a note of analysis required and made available by this pass.
717     // Remove the analysis not preserved by this pass
718     removeNotPreservedAnalysis(P);
719     recordAvailableAnalysis(P);
720   }
721
722   // Add pass
723   PassVector.push_back(P);
724 }
725
726
727 /// Populate RP with analysis pass that are required by
728 /// pass P and are available. Populate RP_NotAvail with analysis
729 /// pass that are required by pass P but are not available.
730 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
731                                        SmallVector<AnalysisID, 8> &RP_NotAvail,
732                                             Pass *P) {
733   AnalysisUsage AnUsage;
734   P->getAnalysisUsage(AnUsage);
735   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
736   for (std::vector<AnalysisID>::const_iterator 
737          I = RequiredSet.begin(), E = RequiredSet.end();
738        I != E; ++I) {
739     AnalysisID AID = *I;
740     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
741       RP.push_back(AnalysisPass);   
742     else
743       RP_NotAvail.push_back(AID);
744   }
745
746   const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
747   for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
748          E = IDs.end(); I != E; ++I) {
749     AnalysisID AID = *I;
750     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
751       RP.push_back(AnalysisPass);   
752     else
753       RP_NotAvail.push_back(AID);
754   }
755 }
756
757 // All Required analyses should be available to the pass as it runs!  Here
758 // we fill in the AnalysisImpls member of the pass so that it can
759 // successfully use the getAnalysis() method to retrieve the
760 // implementations it needs.
761 //
762 void PMDataManager::initializeAnalysisImpl(Pass *P) {
763   AnalysisUsage AnUsage;
764   P->getAnalysisUsage(AnUsage);
765  
766   for (std::vector<const PassInfo *>::const_iterator
767          I = AnUsage.getRequiredSet().begin(),
768          E = AnUsage.getRequiredSet().end(); I != E; ++I) {
769     Pass *Impl = findAnalysisPass(*I, true);
770     if (Impl == 0)
771       assert(0 && "Analysis used but not available!");
772     AnalysisResolver *AR = P->getResolver();
773     AR->addAnalysisImplsPair(*I, Impl);
774   }
775 }
776
777 /// Find the pass that implements Analysis AID. If desired pass is not found
778 /// then return NULL.
779 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
780
781   // Check if AvailableAnalysis map has one entry.
782   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
783
784   if (I != AvailableAnalysis.end())
785     return I->second;
786
787   // Search Parents through TopLevelManager
788   if (SearchParent)
789     return TPM->findAnalysisPass(AID);
790   
791   return NULL;
792 }
793
794 // Print list of passes that are last used by P.
795 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
796
797   std::vector<Pass *> LUses;
798   
799   assert (TPM && "Top Level Manager is missing");
800   TPM->collectLastUses(LUses, P);
801   
802   for (std::vector<Pass *>::iterator I = LUses.begin(),
803          E = LUses.end(); I != E; ++I) {
804     llvm::cerr << "--" << std::string(Offset*2, ' ');
805     (*I)->dumpPassStructure(0);
806   }
807 }
808
809 void PMDataManager::dumpPassArguments() const {
810   for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
811         E = PassVector.end(); I != E; ++I) {
812     if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
813       PMD->dumpPassArguments();
814     else
815       if (const PassInfo *PI = (*I)->getPassInfo())
816         if (!PI->isAnalysisGroup())
817           cerr << " -" << PI->getPassArgument();
818   }
819 }
820
821 void PMDataManager:: dumpPassInfo(Pass *P, enum PassDebuggingString S1,
822                                   enum PassDebuggingString S2,
823                                   std::string Msg) {
824   if (PassDebugging < Executions)
825     return;
826   cerr << (void*)this << std::string(getDepth()*2+1, ' ');
827   switch (S1) {
828   case EXECUTION_MSG:
829     cerr << "Executing Pass '" << P->getPassName();
830     break;
831   case MODIFICATION_MSG:
832     cerr << "' Made Modification '" << P->getPassName();
833     break;
834   case FREEING_MSG:
835     cerr << " Freeing Pass '" << P->getPassName();
836     break;
837   default:
838     break;
839   }
840   switch (S2) {
841   case ON_BASICBLOCK_MSG:
842     cerr << "' on BasicBlock '" << Msg << "...\n";
843     break;
844   case ON_FUNCTION_MSG:
845     cerr << "' on Function '" << Msg << "...\n";
846     break;
847   case ON_MODULE_MSG:
848     cerr << "' on Module '"  << Msg << "...\n";
849     break;
850   case ON_LOOP_MSG:
851     cerr << "' on Loop " << Msg << "...\n";
852     break;
853   case ON_CG_MSG:
854     cerr << "' on Call Graph " << Msg << "...\n";
855     break;
856   default:
857     break;
858   }
859 }
860
861 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
862                                         const std::vector<AnalysisID> &Set) 
863   const {
864   if (PassDebugging >= Details && !Set.empty()) {
865     cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
866       for (unsigned i = 0; i != Set.size(); ++i) {
867         if (i) cerr << ",";
868         cerr << " " << Set[i]->getPassName();
869       }
870       cerr << "\n";
871   }
872 }
873
874 // Destructor
875 PMDataManager::~PMDataManager() {
876   
877   for (std::vector<Pass *>::iterator I = PassVector.begin(),
878          E = PassVector.end(); I != E; ++I)
879     delete *I;
880   
881   PassVector.clear();
882 }
883
884 //===----------------------------------------------------------------------===//
885 // NOTE: Is this the right place to define this method ?
886 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
887 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
888   return PM.findAnalysisPass(ID, dir);
889 }
890
891 //===----------------------------------------------------------------------===//
892 // BBPassManager implementation
893
894 /// Execute all of the passes scheduled for execution by invoking 
895 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
896 /// the function, and if so, return true.
897 bool
898 BBPassManager::runOnFunction(Function &F) {
899
900   if (F.isDeclaration())
901     return false;
902
903   bool Changed = doInitialization(F);
904
905   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
906     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
907       BasicBlockPass *BP = getContainedPass(Index);
908       AnalysisUsage AnUsage;
909       BP->getAnalysisUsage(AnUsage);
910
911       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
912       dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
913
914       initializeAnalysisImpl(BP);
915
916       if (TheTimeInfo) TheTimeInfo->passStarted(BP);
917       Changed |= BP->runOnBasicBlock(*I);
918       if (TheTimeInfo) TheTimeInfo->passEnded(BP);
919
920       if (Changed) 
921         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
922       dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
923
924       removeNotPreservedAnalysis(BP);
925       recordAvailableAnalysis(BP);
926       removeDeadPasses(BP, (*I).getName(), ON_BASICBLOCK_MSG);
927                        
928     }
929   return Changed |= doFinalization(F);
930 }
931
932 // Implement doInitialization and doFinalization
933 inline bool BBPassManager::doInitialization(Module &M) {
934   bool Changed = false;
935
936   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
937     BasicBlockPass *BP = getContainedPass(Index);
938     Changed |= BP->doInitialization(M);
939   }
940
941   return Changed;
942 }
943
944 inline bool BBPassManager::doFinalization(Module &M) {
945   bool Changed = false;
946
947   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
948     BasicBlockPass *BP = getContainedPass(Index);
949     Changed |= BP->doFinalization(M);
950   }
951
952   return Changed;
953 }
954
955 inline bool BBPassManager::doInitialization(Function &F) {
956   bool Changed = false;
957
958   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
959     BasicBlockPass *BP = getContainedPass(Index);
960     Changed |= BP->doInitialization(F);
961   }
962
963   return Changed;
964 }
965
966 inline bool BBPassManager::doFinalization(Function &F) {
967   bool Changed = false;
968
969   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
970     BasicBlockPass *BP = getContainedPass(Index);
971     Changed |= BP->doFinalization(F);
972   }
973
974   return Changed;
975 }
976
977
978 //===----------------------------------------------------------------------===//
979 // FunctionPassManager implementation
980
981 /// Create new Function pass manager
982 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
983   FPM = new FunctionPassManagerImpl(0);
984   // FPM is the top level manager.
985   FPM->setTopLevelManager(FPM);
986
987   PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
988   AnalysisResolver *AR = new AnalysisResolver(*PMD);
989   FPM->setResolver(AR);
990   
991   MP = P;
992 }
993
994 FunctionPassManager::~FunctionPassManager() {
995   delete FPM;
996 }
997
998 /// add - Add a pass to the queue of passes to run.  This passes
999 /// ownership of the Pass to the PassManager.  When the
1000 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1001 /// there is no need to delete the pass. (TODO delete passes.)
1002 /// This implies that all passes MUST be allocated with 'new'.
1003 void FunctionPassManager::add(Pass *P) { 
1004   FPM->add(P);
1005 }
1006
1007 /// run - Execute all of the passes scheduled for execution.  Keep
1008 /// track of whether any of the passes modifies the function, and if
1009 /// so, return true.
1010 ///
1011 bool FunctionPassManager::run(Function &F) {
1012   std::string errstr;
1013   if (MP->materializeFunction(&F, &errstr)) {
1014     cerr << "Error reading bytecode file: " << errstr << "\n";
1015     abort();
1016   }
1017   return FPM->run(F);
1018 }
1019
1020
1021 /// doInitialization - Run all of the initializers for the function passes.
1022 ///
1023 bool FunctionPassManager::doInitialization() {
1024   return FPM->doInitialization(*MP->getModule());
1025 }
1026
1027 /// doFinalization - Run all of the initializers for the function passes.
1028 ///
1029 bool FunctionPassManager::doFinalization() {
1030   return FPM->doFinalization(*MP->getModule());
1031 }
1032
1033 //===----------------------------------------------------------------------===//
1034 // FunctionPassManagerImpl implementation
1035 //
1036 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1037   bool Changed = false;
1038
1039   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1040     FPPassManager *FP = getContainedManager(Index);
1041     Changed |= FP->doInitialization(M);
1042   }
1043
1044   return Changed;
1045 }
1046
1047 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1048   bool Changed = false;
1049
1050   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1051     FPPassManager *FP = getContainedManager(Index);
1052     Changed |= FP->doFinalization(M);
1053   }
1054
1055   return Changed;
1056 }
1057
1058 // Execute all the passes managed by this top level manager.
1059 // Return true if any function is modified by a pass.
1060 bool FunctionPassManagerImpl::run(Function &F) {
1061
1062   bool Changed = false;
1063
1064   TimingInfo::createTheTimeInfo();
1065
1066   dumpArguments();
1067   dumpPasses();
1068
1069   initializeAllAnalysisInfo();
1070   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1071     FPPassManager *FP = getContainedManager(Index);
1072     Changed |= FP->runOnFunction(F);
1073   }
1074   return Changed;
1075 }
1076
1077 //===----------------------------------------------------------------------===//
1078 // FPPassManager implementation
1079
1080 /// Print passes managed by this manager
1081 void FPPassManager::dumpPassStructure(unsigned Offset) {
1082   llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1083   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1084     FunctionPass *FP = getContainedPass(Index);
1085     FP->dumpPassStructure(Offset + 1);
1086     dumpLastUses(FP, Offset+1);
1087   }
1088 }
1089
1090
1091 /// Execute all of the passes scheduled for execution by invoking 
1092 /// runOnFunction method.  Keep track of whether any of the passes modifies 
1093 /// the function, and if so, return true.
1094 bool FPPassManager::runOnFunction(Function &F) {
1095
1096   bool Changed = false;
1097
1098   if (F.isDeclaration())
1099     return false;
1100
1101   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1102     FunctionPass *FP = getContainedPass(Index);
1103
1104     AnalysisUsage AnUsage;
1105     FP->getAnalysisUsage(AnUsage);
1106
1107     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1108     dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1109
1110     initializeAnalysisImpl(FP);
1111
1112     if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1113     Changed |= FP->runOnFunction(F);
1114     if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1115
1116     if (Changed) 
1117       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1118     dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1119
1120     removeNotPreservedAnalysis(FP);
1121     recordAvailableAnalysis(FP);
1122     removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1123   }
1124   return Changed;
1125 }
1126
1127 bool FPPassManager::runOnModule(Module &M) {
1128
1129   bool Changed = doInitialization(M);
1130
1131   for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1132     this->runOnFunction(*I);
1133
1134   return Changed |= doFinalization(M);
1135 }
1136
1137 inline bool FPPassManager::doInitialization(Module &M) {
1138   bool Changed = false;
1139
1140   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1141     FunctionPass *FP = getContainedPass(Index);
1142     Changed |= FP->doInitialization(M);
1143   }
1144
1145   return Changed;
1146 }
1147
1148 inline bool FPPassManager::doFinalization(Module &M) {
1149   bool Changed = false;
1150
1151   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1152     FunctionPass *FP = getContainedPass(Index);
1153     Changed |= FP->doFinalization(M);
1154   }
1155
1156   return Changed;
1157 }
1158
1159 //===----------------------------------------------------------------------===//
1160 // MPPassManager implementation
1161
1162 /// Execute all of the passes scheduled for execution by invoking 
1163 /// runOnModule method.  Keep track of whether any of the passes modifies 
1164 /// the module, and if so, return true.
1165 bool
1166 MPPassManager::runOnModule(Module &M) {
1167   bool Changed = false;
1168
1169   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1170     ModulePass *MP = getContainedPass(Index);
1171
1172     AnalysisUsage AnUsage;
1173     MP->getAnalysisUsage(AnUsage);
1174
1175     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1176     dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1177
1178     initializeAnalysisImpl(MP);
1179
1180     if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1181     Changed |= MP->runOnModule(M);
1182     if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1183
1184     if (Changed) 
1185       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1186                    M.getModuleIdentifier());
1187     dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1188       
1189     removeNotPreservedAnalysis(MP);
1190     recordAvailableAnalysis(MP);
1191     removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1192   }
1193   return Changed;
1194 }
1195
1196 /// Add RequiredPass into list of lower level passes required by pass P.
1197 /// RequiredPass is run on the fly by Pass Manager when P requests it
1198 /// through getAnalysis interface.
1199 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1200
1201   assert (P->getPotentialPassManagerType() == PMT_ModulePassManager
1202           && "Unable to handle Pass that requires lower level Analysis pass");
1203   assert ((P->getPotentialPassManagerType() < 
1204            RequiredPass->getPotentialPassManagerType())
1205           && "Unable to handle Pass that requires lower level Analysis pass");
1206
1207   FPPassManager *FPP = OnTheFlyManagers[P];
1208   if (!FPP) {
1209     FPP = new FPPassManager(getDepth() + 1);
1210     OnTheFlyManagers[P] = FPP;
1211   }
1212
1213   FPP->add(RequiredPass, false);
1214 }
1215
1216 /// Return function pass corresponding to PassInfo PI, that is 
1217 /// required by module pass MP. Instantiate analysis pass, by using
1218 /// its runOnFunction() for function F.
1219 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, 
1220                                      Function &F) {
1221    AnalysisID AID = PI;
1222   FPPassManager *FPP =OnTheFlyManagers[MP];
1223   assert (FPP && "Unable to find on the fly pass");
1224   
1225   FPP->runOnFunction(F);
1226   return FPP->findAnalysisPass(AID, false);
1227 }
1228
1229
1230 //===----------------------------------------------------------------------===//
1231 // PassManagerImpl implementation
1232 //
1233 /// run - Execute all of the passes scheduled for execution.  Keep track of
1234 /// whether any of the passes modifies the module, and if so, return true.
1235 bool PassManagerImpl::run(Module &M) {
1236
1237   bool Changed = false;
1238
1239   TimingInfo::createTheTimeInfo();
1240
1241   dumpArguments();
1242   dumpPasses();
1243
1244   initializeAllAnalysisInfo();
1245   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1246     MPPassManager *MP = getContainedManager(Index);
1247     Changed |= MP->runOnModule(M);
1248   }
1249   return Changed;
1250 }
1251
1252 //===----------------------------------------------------------------------===//
1253 // PassManager implementation
1254
1255 /// Create new pass manager
1256 PassManager::PassManager() {
1257   PM = new PassManagerImpl(0);
1258   // PM is the top level manager
1259   PM->setTopLevelManager(PM);
1260 }
1261
1262 PassManager::~PassManager() {
1263   delete PM;
1264 }
1265
1266 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1267 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1268 /// will be destroyed as well, so there is no need to delete the pass.  This
1269 /// implies that all passes MUST be allocated with 'new'.
1270 void 
1271 PassManager::add(Pass *P) {
1272   PM->add(P);
1273 }
1274
1275 /// run - Execute all of the passes scheduled for execution.  Keep track of
1276 /// whether any of the passes modifies the module, and if so, return true.
1277 bool
1278 PassManager::run(Module &M) {
1279   return PM->run(M);
1280 }
1281
1282 //===----------------------------------------------------------------------===//
1283 // TimingInfo Class - This class is used to calculate information about the
1284 // amount of time each pass takes to execute.  This only happens with
1285 // -time-passes is enabled on the command line.
1286 //
1287 bool llvm::TimePassesIsEnabled = false;
1288 static cl::opt<bool,true>
1289 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1290             cl::desc("Time each pass, printing elapsed time for each on exit"));
1291
1292 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1293 // a non null value (if the -time-passes option is enabled) or it leaves it
1294 // null.  It may be called multiple times.
1295 void TimingInfo::createTheTimeInfo() {
1296   if (!TimePassesIsEnabled || TheTimeInfo) return;
1297
1298   // Constructed the first time this is called, iff -time-passes is enabled.
1299   // This guarantees that the object will be constructed before static globals,
1300   // thus it will be destroyed before them.
1301   static ManagedStatic<TimingInfo> TTI;
1302   TheTimeInfo = &*TTI;
1303 }
1304
1305 /// If TimingInfo is enabled then start pass timer.
1306 void StartPassTimer(Pass *P) {
1307   if (TheTimeInfo) 
1308     TheTimeInfo->passStarted(P);
1309 }
1310
1311 /// If TimingInfo is enabled then stop pass timer.
1312 void StopPassTimer(Pass *P) {
1313   if (TheTimeInfo) 
1314     TheTimeInfo->passEnded(P);
1315 }
1316
1317 //===----------------------------------------------------------------------===//
1318 // PMStack implementation
1319 //
1320
1321 // Pop Pass Manager from the stack and clear its analysis info.
1322 void PMStack::pop() {
1323
1324   PMDataManager *Top = this->top();
1325   Top->initializeAnalysisInfo();
1326
1327   S.pop_back();
1328 }
1329
1330 // Push PM on the stack and set its top level manager.
1331 void PMStack::push(Pass *P) {
1332
1333   PMDataManager *Top = NULL;
1334   PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1335   assert (PM && "Unable to push. Pass Manager expected");
1336
1337   if (this->empty()) {
1338     Top = PM;
1339   } 
1340   else {
1341     Top = this->top();
1342     PMTopLevelManager *TPM = Top->getTopLevelManager();
1343
1344     assert (TPM && "Unable to find top level manager");
1345     TPM->addIndirectPassManager(PM);
1346     PM->setTopLevelManager(TPM);
1347   }
1348
1349   AnalysisResolver *AR = new AnalysisResolver(*Top);
1350   P->setResolver(AR);
1351
1352   S.push_back(PM);
1353 }
1354
1355 // Dump content of the pass manager stack.
1356 void PMStack::dump() {
1357   for(std::deque<PMDataManager *>::iterator I = S.begin(),
1358         E = S.end(); I != E; ++I) {
1359     Pass *P = dynamic_cast<Pass *>(*I);
1360     printf ("%s ", P->getPassName());
1361   }
1362   if (!S.empty())
1363     printf ("\n");
1364 }
1365
1366 /// Find appropriate Module Pass Manager in the PM Stack and
1367 /// add self into that manager. 
1368 void ModulePass::assignPassManager(PMStack &PMS, 
1369                                    PassManagerType PreferredType) {
1370
1371   // Find Module Pass Manager
1372   while(!PMS.empty()) {
1373     PassManagerType TopPMType = PMS.top()->getPassManagerType();
1374     if (TopPMType == PreferredType)
1375       break; // We found desired pass manager
1376     else if (TopPMType > PMT_ModulePassManager)
1377       PMS.pop();    // Pop children pass managers
1378     else
1379       break;
1380   }
1381
1382   PMS.top()->add(this);
1383 }
1384
1385 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1386 /// in the PM Stack and add self into that manager. 
1387 void FunctionPass::assignPassManager(PMStack &PMS,
1388                                      PassManagerType PreferredType) {
1389
1390   // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1391   while(!PMS.empty()) {
1392     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1393       PMS.pop();
1394     else
1395       break; 
1396   }
1397   FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1398
1399   // Create new Function Pass Manager
1400   if (!FPP) {
1401     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1402     PMDataManager *PMD = PMS.top();
1403
1404     // [1] Create new Function Pass Manager
1405     FPP = new FPPassManager(PMD->getDepth() + 1);
1406
1407     // [2] Set up new manager's top level manager
1408     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1409     TPM->addIndirectPassManager(FPP);
1410
1411     // [3] Assign manager to manage this new manager. This may create
1412     // and push new managers into PMS
1413     Pass *P = dynamic_cast<Pass *>(FPP);
1414
1415     // If Call Graph Pass Manager is active then use it to manage
1416     // this new Function Pass manager.
1417     if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1418       P->assignPassManager(PMS, PMT_CallGraphPassManager);
1419     else
1420       P->assignPassManager(PMS);
1421
1422     // [4] Push new manager into PMS
1423     PMS.push(FPP);
1424   }
1425
1426   // Assign FPP as the manager of this pass.
1427   FPP->add(this);
1428 }
1429
1430 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1431 /// in the PM Stack and add self into that manager. 
1432 void BasicBlockPass::assignPassManager(PMStack &PMS,
1433                                        PassManagerType PreferredType) {
1434
1435   BBPassManager *BBP = NULL;
1436
1437   // Basic Pass Manager is a leaf pass manager. It does not handle
1438   // any other pass manager.
1439   if (!PMS.empty()) {
1440     BBP = dynamic_cast<BBPassManager *>(PMS.top());
1441   }
1442
1443   // If leaf manager is not Basic Block Pass manager then create new
1444   // basic Block Pass manager.
1445
1446   if (!BBP) {
1447     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1448     PMDataManager *PMD = PMS.top();
1449
1450     // [1] Create new Basic Block Manager
1451     BBP = new BBPassManager(PMD->getDepth() + 1);
1452
1453     // [2] Set up new manager's top level manager
1454     // Basic Block Pass Manager does not live by itself
1455     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1456     TPM->addIndirectPassManager(BBP);
1457
1458     // [3] Assign manager to manage this new manager. This may create
1459     // and push new managers into PMS
1460     Pass *P = dynamic_cast<Pass *>(BBP);
1461     P->assignPassManager(PMS);
1462
1463     // [4] Push new manager into PMS
1464     PMS.push(BBP);
1465   }
1466
1467   // Assign BBP as the manager of this pass.
1468   BBP->add(this);
1469 }
1470
1471