"Unable to schedule <A> required by <B>" is more helpful then
[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 } // End of anon namespace
364
365 static TimingInfo *TheTimeInfo;
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 P is an analysis pass and it is available then do not
430   // generate the analysis again. Stale analysis info should not be
431   // available at this point.
432   if (P->getPassInfo() &&
433       P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo()))
434     return;
435
436   AnalysisUsage AnUsage;
437   P->getAnalysisUsage(AnUsage);
438   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
439   for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
440          E = RequiredSet.end(); I != E; ++I) {
441
442     Pass *AnalysisPass = findAnalysisPass(*I);
443     if (!AnalysisPass) {
444       AnalysisPass = (*I)->createPass();
445       // Schedule this analysis run first only if it is not a lower level
446       // analysis pass. Lower level analsyis passes are run on the fly.
447       if (P->getPotentialPassManagerType () >=
448           AnalysisPass->getPotentialPassManagerType())
449         schedulePass(AnalysisPass);
450       else
451         delete AnalysisPass;
452     }
453   }
454
455   // Now all required passes are available.
456   addTopLevelPass(P);
457 }
458
459 /// Find the pass that implements Analysis AID. Search immutable
460 /// passes and all pass managers. If desired pass is not found
461 /// then return NULL.
462 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
463
464   Pass *P = NULL;
465   // Check pass managers
466   for (std::vector<PMDataManager *>::iterator I = PassManagers.begin(),
467          E = PassManagers.end(); P == NULL && I != E; ++I) {
468     PMDataManager *PMD = *I;
469     P = PMD->findAnalysisPass(AID, false);
470   }
471
472   // Check other pass managers
473   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
474          E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
475     P = (*I)->findAnalysisPass(AID, false);
476
477   for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
478          E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
479     const PassInfo *PI = (*I)->getPassInfo();
480     if (PI == AID)
481       P = *I;
482
483     // If Pass not found then check the interfaces implemented by Immutable Pass
484     if (!P) {
485       const std::vector<const PassInfo*> &ImmPI =
486         PI->getInterfacesImplemented();
487       if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
488         P = *I;
489     }
490   }
491
492   return P;
493 }
494
495 // Print passes managed by this top level manager.
496 void PMTopLevelManager::dumpPasses() const {
497
498   if (PassDebugging < Structure)
499     return;
500
501   // Print out the immutable passes
502   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
503     ImmutablePasses[i]->dumpPassStructure(0);
504   }
505   
506   // Every class that derives from PMDataManager also derives from Pass
507   // (sometimes indirectly), but there's no inheritance relationship
508   // between PMDataManager and Pass, so we have to dynamic_cast to get
509   // from a PMDataManager* to a Pass*.
510   for (std::vector<PMDataManager *>::const_iterator I = PassManagers.begin(),
511          E = PassManagers.end(); I != E; ++I)
512     dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
513 }
514
515 void PMTopLevelManager::dumpArguments() const {
516
517   if (PassDebugging < Arguments)
518     return;
519
520   cerr << "Pass Arguments: ";
521   for (std::vector<PMDataManager *>::const_iterator I = PassManagers.begin(),
522          E = PassManagers.end(); I != E; ++I) {
523     PMDataManager *PMD = *I;
524     PMD->dumpPassArguments();
525   }
526   cerr << "\n";
527 }
528
529 void PMTopLevelManager::initializeAllAnalysisInfo() {
530   
531   for (std::vector<PMDataManager *>::iterator I = PassManagers.begin(),
532          E = PassManagers.end(); I != E; ++I) {
533     PMDataManager *PMD = *I;
534     PMD->initializeAnalysisInfo();
535   }
536   
537   // Initailize other pass managers
538   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
539          E = IndirectPassManagers.end(); I != E; ++I)
540     (*I)->initializeAnalysisInfo();
541 }
542
543 /// Destructor
544 PMTopLevelManager::~PMTopLevelManager() {
545   for (std::vector<PMDataManager *>::iterator I = PassManagers.begin(),
546          E = PassManagers.end(); I != E; ++I)
547     delete *I;
548   
549   for (std::vector<ImmutablePass *>::iterator
550          I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
551     delete *I;
552 }
553
554 //===----------------------------------------------------------------------===//
555 // PMDataManager implementation
556
557 /// Augement AvailableAnalysis by adding analysis made available by pass P.
558 void PMDataManager::recordAvailableAnalysis(Pass *P) {
559                                                 
560   if (const PassInfo *PI = P->getPassInfo()) {
561     AvailableAnalysis[PI] = P;
562
563     //This pass is the current implementation of all of the interfaces it
564     //implements as well.
565     const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
566     for (unsigned i = 0, e = II.size(); i != e; ++i)
567       AvailableAnalysis[II[i]] = P;
568   }
569 }
570
571 // Return true if P preserves high level analysis used by other
572 // passes managed by this manager
573 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
574
575   AnalysisUsage AnUsage;
576   P->getAnalysisUsage(AnUsage);
577   
578   if (AnUsage.getPreservesAll())
579     return true;
580   
581   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
582   for (std::vector<Pass *>::iterator I = HigherLevelAnalysis.begin(),
583          E = HigherLevelAnalysis.end(); I  != E; ++I) {
584     Pass *P1 = *I;
585     if (!dynamic_cast<ImmutablePass*>(P1) &&
586         std::find(PreservedSet.begin(), PreservedSet.end(),
587                   P1->getPassInfo()) == 
588            PreservedSet.end())
589       return false;
590   }
591   
592   return true;
593 }
594
595 /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
596 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
597   AnalysisUsage AnUsage;
598   P->getAnalysisUsage(AnUsage);
599   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
600
601   // Verify preserved analysis
602   for (std::vector<AnalysisID>::const_iterator I = PreservedSet.begin(),
603          E = PreservedSet.end(); I != E; ++I) {
604     AnalysisID AID = *I;
605     Pass *AP = findAnalysisPass(AID, true);
606     if (AP)
607       AP->verifyAnalysis();
608   }
609 }
610
611 /// Remove Analyss not preserved by Pass P
612 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
613   AnalysisUsage AnUsage;
614   P->getAnalysisUsage(AnUsage);
615   if (AnUsage.getPreservesAll())
616     return;
617
618   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
619   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
620          E = AvailableAnalysis.end(); I != E; ) {
621     std::map<AnalysisID, Pass*>::iterator Info = I++;
622     if (!dynamic_cast<ImmutablePass*>(Info->second)
623         && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
624         PreservedSet.end()) {
625       // Remove this analysis
626       AvailableAnalysis.erase(Info);
627       if (PassDebugging >= Details) {
628         Pass *S = Info->second;
629         cerr << " -- " <<  P->getPassName() << " is not preserving ";
630         cerr << S->getPassName() << "\n";
631       }
632     }
633   }
634
635   // Check inherited analysis also. If P is not preserving analysis
636   // provided by parent manager then remove it here.
637   for (unsigned Index = 0; Index < PMT_Last; ++Index) {
638
639     if (!InheritedAnalysis[Index])
640       continue;
641
642     for (std::map<AnalysisID, Pass*>::iterator 
643            I = InheritedAnalysis[Index]->begin(),
644            E = InheritedAnalysis[Index]->end(); I != E; ) {
645       std::map<AnalysisID, Pass *>::iterator Info = I++;
646       if (!dynamic_cast<ImmutablePass*>(Info->second) &&
647           std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
648              PreservedSet.end())
649         // Remove this analysis
650         InheritedAnalysis[Index]->erase(Info);
651     }
652   }
653
654 }
655
656 /// Remove analysis passes that are not used any longer
657 void PMDataManager::removeDeadPasses(Pass *P, const char *Msg,
658                                      enum PassDebuggingString DBG_STR) {
659
660   SmallVector<Pass *, 12> DeadPasses;
661
662   // If this is a on the fly manager then it does not have TPM.
663   if (!TPM)
664     return;
665
666   TPM->collectLastUses(DeadPasses, P);
667
668   for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
669          E = DeadPasses.end(); I != E; ++I) {
670
671     dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
672
673     if (TheTimeInfo) TheTimeInfo->passStarted(*I);
674     (*I)->releaseMemory();
675     if (TheTimeInfo) TheTimeInfo->passEnded(*I);
676
677     std::map<AnalysisID, Pass*>::iterator Pos = 
678       AvailableAnalysis.find((*I)->getPassInfo());
679     
680     // It is possible that pass is already removed from the AvailableAnalysis
681     if (Pos != AvailableAnalysis.end())
682       AvailableAnalysis.erase(Pos);
683   }
684 }
685
686 /// Add pass P into the PassVector. Update 
687 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
688 void PMDataManager::add(Pass *P, 
689                         bool ProcessAnalysis) {
690
691   // This manager is going to manage pass P. Set up analysis resolver
692   // to connect them.
693   AnalysisResolver *AR = new AnalysisResolver(*this);
694   P->setResolver(AR);
695
696   // If a FunctionPass F is the last user of ModulePass info M
697   // then the F's manager, not F, records itself as a last user of M.
698   SmallVector<Pass *, 12> TransferLastUses;
699
700   if (ProcessAnalysis) {
701
702     // At the moment, this pass is the last user of all required passes.
703     SmallVector<Pass *, 12> LastUses;
704     SmallVector<Pass *, 8> RequiredPasses;
705     SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
706
707     unsigned PDepth = this->getDepth();
708
709     collectRequiredAnalysis(RequiredPasses, 
710                             ReqAnalysisNotAvailable, P);
711     for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
712            E = RequiredPasses.end(); I != E; ++I) {
713       Pass *PRequired = *I;
714       unsigned RDepth = 0;
715
716       PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
717       RDepth = DM.getDepth();
718
719       if (PDepth == RDepth)
720         LastUses.push_back(PRequired);
721       else if (PDepth >  RDepth) {
722         // Let the parent claim responsibility of last use
723         TransferLastUses.push_back(PRequired);
724         // Keep track of higher level analysis used by this manager.
725         HigherLevelAnalysis.push_back(PRequired);
726       } else 
727         assert (0 && "Unable to accomodate Required Pass");
728     }
729
730     // Set P as P's last user until someone starts using P.
731     // However, if P is a Pass Manager then it does not need
732     // to record its last user.
733     if (!dynamic_cast<PMDataManager *>(P))
734       LastUses.push_back(P);
735     TPM->setLastUser(LastUses, P);
736
737     if (!TransferLastUses.empty()) {
738       Pass *My_PM = dynamic_cast<Pass *>(this);
739       TPM->setLastUser(TransferLastUses, My_PM);
740       TransferLastUses.clear();
741     }
742
743     // Now, take care of required analysises that are not available.
744     for (SmallVector<AnalysisID, 8>::iterator 
745            I = ReqAnalysisNotAvailable.begin(), 
746            E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
747       Pass *AnalysisPass = (*I)->createPass();
748       this->addLowerLevelRequiredPass(P, AnalysisPass);
749     }
750
751     // Take a note of analysis required and made available by this pass.
752     // Remove the analysis not preserved by this pass
753     removeNotPreservedAnalysis(P);
754     recordAvailableAnalysis(P);
755   }
756
757   // Add pass
758   PassVector.push_back(P);
759 }
760
761
762 /// Populate RP with analysis pass that are required by
763 /// pass P and are available. Populate RP_NotAvail with analysis
764 /// pass that are required by pass P but are not available.
765 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
766                                        SmallVector<AnalysisID, 8> &RP_NotAvail,
767                                             Pass *P) {
768   AnalysisUsage AnUsage;
769   P->getAnalysisUsage(AnUsage);
770   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
771   for (std::vector<AnalysisID>::const_iterator 
772          I = RequiredSet.begin(), E = RequiredSet.end();
773        I != E; ++I) {
774     AnalysisID AID = *I;
775     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
776       RP.push_back(AnalysisPass);   
777     else
778       RP_NotAvail.push_back(AID);
779   }
780
781   const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
782   for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
783          E = IDs.end(); I != E; ++I) {
784     AnalysisID AID = *I;
785     if (Pass *AnalysisPass = findAnalysisPass(*I, true))
786       RP.push_back(AnalysisPass);   
787     else
788       RP_NotAvail.push_back(AID);
789   }
790 }
791
792 // All Required analyses should be available to the pass as it runs!  Here
793 // we fill in the AnalysisImpls member of the pass so that it can
794 // successfully use the getAnalysis() method to retrieve the
795 // implementations it needs.
796 //
797 void PMDataManager::initializeAnalysisImpl(Pass *P) {
798   AnalysisUsage AnUsage;
799   P->getAnalysisUsage(AnUsage);
800  
801   for (std::vector<const PassInfo *>::const_iterator
802          I = AnUsage.getRequiredSet().begin(),
803          E = AnUsage.getRequiredSet().end(); I != E; ++I) {
804     Pass *Impl = findAnalysisPass(*I, true);
805     if (Impl == 0)
806       // This may be analysis pass that is initialized on the fly.
807       // If that is not the case then it will raise an assert when it is used.
808       continue;
809     AnalysisResolver *AR = P->getResolver();
810     AR->addAnalysisImplsPair(*I, Impl);
811   }
812 }
813
814 /// Find the pass that implements Analysis AID. If desired pass is not found
815 /// then return NULL.
816 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
817
818   // Check if AvailableAnalysis map has one entry.
819   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
820
821   if (I != AvailableAnalysis.end())
822     return I->second;
823
824   // Search Parents through TopLevelManager
825   if (SearchParent)
826     return TPM->findAnalysisPass(AID);
827   
828   return NULL;
829 }
830
831 // Print list of passes that are last used by P.
832 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
833
834   SmallVector<Pass *, 12> LUses;
835
836   // If this is a on the fly manager then it does not have TPM.
837   if (!TPM)
838     return;
839
840   TPM->collectLastUses(LUses, P);
841   
842   for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
843          E = LUses.end(); I != E; ++I) {
844     llvm::cerr << "--" << std::string(Offset*2, ' ');
845     (*I)->dumpPassStructure(0);
846   }
847 }
848
849 void PMDataManager::dumpPassArguments() const {
850   for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
851         E = PassVector.end(); I != E; ++I) {
852     if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
853       PMD->dumpPassArguments();
854     else
855       if (const PassInfo *PI = (*I)->getPassInfo())
856         if (!PI->isAnalysisGroup())
857           cerr << " -" << PI->getPassArgument();
858   }
859 }
860
861 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
862                                  enum PassDebuggingString S2,
863                                  const char *Msg) {
864   if (PassDebugging < Executions)
865     return;
866   cerr << (void*)this << std::string(getDepth()*2+1, ' ');
867   switch (S1) {
868   case EXECUTION_MSG:
869     cerr << "Executing Pass '" << P->getPassName();
870     break;
871   case MODIFICATION_MSG:
872     cerr << "Made Modification '" << P->getPassName();
873     break;
874   case FREEING_MSG:
875     cerr << " Freeing Pass '" << P->getPassName();
876     break;
877   default:
878     break;
879   }
880   switch (S2) {
881   case ON_BASICBLOCK_MSG:
882     cerr << "' on BasicBlock '" << Msg << "'...\n";
883     break;
884   case ON_FUNCTION_MSG:
885     cerr << "' on Function '" << Msg << "'...\n";
886     break;
887   case ON_MODULE_MSG:
888     cerr << "' on Module '"  << Msg << "'...\n";
889     break;
890   case ON_LOOP_MSG:
891     cerr << "' on Loop " << Msg << "'...\n";
892     break;
893   case ON_CG_MSG:
894     cerr << "' on Call Graph " << Msg << "'...\n";
895     break;
896   default:
897     break;
898   }
899 }
900
901 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
902                                         const std::vector<AnalysisID> &Set) 
903   const {
904   if (PassDebugging >= Details && !Set.empty()) {
905     cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
906       for (unsigned i = 0; i != Set.size(); ++i) {
907         if (i) cerr << ",";
908         cerr << " " << Set[i]->getPassName();
909       }
910       cerr << "\n";
911   }
912 }
913
914 /// Add RequiredPass into list of lower level passes required by pass P.
915 /// RequiredPass is run on the fly by Pass Manager when P requests it
916 /// through getAnalysis interface.
917 /// This should be handled by specific pass manager.
918 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
919   if (TPM) {
920     TPM->dumpArguments();
921     TPM->dumpPasses();
922   }
923
924   // Module Level pass may required Function Level analysis info 
925   // (e.g. dominator info). Pass manager uses on the fly function pass manager 
926   // to provide this on demand. In that case, in Pass manager terminology, 
927   // module level pass is requiring lower level analysis info managed by
928   // lower level pass manager.
929
930   // When Pass manager is not able to order required analysis info, Pass manager
931   // checks whether any lower level manager will be able to provide this 
932   // analysis info on demand or not.
933 #ifndef NDEBUG
934   cerr << "Unable to schedule " << RequiredPass->getPassName();
935   cerr << " required by " << P->getPassName() << "\n";
936 #endif
937   assert (0 && "Unable to schedule pass");
938 }
939
940 // Destructor
941 PMDataManager::~PMDataManager() {
942   
943   for (std::vector<Pass *>::iterator I = PassVector.begin(),
944          E = PassVector.end(); I != E; ++I)
945     delete *I;
946   
947 }
948
949 //===----------------------------------------------------------------------===//
950 // NOTE: Is this the right place to define this method ?
951 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
952 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
953   return PM.findAnalysisPass(ID, dir);
954 }
955
956 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI, 
957                                      Function &F) {
958   return PM.getOnTheFlyPass(P, AnalysisPI, F);
959 }
960
961 //===----------------------------------------------------------------------===//
962 // BBPassManager implementation
963
964 /// Execute all of the passes scheduled for execution by invoking 
965 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
966 /// the function, and if so, return true.
967 bool
968 BBPassManager::runOnFunction(Function &F) {
969
970   if (F.isDeclaration())
971     return false;
972
973   bool Changed = doInitialization(F);
974
975   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
976     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
977       BasicBlockPass *BP = getContainedPass(Index);
978       AnalysisUsage AnUsage;
979       BP->getAnalysisUsage(AnUsage);
980
981       dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getNameStart());
982       dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
983
984       initializeAnalysisImpl(BP);
985
986       if (TheTimeInfo) TheTimeInfo->passStarted(BP);
987       Changed |= BP->runOnBasicBlock(*I);
988       if (TheTimeInfo) TheTimeInfo->passEnded(BP);
989
990       if (Changed) 
991         dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
992                      I->getNameStart());
993       dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
994
995       verifyPreservedAnalysis(BP);
996       removeNotPreservedAnalysis(BP);
997       recordAvailableAnalysis(BP);
998       removeDeadPasses(BP, I->getNameStart(), ON_BASICBLOCK_MSG);
999     }
1000
1001   return Changed |= doFinalization(F);
1002 }
1003
1004 // Implement doInitialization and doFinalization
1005 inline bool BBPassManager::doInitialization(Module &M) {
1006   bool Changed = false;
1007
1008   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1009     BasicBlockPass *BP = getContainedPass(Index);
1010     Changed |= BP->doInitialization(M);
1011   }
1012
1013   return Changed;
1014 }
1015
1016 inline bool BBPassManager::doFinalization(Module &M) {
1017   bool Changed = false;
1018
1019   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1020     BasicBlockPass *BP = getContainedPass(Index);
1021     Changed |= BP->doFinalization(M);
1022   }
1023
1024   return Changed;
1025 }
1026
1027 inline bool BBPassManager::doInitialization(Function &F) {
1028   bool Changed = false;
1029
1030   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1031     BasicBlockPass *BP = getContainedPass(Index);
1032     Changed |= BP->doInitialization(F);
1033   }
1034
1035   return Changed;
1036 }
1037
1038 inline bool BBPassManager::doFinalization(Function &F) {
1039   bool Changed = false;
1040
1041   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1042     BasicBlockPass *BP = getContainedPass(Index);
1043     Changed |= BP->doFinalization(F);
1044   }
1045
1046   return Changed;
1047 }
1048
1049
1050 //===----------------------------------------------------------------------===//
1051 // FunctionPassManager implementation
1052
1053 /// Create new Function pass manager
1054 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1055   FPM = new FunctionPassManagerImpl(0);
1056   // FPM is the top level manager.
1057   FPM->setTopLevelManager(FPM);
1058
1059   AnalysisResolver *AR = new AnalysisResolver(*FPM);
1060   FPM->setResolver(AR);
1061   
1062   MP = P;
1063 }
1064
1065 FunctionPassManager::~FunctionPassManager() {
1066   delete FPM;
1067 }
1068
1069 /// add - Add a pass to the queue of passes to run.  This passes
1070 /// ownership of the Pass to the PassManager.  When the
1071 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1072 /// there is no need to delete the pass. (TODO delete passes.)
1073 /// This implies that all passes MUST be allocated with 'new'.
1074 void FunctionPassManager::add(Pass *P) { 
1075   FPM->add(P);
1076 }
1077
1078 /// run - Execute all of the passes scheduled for execution.  Keep
1079 /// track of whether any of the passes modifies the function, and if
1080 /// so, return true.
1081 ///
1082 bool FunctionPassManager::run(Function &F) {
1083   std::string errstr;
1084   if (MP->materializeFunction(&F, &errstr)) {
1085     cerr << "Error reading bitcode file: " << errstr << "\n";
1086     abort();
1087   }
1088   return FPM->run(F);
1089 }
1090
1091
1092 /// doInitialization - Run all of the initializers for the function passes.
1093 ///
1094 bool FunctionPassManager::doInitialization() {
1095   return FPM->doInitialization(*MP->getModule());
1096 }
1097
1098 /// doFinalization - Run all of the finalizers for the function passes.
1099 ///
1100 bool FunctionPassManager::doFinalization() {
1101   return FPM->doFinalization(*MP->getModule());
1102 }
1103
1104 //===----------------------------------------------------------------------===//
1105 // FunctionPassManagerImpl implementation
1106 //
1107 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1108   bool Changed = false;
1109
1110   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1111     FPPassManager *FP = getContainedManager(Index);
1112     Changed |= FP->doInitialization(M);
1113   }
1114
1115   return Changed;
1116 }
1117
1118 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1119   bool Changed = false;
1120
1121   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1122     FPPassManager *FP = getContainedManager(Index);
1123     Changed |= FP->doFinalization(M);
1124   }
1125
1126   return Changed;
1127 }
1128
1129 // Execute all the passes managed by this top level manager.
1130 // Return true if any function is modified by a pass.
1131 bool FunctionPassManagerImpl::run(Function &F) {
1132
1133   bool Changed = false;
1134
1135   TimingInfo::createTheTimeInfo();
1136
1137   dumpArguments();
1138   dumpPasses();
1139
1140   initializeAllAnalysisInfo();
1141   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1142     FPPassManager *FP = getContainedManager(Index);
1143     Changed |= FP->runOnFunction(F);
1144   }
1145   return Changed;
1146 }
1147
1148 //===----------------------------------------------------------------------===//
1149 // FPPassManager implementation
1150
1151 char FPPassManager::ID = 0;
1152 /// Print passes managed by this manager
1153 void FPPassManager::dumpPassStructure(unsigned Offset) {
1154   llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1155   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1156     FunctionPass *FP = getContainedPass(Index);
1157     FP->dumpPassStructure(Offset + 1);
1158     dumpLastUses(FP, Offset+1);
1159   }
1160 }
1161
1162
1163 /// Execute all of the passes scheduled for execution by invoking 
1164 /// runOnFunction method.  Keep track of whether any of the passes modifies 
1165 /// the function, and if so, return true.
1166 bool FPPassManager::runOnFunction(Function &F) {
1167
1168   bool Changed = false;
1169
1170   if (F.isDeclaration())
1171     return false;
1172   
1173   // Collect inherited analysis from Module level pass manager.
1174   populateInheritedAnalysis(TPM->activeStack);
1175
1176   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1177     FunctionPass *FP = getContainedPass(Index);
1178
1179     AnalysisUsage AnUsage;
1180     FP->getAnalysisUsage(AnUsage);
1181
1182     dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1183     dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1184
1185     initializeAnalysisImpl(FP);
1186
1187     if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1188     Changed |= FP->runOnFunction(F);
1189     if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1190
1191     if (Changed) 
1192       dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1193     dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1194
1195     verifyPreservedAnalysis(FP);
1196     removeNotPreservedAnalysis(FP);
1197     recordAvailableAnalysis(FP);
1198     removeDeadPasses(FP, F.getNameStart(), ON_FUNCTION_MSG);
1199   }
1200   return Changed;
1201 }
1202
1203 bool FPPassManager::runOnModule(Module &M) {
1204
1205   bool Changed = doInitialization(M);
1206
1207   for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1208     this->runOnFunction(*I);
1209
1210   return Changed |= doFinalization(M);
1211 }
1212
1213 inline bool FPPassManager::doInitialization(Module &M) {
1214   bool Changed = false;
1215
1216   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1217     FunctionPass *FP = getContainedPass(Index);
1218     Changed |= FP->doInitialization(M);
1219   }
1220
1221   return Changed;
1222 }
1223
1224 inline bool FPPassManager::doFinalization(Module &M) {
1225   bool Changed = false;
1226
1227   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1228     FunctionPass *FP = getContainedPass(Index);
1229     Changed |= FP->doFinalization(M);
1230   }
1231
1232   return Changed;
1233 }
1234
1235 //===----------------------------------------------------------------------===//
1236 // MPPassManager implementation
1237
1238 /// Execute all of the passes scheduled for execution by invoking 
1239 /// runOnModule method.  Keep track of whether any of the passes modifies 
1240 /// the module, and if so, return true.
1241 bool
1242 MPPassManager::runOnModule(Module &M) {
1243   bool Changed = false;
1244
1245   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1246     ModulePass *MP = getContainedPass(Index);
1247
1248     AnalysisUsage AnUsage;
1249     MP->getAnalysisUsage(AnUsage);
1250
1251     dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1252                  M.getModuleIdentifier().c_str());
1253     dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1254
1255     initializeAnalysisImpl(MP);
1256
1257     if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1258     Changed |= MP->runOnModule(M);
1259     if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1260
1261     if (Changed) 
1262       dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1263                    M.getModuleIdentifier().c_str());
1264     dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1265       
1266     verifyPreservedAnalysis(MP);
1267     removeNotPreservedAnalysis(MP);
1268     recordAvailableAnalysis(MP);
1269     removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1270   }
1271   return Changed;
1272 }
1273
1274 /// Add RequiredPass into list of lower level passes required by pass P.
1275 /// RequiredPass is run on the fly by Pass Manager when P requests it
1276 /// through getAnalysis interface.
1277 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1278
1279   assert (P->getPotentialPassManagerType() == PMT_ModulePassManager
1280           && "Unable to handle Pass that requires lower level Analysis pass");
1281   assert ((P->getPotentialPassManagerType() < 
1282            RequiredPass->getPotentialPassManagerType())
1283           && "Unable to handle Pass that requires lower level Analysis pass");
1284
1285   FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1286   if (!FPP) {
1287     FPP = new FunctionPassManagerImpl(0);
1288     // FPP is the top level manager.
1289     FPP->setTopLevelManager(FPP);
1290
1291     OnTheFlyManagers[P] = FPP;
1292   }
1293   FPP->add(RequiredPass);
1294
1295   // Register P as the last user of RequiredPass.
1296   SmallVector<Pass *, 12> LU;
1297   LU.push_back(RequiredPass);
1298   FPP->setLastUser(LU,  P);
1299 }
1300
1301 /// Return function pass corresponding to PassInfo PI, that is 
1302 /// required by module pass MP. Instantiate analysis pass, by using
1303 /// its runOnFunction() for function F.
1304 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, 
1305                                      Function &F) {
1306    AnalysisID AID = PI;
1307   FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1308   assert (FPP && "Unable to find on the fly pass");
1309   
1310   FPP->run(F);
1311   return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(AID);
1312 }
1313
1314
1315 //===----------------------------------------------------------------------===//
1316 // PassManagerImpl implementation
1317 //
1318 /// run - Execute all of the passes scheduled for execution.  Keep track of
1319 /// whether any of the passes modifies the module, and if so, return true.
1320 bool PassManagerImpl::run(Module &M) {
1321
1322   bool Changed = false;
1323
1324   TimingInfo::createTheTimeInfo();
1325
1326   dumpArguments();
1327   dumpPasses();
1328
1329   initializeAllAnalysisInfo();
1330   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1331     MPPassManager *MP = getContainedManager(Index);
1332     Changed |= MP->runOnModule(M);
1333   }
1334   return Changed;
1335 }
1336
1337 //===----------------------------------------------------------------------===//
1338 // PassManager implementation
1339
1340 /// Create new pass manager
1341 PassManager::PassManager() {
1342   PM = new PassManagerImpl(0);
1343   // PM is the top level manager
1344   PM->setTopLevelManager(PM);
1345 }
1346
1347 PassManager::~PassManager() {
1348   delete PM;
1349 }
1350
1351 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1352 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1353 /// will be destroyed as well, so there is no need to delete the pass.  This
1354 /// implies that all passes MUST be allocated with 'new'.
1355 void 
1356 PassManager::add(Pass *P) {
1357   PM->add(P);
1358 }
1359
1360 /// run - Execute all of the passes scheduled for execution.  Keep track of
1361 /// whether any of the passes modifies the module, and if so, return true.
1362 bool
1363 PassManager::run(Module &M) {
1364   return PM->run(M);
1365 }
1366
1367 //===----------------------------------------------------------------------===//
1368 // TimingInfo Class - This class is used to calculate information about the
1369 // amount of time each pass takes to execute.  This only happens with
1370 // -time-passes is enabled on the command line.
1371 //
1372 bool llvm::TimePassesIsEnabled = false;
1373 static cl::opt<bool,true>
1374 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1375             cl::desc("Time each pass, printing elapsed time for each on exit"));
1376
1377 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1378 // a non null value (if the -time-passes option is enabled) or it leaves it
1379 // null.  It may be called multiple times.
1380 void TimingInfo::createTheTimeInfo() {
1381   if (!TimePassesIsEnabled || TheTimeInfo) return;
1382
1383   // Constructed the first time this is called, iff -time-passes is enabled.
1384   // This guarantees that the object will be constructed before static globals,
1385   // thus it will be destroyed before them.
1386   static ManagedStatic<TimingInfo> TTI;
1387   TheTimeInfo = &*TTI;
1388 }
1389
1390 /// If TimingInfo is enabled then start pass timer.
1391 void StartPassTimer(Pass *P) {
1392   if (TheTimeInfo) 
1393     TheTimeInfo->passStarted(P);
1394 }
1395
1396 /// If TimingInfo is enabled then stop pass timer.
1397 void StopPassTimer(Pass *P) {
1398   if (TheTimeInfo) 
1399     TheTimeInfo->passEnded(P);
1400 }
1401
1402 //===----------------------------------------------------------------------===//
1403 // PMStack implementation
1404 //
1405
1406 // Pop Pass Manager from the stack and clear its analysis info.
1407 void PMStack::pop() {
1408
1409   PMDataManager *Top = this->top();
1410   Top->initializeAnalysisInfo();
1411
1412   S.pop_back();
1413 }
1414
1415 // Push PM on the stack and set its top level manager.
1416 void PMStack::push(PMDataManager *PM) {
1417
1418   PMDataManager *Top = NULL;
1419   assert (PM && "Unable to push. Pass Manager expected");
1420
1421   if (this->empty()) {
1422     Top = PM;
1423   } 
1424   else {
1425     Top = this->top();
1426     PMTopLevelManager *TPM = Top->getTopLevelManager();
1427
1428     assert (TPM && "Unable to find top level manager");
1429     TPM->addIndirectPassManager(PM);
1430     PM->setTopLevelManager(TPM);
1431   }
1432
1433   S.push_back(PM);
1434 }
1435
1436 // Dump content of the pass manager stack.
1437 void PMStack::dump() {
1438   for(std::deque<PMDataManager *>::iterator I = S.begin(),
1439         E = S.end(); I != E; ++I) {
1440     Pass *P = dynamic_cast<Pass *>(*I);
1441     printf("%s ", P->getPassName());
1442   }
1443   if (!S.empty())
1444     printf("\n");
1445 }
1446
1447 /// Find appropriate Module Pass Manager in the PM Stack and
1448 /// add self into that manager. 
1449 void ModulePass::assignPassManager(PMStack &PMS, 
1450                                    PassManagerType PreferredType) {
1451
1452   // Find Module Pass Manager
1453   while(!PMS.empty()) {
1454     PassManagerType TopPMType = PMS.top()->getPassManagerType();
1455     if (TopPMType == PreferredType)
1456       break; // We found desired pass manager
1457     else if (TopPMType > PMT_ModulePassManager)
1458       PMS.pop();    // Pop children pass managers
1459     else
1460       break;
1461   }
1462
1463   PMS.top()->add(this);
1464 }
1465
1466 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1467 /// in the PM Stack and add self into that manager. 
1468 void FunctionPass::assignPassManager(PMStack &PMS,
1469                                      PassManagerType PreferredType) {
1470
1471   // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1472   while(!PMS.empty()) {
1473     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1474       PMS.pop();
1475     else
1476       break; 
1477   }
1478   FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1479
1480   // Create new Function Pass Manager
1481   if (!FPP) {
1482     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1483     PMDataManager *PMD = PMS.top();
1484
1485     // [1] Create new Function Pass Manager
1486     FPP = new FPPassManager(PMD->getDepth() + 1);
1487     FPP->populateInheritedAnalysis(PMS);
1488
1489     // [2] Set up new manager's top level manager
1490     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1491     TPM->addIndirectPassManager(FPP);
1492
1493     // [3] Assign manager to manage this new manager. This may create
1494     // and push new managers into PMS
1495
1496     // If Call Graph Pass Manager is active then use it to manage
1497     // this new Function Pass manager.
1498     if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1499       FPP->assignPassManager(PMS, PMT_CallGraphPassManager);
1500     else
1501       FPP->assignPassManager(PMS);
1502
1503     // [4] Push new manager into PMS
1504     PMS.push(FPP);
1505   }
1506
1507   // Assign FPP as the manager of this pass.
1508   FPP->add(this);
1509 }
1510
1511 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1512 /// in the PM Stack and add self into that manager. 
1513 void BasicBlockPass::assignPassManager(PMStack &PMS,
1514                                        PassManagerType PreferredType) {
1515
1516   BBPassManager *BBP = NULL;
1517
1518   // Basic Pass Manager is a leaf pass manager. It does not handle
1519   // any other pass manager.
1520   if (!PMS.empty())
1521     BBP = dynamic_cast<BBPassManager *>(PMS.top());
1522
1523   // If leaf manager is not Basic Block Pass manager then create new
1524   // basic Block Pass manager.
1525
1526   if (!BBP) {
1527     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1528     PMDataManager *PMD = PMS.top();
1529
1530     // [1] Create new Basic Block Manager
1531     BBP = new BBPassManager(PMD->getDepth() + 1);
1532
1533     // [2] Set up new manager's top level manager
1534     // Basic Block Pass Manager does not live by itself
1535     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1536     TPM->addIndirectPassManager(BBP);
1537
1538     // [3] Assign manager to manage this new manager. This may create
1539     // and push new managers into PMS
1540     BBP->assignPassManager(PMS);
1541
1542     // [4] Push new manager into PMS
1543     PMS.push(BBP);
1544   }
1545
1546   // Assign BBP as the manager of this pass.
1547   BBP->add(this);
1548 }
1549
1550 PassManagerBase::~PassManagerBase() {}
1551   
1552 /*===-- C Bindings --------------------------------------------------------===*/
1553
1554 LLVMPassManagerRef LLVMCreatePassManager() {
1555   return wrap(new PassManager());
1556 }
1557
1558 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1559   return wrap(new FunctionPassManager(unwrap(P)));
1560 }
1561
1562 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1563   return unwrap<PassManager>(PM)->run(*unwrap(M));
1564 }
1565
1566 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1567   return unwrap<FunctionPassManager>(FPM)->doInitialization();
1568 }
1569
1570 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1571   return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1572 }
1573
1574 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1575   return unwrap<FunctionPassManager>(FPM)->doFinalization();
1576 }
1577
1578 void LLVMDisposePassManager(LLVMPassManagerRef PM) {
1579   delete unwrap(PM);
1580 }