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