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