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