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