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