Add #ifdef switch toggle between old and new pass manager. However,
[oota-llvm.git] / lib / VMCore / PassManager.cpp
1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source 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/PassManager.h"
16 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/Support/Streams.h"
19 #include <vector>
20 #include <map>
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // Overview:
25 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
26 // 
27 //   o Manage optimization pass execution order
28 //   o Make required Analysis information available before pass P is run
29 //   o Release memory occupied by dead passes
30 //   o If Analysis information is dirtied by a pass then regenerate Analysis 
31 //     information before it is consumed by another pass.
32 //
33 // Pass Manager Infrastructure uses multipe pass managers. They are PassManager,
34 // FunctionPassManager, ModulePassManager, BasicBlockPassManager. This class 
35 // hierarcy uses multiple inheritance but pass managers do not derive from
36 // another pass manager.
37 //
38 // PassManager and FunctionPassManager are two top level pass manager that
39 // represents the external interface of this entire pass manager infrastucture.
40 //
41 // Important classes :
42 //
43 // [o] class PMTopLevelManager;
44 //
45 // Two top level managers, PassManager and FunctionPassManager, derive from 
46 // PMTopLevelManager. PMTopLevelManager manages information used by top level 
47 // managers such as last user info.
48 //
49 // [o] class PMDataManager;
50 //
51 // PMDataManager manages information, e.g. list of available analysis info, 
52 // used by a pass manager to manage execution order of passes. It also provides
53 // a place to implement common pass manager APIs. All pass managers derive from
54 // PMDataManager.
55 //
56 // [o] class BasicBlockPassManager : public FunctionPass, public PMDataManager;
57 //
58 // BasicBlockPassManager manages BasicBlockPasses.
59 //
60 // [o] class FunctionPassManager;
61 //
62 // This is a external interface used by JIT to manage FunctionPasses. This
63 // interface relies on FunctionPassManagerImpl to do all the tasks.
64 //
65 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
66 //                                     public PMTopLevelManager;
67 //
68 // FunctionPassManagerImpl is a top level manager. It manages FunctionPasses
69 // and BasicBlockPassManagers.
70 //
71 // [o] class ModulePassManager : public Pass, public PMDataManager;
72 //
73 // ModulePassManager manages ModulePasses and FunctionPassManagerImpls.
74 //
75 // [o] class PassManager;
76 //
77 // This is a external interface used by various tools to manages passes. It
78 // relies on PassManagerImpl to do all the tasks.
79 //
80 // [o] class PassManagerImpl : public Pass, public PMDataManager,
81 //                             public PMDTopLevelManager
82 //
83 // PassManagerImpl is a top level pass manager responsible for managing
84 // ModulePassManagers.
85 //===----------------------------------------------------------------------===//
86
87 #ifndef USE_OLD_PASSMANAGER
88 namespace llvm {
89
90 class PMDataManager;
91
92 //===----------------------------------------------------------------------===//
93 // PMTopLevelManager
94 //
95 /// PMTopLevelManager manages LastUser info and collects common APIs used by
96 /// top level pass managers.
97 class PMTopLevelManager {
98
99 public:
100
101   inline std::vector<Pass *>::iterator passManagersBegin() { 
102     return PassManagers.begin(); 
103   }
104
105   inline std::vector<Pass *>::iterator passManagersEnd() { 
106     return PassManagers.end();
107   }
108
109   /// Schedule pass P for execution. Make sure that passes required by
110   /// P are run before P is run. Update analysis info maintained by
111   /// the manager. Remove dead passes. This is a recursive function.
112   void schedulePass(Pass *P);
113
114   /// This is implemented by top level pass manager and used by 
115   /// schedulePass() to add analysis info passes that are not available.
116   virtual void addTopLevelPass(Pass  *P) = 0;
117
118   /// Set pass P as the last user of the given analysis passes.
119   void setLastUser(std::vector<Pass *> &AnalysisPasses, Pass *P);
120
121   /// Collect passes whose last user is P
122   void collectLastUses(std::vector<Pass *> &LastUses, Pass *P);
123
124   /// Find the pass that implements Analysis AID. Search immutable
125   /// passes and all pass managers. If desired pass is not found
126   /// then return NULL.
127   Pass *findAnalysisPass(AnalysisID AID);
128
129   inline void clearManagers() { 
130     PassManagers.clear();
131   }
132
133   virtual ~PMTopLevelManager() {
134
135     for (std::vector<Pass *>::iterator I = PassManagers.begin(),
136            E = PassManagers.end(); I != E; ++I)
137       delete *I;
138
139     for (std::vector<ImmutablePass *>::iterator
140            I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
141       delete *I;
142
143     PassManagers.clear();
144   }
145
146   /// Add immutable pass and initialize it.
147   inline void addImmutablePass(ImmutablePass *P) {
148     P->initializePass();
149     ImmutablePasses.push_back(P);
150   }
151
152   inline std::vector<ImmutablePass *>& getImmutablePasses() {
153     return ImmutablePasses;
154   }
155
156   void addPassManager(Pass *Manager) {
157     PassManagers.push_back(Manager);
158   }
159
160   // Add Manager into the list of managers that are not directly
161   // maintained by this top level pass manager
162   inline void addIndirectPassManager(PMDataManager *Manager) {
163     IndirectPassManagers.push_back(Manager);
164   }
165
166   // Print passes managed by this top level manager.
167   void dumpPasses();
168
169 private:
170   
171   /// Collection of pass managers
172   std::vector<Pass *> PassManagers;
173
174   /// Collection of pass managers that are not directly maintained
175   /// by this pass manager
176   std::vector<PMDataManager *> IndirectPassManagers;
177
178   // Map to keep track of last user of the analysis pass.
179   // LastUser->second is the last user of Lastuser->first.
180   std::map<Pass *, Pass *> LastUser;
181
182   /// Immutable passes are managed by top level manager.
183   std::vector<ImmutablePass *> ImmutablePasses;
184 };
185   
186 //===----------------------------------------------------------------------===//
187 // PMDataManager
188
189 /// PMDataManager provides the common place to manage the analysis data
190 /// used by pass managers.
191 class PMDataManager {
192
193 public:
194
195   PMDataManager(int D) : TPM(NULL), Depth(D) {
196     initializeAnalysisInfo();
197   }
198
199   virtual ~PMDataManager() {
200
201     for (std::vector<Pass *>::iterator I = PassVector.begin(),
202            E = PassVector.end(); I != E; ++I)
203       delete *I;
204
205     PassVector.clear();
206   }
207
208   /// Return true IFF pass P's required analysis set does not required new
209   /// manager.
210   bool manageablePass(Pass *P);
211
212   /// Augment AvailableAnalysis by adding analysis made available by pass P.
213   void recordAvailableAnalysis(Pass *P);
214
215   /// Remove Analysis that is not preserved by the pass
216   void removeNotPreservedAnalysis(Pass *P);
217   
218   /// Remove dead passes
219   void removeDeadPasses(Pass *P);
220
221   /// Add pass P into the PassVector. Update 
222   /// AvailableAnalysis appropriately if ProcessAnalysis is true.
223   void addPassToManager (Pass *P, bool ProcessAnalysis = true);
224
225   /// Initialize available analysis information.
226   void initializeAnalysisInfo() { 
227     ForcedLastUses.clear();
228     AvailableAnalysis.clear();
229   }
230
231   /// Populate RequiredPasses with the analysis pass that are required by
232   /// pass P.
233   void collectRequiredAnalysisPasses(std::vector<Pass *> &RequiredPasses,
234                                      Pass *P);
235
236   /// All Required analyses should be available to the pass as it runs!  Here
237   /// we fill in the AnalysisImpls member of the pass so that it can
238   /// successfully use the getAnalysis() method to retrieve the
239   /// implementations it needs.
240   void initializeAnalysisImpl(Pass *P);
241
242   /// Find the pass that implements Analysis AID. If desired pass is not found
243   /// then return NULL.
244   Pass *findAnalysisPass(AnalysisID AID, bool Direction);
245
246   inline std::vector<Pass *>::iterator passVectorBegin() { 
247     return PassVector.begin(); 
248   }
249
250   inline std::vector<Pass *>::iterator passVectorEnd() { 
251     return PassVector.end();
252   }
253
254   // Access toplevel manager
255   PMTopLevelManager *getTopLevelManager() { return TPM; }
256   void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
257
258   unsigned getDepth() { return Depth; }
259
260   // Print list of passes that are last used by P.
261   void dumpLastUses(Pass *P, unsigned Offset) {
262     
263     std::vector<Pass *> LUses;
264
265     assert (TPM && "Top Level Manager is missing");
266     TPM->collectLastUses(LUses, P);
267     
268     for (std::vector<Pass *>::iterator I = LUses.begin(),
269            E = LUses.end(); I != E; ++I) {
270       llvm::cerr << "--" << std::string(Offset*2, ' ');
271       (*I)->dumpPassStructure(0);
272     }
273   }
274
275 protected:
276
277   // Collection of pass whose last user asked this manager to claim
278   // last use. If a FunctionPass F is the last user of ModulePass info M
279   // then the F's manager, not F, records itself as a last user of M.
280   std::vector<Pass *> ForcedLastUses;
281
282   // Top level manager.
283   PMTopLevelManager *TPM;
284
285 private:
286   // Set of available Analysis. This information is used while scheduling 
287   // pass. If a pass requires an analysis which is not not available then 
288   // equired analysis pass is scheduled to run before the pass itself is 
289   // scheduled to run.
290   std::map<AnalysisID, Pass*> AvailableAnalysis;
291
292   // Collection of pass that are managed by this manager
293   std::vector<Pass *> PassVector;
294
295   unsigned Depth;
296 };
297
298 //===----------------------------------------------------------------------===//
299 // BasicBlockPassManager
300 //
301 /// BasicBlockPassManager manages BasicBlockPass. It batches all the
302 /// pass together and sequence them to process one basic block before
303 /// processing next basic block.
304 class BasicBlockPassManager : public PMDataManager, 
305                                   public FunctionPass {
306
307 public:
308   BasicBlockPassManager(int D) : PMDataManager(D) { }
309
310   /// Add a pass into a passmanager queue. 
311   bool addPass(Pass *p);
312   
313   /// Execute all of the passes scheduled for execution.  Keep track of
314   /// whether any of the passes modifies the function, and if so, return true.
315   bool runOnFunction(Function &F);
316
317   /// Pass Manager itself does not invalidate any analysis info.
318   void getAnalysisUsage(AnalysisUsage &Info) const {
319     Info.setPreservesAll();
320   }
321
322   bool doInitialization(Module &M);
323   bool doInitialization(Function &F);
324   bool doFinalization(Module &M);
325   bool doFinalization(Function &F);
326
327   // Print passes managed by this manager
328   void dumpPassStructure(unsigned Offset) {
329     llvm::cerr << std::string(Offset*2, ' ') << "BasicBLockPass Manager\n";
330     for (std::vector<Pass *>::iterator I = passVectorBegin(),
331            E = passVectorEnd(); I != E; ++I)  {
332       (*I)->dumpPassStructure(Offset + 1);
333       dumpLastUses(*I, Offset+1);
334     }
335   }
336
337 };
338
339 //===----------------------------------------------------------------------===//
340 // FunctionPassManagerImpl_New
341 //
342 /// FunctionPassManagerImpl_New manages FunctionPasses and BasicBlockPassManagers.
343 /// It batches all function passes and basic block pass managers together and
344 /// sequence them to process one function at a time before processing next
345 /// function.
346 class FunctionPassManagerImpl_New : public ModulePass, 
347                                     public PMDataManager,
348                                     public PMTopLevelManager {
349 public:
350   FunctionPassManagerImpl_New(int D) : PMDataManager(D) { 
351     activeBBPassManager = NULL;
352   }
353   ~FunctionPassManagerImpl_New() { /* TODO */ };
354  
355   inline void addTopLevelPass(Pass *P) { 
356
357     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
358
359       // P is a immutable pass then it will be managed by this
360       // top level manager. Set up analysis resolver to connect them.
361       AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
362       P->setResolver(AR);
363       initializeAnalysisImpl(P);
364       addImmutablePass(IP);
365       recordAvailableAnalysis(IP);
366     } 
367     else 
368       addPass(P);
369   }
370
371   /// add - Add a pass to the queue of passes to run.  This passes
372   /// ownership of the Pass to the PassManager.  When the
373   /// PassManager_X is destroyed, the pass will be destroyed as well, so
374   /// there is no need to delete the pass. (TODO delete passes.)
375   /// This implies that all passes MUST be allocated with 'new'.
376   void add(Pass *P) { 
377     schedulePass(P);
378   }
379
380   /// Add pass into the pass manager queue.
381   bool addPass(Pass *P);
382
383   /// Execute all of the passes scheduled for execution.  Keep
384   /// track of whether any of the passes modifies the function, and if
385   /// so, return true.
386   bool runOnModule(Module &M);
387   bool runOnFunction(Function &F);
388   bool run(Function &F);
389
390   /// doInitialization - Run all of the initializers for the function passes.
391   ///
392   bool doInitialization(Module &M);
393   
394   /// doFinalization - Run all of the initializers for the function passes.
395   ///
396   bool doFinalization(Module &M);
397
398   /// Pass Manager itself does not invalidate any analysis info.
399   void getAnalysisUsage(AnalysisUsage &Info) const {
400     Info.setPreservesAll();
401   }
402
403   // Print passes managed by this manager
404   void dumpPassStructure(unsigned Offset) {
405     llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
406     for (std::vector<Pass *>::iterator I = passVectorBegin(),
407            E = passVectorEnd(); I != E; ++I)  {
408       (*I)->dumpPassStructure(Offset + 1);
409       dumpLastUses(*I, Offset+1);
410     }
411   }
412
413 private:
414   // Active Pass Managers
415   BasicBlockPassManager *activeBBPassManager;
416 };
417
418 //===----------------------------------------------------------------------===//
419 // ModulePassManager
420 //
421 /// ModulePassManager manages ModulePasses and function pass managers.
422 /// It batches all Module passes  passes and function pass managers together and
423 /// sequence them to process one module.
424 class ModulePassManager : public Pass,
425                               public PMDataManager {
426  
427 public:
428   ModulePassManager(int D) : PMDataManager(D) { 
429     activeFunctionPassManager = NULL; 
430   }
431   
432   /// Add a pass into a passmanager queue. 
433   bool addPass(Pass *p);
434   
435   /// run - Execute all of the passes scheduled for execution.  Keep track of
436   /// whether any of the passes modifies the module, and if so, return true.
437   bool runOnModule(Module &M);
438
439   /// Pass Manager itself does not invalidate any analysis info.
440   void getAnalysisUsage(AnalysisUsage &Info) const {
441     Info.setPreservesAll();
442   }
443
444   // Print passes managed by this manager
445   void dumpPassStructure(unsigned Offset) {
446     llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
447     for (std::vector<Pass *>::iterator I = passVectorBegin(),
448            E = passVectorEnd(); I != E; ++I)  {
449       (*I)->dumpPassStructure(Offset + 1);
450       dumpLastUses(*I, Offset+1);
451     }
452   }
453
454 private:
455   // Active Pass Manager
456   FunctionPassManagerImpl_New *activeFunctionPassManager;
457 };
458
459 //===----------------------------------------------------------------------===//
460 // PassManagerImpl_New
461 //
462 /// PassManagerImpl_New manages ModulePassManagers
463 class PassManagerImpl_New : public Pass,
464                             public PMDataManager,
465                             public PMTopLevelManager {
466
467 public:
468
469   PassManagerImpl_New(int D) : PMDataManager(D) {
470     activeManager = NULL;
471   }
472
473   /// add - Add a pass to the queue of passes to run.  This passes ownership of
474   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
475   /// will be destroyed as well, so there is no need to delete the pass.  This
476   /// implies that all passes MUST be allocated with 'new'.
477   void add(Pass *P) {
478     schedulePass(P);
479   }
480  
481   /// run - Execute all of the passes scheduled for execution.  Keep track of
482   /// whether any of the passes modifies the module, and if so, return true.
483   bool run(Module &M);
484
485   /// Pass Manager itself does not invalidate any analysis info.
486   void getAnalysisUsage(AnalysisUsage &Info) const {
487     Info.setPreservesAll();
488   }
489
490   inline void addTopLevelPass(Pass *P) {
491
492     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
493       
494       // P is a immutable pass and it will be managed by this
495       // top level manager. Set up analysis resolver to connect them.
496       AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
497       P->setResolver(AR);
498       initializeAnalysisImpl(P);
499       addImmutablePass(IP);
500       recordAvailableAnalysis(IP);
501     }
502     else 
503       addPass(P);
504   }
505
506 private:
507
508   /// Add a pass into a passmanager queue.
509   bool addPass(Pass *p);
510
511   // Active Pass Manager
512   ModulePassManager *activeManager;
513 };
514
515 } // End of llvm namespace
516
517 //===----------------------------------------------------------------------===//
518 // PMTopLevelManager implementation
519
520 /// Set pass P as the last user of the given analysis passes.
521 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses, 
522                                     Pass *P) {
523
524   for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
525          E = AnalysisPasses.end(); I != E; ++I) {
526     Pass *AP = *I;
527     LastUser[AP] = P;
528     // If AP is the last user of other passes then make P last user of
529     // such passes.
530     for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
531            LUE = LastUser.end(); LUI != LUE; ++LUI) {
532       if (LUI->second == AP)
533         LastUser[LUI->first] = P;
534     }
535   }
536
537 }
538
539 /// Collect passes whose last user is P
540 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
541                                             Pass *P) {
542    for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
543           LUE = LastUser.end(); LUI != LUE; ++LUI)
544       if (LUI->second == P)
545         LastUses.push_back(LUI->first);
546 }
547
548 /// Schedule pass P for execution. Make sure that passes required by
549 /// P are run before P is run. Update analysis info maintained by
550 /// the manager. Remove dead passes. This is a recursive function.
551 void PMTopLevelManager::schedulePass(Pass *P) {
552
553   // TODO : Allocate function manager for this pass, other wise required set
554   // may be inserted into previous function manager
555
556   AnalysisUsage AnUsage;
557   P->getAnalysisUsage(AnUsage);
558   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
559   for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
560          E = RequiredSet.end(); I != E; ++I) {
561
562     Pass *AnalysisPass = findAnalysisPass(*I);
563     if (!AnalysisPass) {
564       // Schedule this analysis run first.
565       AnalysisPass = (*I)->createPass();
566       schedulePass(AnalysisPass);
567     }
568   }
569
570   // Now all required passes are available.
571   addTopLevelPass(P);
572 }
573
574 /// Find the pass that implements Analysis AID. Search immutable
575 /// passes and all pass managers. If desired pass is not found
576 /// then return NULL.
577 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
578
579   Pass *P = NULL;
580   // Check pass managers
581   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
582          E = PassManagers.end(); P == NULL && I != E; ++I) {
583     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
584     assert(PMD && "This is not a PassManager");
585     P = PMD->findAnalysisPass(AID, false);
586   }
587
588   // Check other pass managers
589   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
590          E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
591     P = (*I)->findAnalysisPass(AID, false);
592
593   for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
594          E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
595     const PassInfo *PI = (*I)->getPassInfo();
596     if (PI == AID)
597       P = *I;
598
599     // If Pass not found then check the interfaces implemented by Immutable Pass
600     if (!P) {
601       const std::vector<const PassInfo*> &ImmPI = 
602         PI->getInterfacesImplemented();
603       for (unsigned Index = 0, End = ImmPI.size(); 
604            P == NULL && Index != End; ++Index)
605         if (ImmPI[Index] == AID)
606           P = *I;
607     }
608   }
609
610   return P;
611 }
612
613 // Print passes managed by this top level manager.
614 void PMTopLevelManager::dumpPasses() {
615
616   // Print out the immutable passes
617   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
618     ImmutablePasses[i]->dumpPassStructure(0);
619   }
620   
621   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
622          E = PassManagers.end(); I != E; ++I)
623     (*I)->dumpPassStructure(1);
624
625 }
626
627 //===----------------------------------------------------------------------===//
628 // PMDataManager implementation
629
630 /// Return true IFF pass P's required analysis set does not required new
631 /// manager.
632 bool PMDataManager::manageablePass(Pass *P) {
633
634   // TODO 
635   // If this pass is not preserving information that is required by a
636   // pass maintained by higher level pass manager then do not insert
637   // this pass into current manager. Use new manager. For example,
638   // For example, If FunctionPass F is not preserving ModulePass Info M1
639   // that is used by another ModulePass M2 then do not insert F in
640   // current function pass manager.
641   return true;
642 }
643
644 /// Augement AvailableAnalysis by adding analysis made available by pass P.
645 void PMDataManager::recordAvailableAnalysis(Pass *P) {
646                                                 
647   if (const PassInfo *PI = P->getPassInfo()) {
648     AvailableAnalysis[PI] = P;
649
650     //This pass is the current implementation of all of the interfaces it
651     //implements as well.
652     const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
653     for (unsigned i = 0, e = II.size(); i != e; ++i)
654       AvailableAnalysis[II[i]] = P;
655   }
656 }
657
658 /// Remove Analyss not preserved by Pass P
659 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
660   AnalysisUsage AnUsage;
661   P->getAnalysisUsage(AnUsage);
662
663   if (AnUsage.getPreservesAll())
664     return;
665
666   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
667   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
668          E = AvailableAnalysis.end(); I != E; ) {
669     if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) == 
670         PreservedSet.end()) {
671       // Remove this analysis
672       if (!dynamic_cast<ImmutablePass*>(I->second)) {
673         std::map<AnalysisID, Pass*>::iterator J = I++;
674         AvailableAnalysis.erase(J);
675       } else
676         ++I;
677     } else
678       ++I;
679   }
680 }
681
682 /// Remove analysis passes that are not used any longer
683 void PMDataManager::removeDeadPasses(Pass *P) {
684
685   std::vector<Pass *> DeadPasses;
686   TPM->collectLastUses(DeadPasses, P);
687
688   for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
689          E = DeadPasses.end(); I != E; ++I) {
690     (*I)->releaseMemory();
691     
692     std::map<AnalysisID, Pass*>::iterator Pos = 
693       AvailableAnalysis.find((*I)->getPassInfo());
694     
695     // It is possible that pass is already removed from the AvailableAnalysis
696     if (Pos != AvailableAnalysis.end())
697       AvailableAnalysis.erase(Pos);
698   }
699 }
700
701 /// Add pass P into the PassVector. Update 
702 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
703 void PMDataManager::addPassToManager(Pass *P, 
704                                      bool ProcessAnalysis) {
705
706   // This manager is going to manage pass P. Set up analysis resolver
707   // to connect them.
708   AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
709   P->setResolver(AR);
710
711   if (ProcessAnalysis) {
712
713     // At the moment, this pass is the last user of all required passes.
714     std::vector<Pass *> LastUses;
715     std::vector<Pass *> RequiredPasses;
716     unsigned PDepth = this->getDepth();
717
718     collectRequiredAnalysisPasses(RequiredPasses, P);
719     for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
720            E = RequiredPasses.end(); I != E; ++I) {
721       Pass *PRequired = *I;
722       unsigned RDepth = 0;
723
724       PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
725       RDepth = DM.getDepth();
726
727       if (PDepth == RDepth)
728         LastUses.push_back(PRequired);
729       else if (PDepth >  RDepth) {
730         // Let the parent claim responsibility of last use
731         ForcedLastUses.push_back(PRequired);
732       } else {
733         // Note : This feature is not yet implemented
734         assert (0 && 
735                 "Unable to handle Pass that requires lower level Analysis pass");
736       }
737     }
738
739     if (!LastUses.empty())
740       TPM->setLastUser(LastUses, P);
741
742     // Take a note of analysis required and made available by this pass.
743     // Remove the analysis not preserved by this pass
744     removeNotPreservedAnalysis(P);
745     recordAvailableAnalysis(P);
746   }
747
748   // Add pass
749   PassVector.push_back(P);
750 }
751
752 /// Populate RequiredPasses with the analysis pass that are required by
753 /// pass P.
754 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
755                                                   Pass *P) {
756   AnalysisUsage AnUsage;
757   P->getAnalysisUsage(AnUsage);
758   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
759   for (std::vector<AnalysisID>::const_iterator 
760          I = RequiredSet.begin(), E = RequiredSet.end();
761        I != E; ++I) {
762     Pass *AnalysisPass = findAnalysisPass(*I, true);
763     assert (AnalysisPass && "Analysis pass is not available");
764     RP.push_back(AnalysisPass);
765   }
766
767   const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
768   for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
769          E = IDs.end(); I != E; ++I) {
770     Pass *AnalysisPass = findAnalysisPass(*I, true);
771     assert (AnalysisPass && "Analysis pass is not available");
772     RP.push_back(AnalysisPass);
773   }
774 }
775
776 // All Required analyses should be available to the pass as it runs!  Here
777 // we fill in the AnalysisImpls member of the pass so that it can
778 // successfully use the getAnalysis() method to retrieve the
779 // implementations it needs.
780 //
781 void PMDataManager::initializeAnalysisImpl(Pass *P) {
782   AnalysisUsage AnUsage;
783   P->getAnalysisUsage(AnUsage);
784  
785   for (std::vector<const PassInfo *>::const_iterator
786          I = AnUsage.getRequiredSet().begin(),
787          E = AnUsage.getRequiredSet().end(); I != E; ++I) {
788     Pass *Impl = findAnalysisPass(*I, true);
789     if (Impl == 0)
790       assert(0 && "Analysis used but not available!");
791     AnalysisResolver_New *AR = P->getResolver();
792     AR->addAnalysisImplsPair(*I, Impl);
793   }
794 }
795
796 /// Find the pass that implements Analysis AID. If desired pass is not found
797 /// then return NULL.
798 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
799
800   // Check if AvailableAnalysis map has one entry.
801   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
802
803   if (I != AvailableAnalysis.end())
804     return I->second;
805
806   // Search Parents through TopLevelManager
807   if (SearchParent)
808     return TPM->findAnalysisPass(AID);
809   
810   return NULL;
811 }
812
813
814 //===----------------------------------------------------------------------===//
815 // NOTE: Is this the right place to define this method ?
816 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
817 Pass *AnalysisResolver_New::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
818   return PM.findAnalysisPass(ID, dir);
819 }
820
821 //===----------------------------------------------------------------------===//
822 // BasicBlockPassManager implementation
823
824 /// Add pass P into PassVector and return true. If this pass is not
825 /// manageable by this manager then return false.
826 bool
827 BasicBlockPassManager::addPass(Pass *P) {
828
829   BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
830   if (!BP)
831     return false;
832
833   // If this pass does not preserve anlysis that is used by other passes
834   // managed by this manager than it is not a suiable pass for this manager.
835   if (!manageablePass(P))
836     return false;
837
838   addPassToManager (BP);
839
840   return true;
841 }
842
843 /// Execute all of the passes scheduled for execution by invoking 
844 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
845 /// the function, and if so, return true.
846 bool
847 BasicBlockPassManager::runOnFunction(Function &F) {
848
849   if (F.isExternal())
850     return false;
851
852   bool Changed = doInitialization(F);
853   initializeAnalysisInfo();
854
855   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
856     for (std::vector<Pass *>::iterator itr = passVectorBegin(),
857            e = passVectorEnd(); itr != e; ++itr) {
858       Pass *P = *itr;
859       initializeAnalysisImpl(P);
860       BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
861       Changed |= BP->runOnBasicBlock(*I);
862       removeNotPreservedAnalysis(P);
863       recordAvailableAnalysis(P);
864       removeDeadPasses(P);
865     }
866   return Changed | doFinalization(F);
867 }
868
869 // Implement doInitialization and doFinalization
870 inline bool BasicBlockPassManager::doInitialization(Module &M) {
871   bool Changed = false;
872
873   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
874          e = passVectorEnd(); itr != e; ++itr) {
875     Pass *P = *itr;
876     BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);    
877     Changed |= BP->doInitialization(M);
878   }
879
880   return Changed;
881 }
882
883 inline bool BasicBlockPassManager::doFinalization(Module &M) {
884   bool Changed = false;
885
886   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
887          e = passVectorEnd(); itr != e; ++itr) {
888     Pass *P = *itr;
889     BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);    
890     Changed |= BP->doFinalization(M);
891   }
892
893   return Changed;
894 }
895
896 inline bool BasicBlockPassManager::doInitialization(Function &F) {
897   bool Changed = false;
898
899   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
900          e = passVectorEnd(); itr != e; ++itr) {
901     Pass *P = *itr;
902     BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);    
903     Changed |= BP->doInitialization(F);
904   }
905
906   return Changed;
907 }
908
909 inline bool BasicBlockPassManager::doFinalization(Function &F) {
910   bool Changed = false;
911
912   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
913          e = passVectorEnd(); itr != e; ++itr) {
914     Pass *P = *itr;
915     BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);    
916     Changed |= BP->doFinalization(F);
917   }
918
919   return Changed;
920 }
921
922
923 //===----------------------------------------------------------------------===//
924 // FunctionPassManager implementation
925
926 /// Create new Function pass manager
927 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
928   FPM = new FunctionPassManagerImpl_New(0);
929   // FPM is the top level manager.
930   FPM->setTopLevelManager(FPM);
931
932   PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
933   AnalysisResolver_New *AR = new AnalysisResolver_New(*PMD);
934   FPM->setResolver(AR);
935   
936   FPM->addPassManager(FPM);
937   MP = P;
938 }
939
940 FunctionPassManager::~FunctionPassManager() {
941   // Note : FPM maintains one entry in PassManagers vector.
942   // This one entry is FPM itself. This is not ideal. One
943   // alternative is have one additional layer between
944   // FunctionPassManager and FunctionPassManagerImpl.
945   // Meanwhile, to avoid going into infinte loop, first
946   // remove FPM from its PassMangers vector.
947   FPM->clearManagers();
948   delete FPM;
949 }
950
951 /// add - Add a pass to the queue of passes to run.  This passes
952 /// ownership of the Pass to the PassManager.  When the
953 /// PassManager_X is destroyed, the pass will be destroyed as well, so
954 /// there is no need to delete the pass. (TODO delete passes.)
955 /// This implies that all passes MUST be allocated with 'new'.
956 void FunctionPassManager::add(Pass *P) { 
957   FPM->add(P);
958 }
959
960 /// run - Execute all of the passes scheduled for execution.  Keep
961 /// track of whether any of the passes modifies the function, and if
962 /// so, return true.
963 ///
964 bool FunctionPassManager::run(Function &F) {
965   std::string errstr;
966   if (MP->materializeFunction(&F, &errstr)) {
967     cerr << "Error reading bytecode file: " << errstr << "\n";
968     abort();
969   }
970   return FPM->run(F);
971 }
972
973
974 /// doInitialization - Run all of the initializers for the function passes.
975 ///
976 bool FunctionPassManager::doInitialization() {
977   return FPM->doInitialization(*MP->getModule());
978 }
979
980 /// doFinalization - Run all of the initializers for the function passes.
981 ///
982 bool FunctionPassManager::doFinalization() {
983   return FPM->doFinalization(*MP->getModule());
984 }
985
986 //===----------------------------------------------------------------------===//
987 // FunctionPassManagerImpl_New implementation
988
989 /// Add pass P into the pass manager queue. If P is a BasicBlockPass then
990 /// either use it into active basic block pass manager or create new basic
991 /// block pass manager to handle pass P.
992 bool
993 FunctionPassManagerImpl_New::addPass(Pass *P) {
994
995   // If P is a BasicBlockPass then use BasicBlockPassManager.
996   if (BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P)) {
997
998     if (!activeBBPassManager || !activeBBPassManager->addPass(BP)) {
999
1000       // If active manager exists then clear its analysis info.
1001       if (activeBBPassManager)
1002         activeBBPassManager->initializeAnalysisInfo();
1003
1004       // Create and add new manager
1005       activeBBPassManager = 
1006         new BasicBlockPassManager(getDepth() + 1);
1007       // Inherit top level manager
1008       activeBBPassManager->setTopLevelManager(this->getTopLevelManager());
1009
1010       // Add new manager into current manager's list.
1011       addPassToManager(activeBBPassManager, false);
1012
1013       // Add new manager into top level manager's indirect passes list
1014       PMDataManager *PMD = dynamic_cast<PMDataManager *>(activeBBPassManager);
1015       assert (PMD && "Manager is not Pass Manager");
1016       TPM->addIndirectPassManager(PMD);
1017
1018       // Add pass into new manager. This time it must succeed.
1019       if (!activeBBPassManager->addPass(BP))
1020         assert(0 && "Unable to add Pass");
1021     }
1022
1023     if (!ForcedLastUses.empty())
1024       TPM->setLastUser(ForcedLastUses, this);
1025
1026     return true;
1027   }
1028
1029   FunctionPass *FP = dynamic_cast<FunctionPass *>(P);
1030   if (!FP)
1031     return false;
1032
1033   // If this pass does not preserve anlysis that is used by other passes
1034   // managed by this manager than it is not a suiable pass for this manager.
1035   if (!manageablePass(P))
1036     return false;
1037
1038   addPassToManager (FP);
1039
1040   // If active manager exists then clear its analysis info.
1041   if (activeBBPassManager) {
1042     activeBBPassManager->initializeAnalysisInfo();
1043     activeBBPassManager = NULL;
1044   }
1045
1046   return true;
1047 }
1048
1049 /// Execute all of the passes scheduled for execution by invoking 
1050 /// runOnFunction method.  Keep track of whether any of the passes modifies 
1051 /// the function, and if so, return true.
1052 bool FunctionPassManagerImpl_New::runOnModule(Module &M) {
1053
1054   bool Changed = doInitialization(M);
1055   initializeAnalysisInfo();
1056
1057   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1058     this->runOnFunction(*I);
1059
1060   return Changed | doFinalization(M);
1061 }
1062
1063 /// Execute all of the passes scheduled for execution by invoking 
1064 /// runOnFunction method.  Keep track of whether any of the passes modifies 
1065 /// the function, and if so, return true.
1066 bool FunctionPassManagerImpl_New::runOnFunction(Function &F) {
1067
1068   bool Changed = false;
1069
1070   if (F.isExternal())
1071     return false;
1072
1073   initializeAnalysisInfo();
1074
1075   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1076          e = passVectorEnd(); itr != e; ++itr) {
1077     Pass *P = *itr;
1078     initializeAnalysisImpl(P);    
1079     FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
1080     Changed |= FP->runOnFunction(F);
1081     removeNotPreservedAnalysis(P);
1082     recordAvailableAnalysis(P);
1083     removeDeadPasses(P);
1084   }
1085   return Changed;
1086 }
1087
1088
1089 inline bool FunctionPassManagerImpl_New::doInitialization(Module &M) {
1090   bool Changed = false;
1091
1092   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1093          e = passVectorEnd(); itr != e; ++itr) {
1094     Pass *P = *itr;
1095     
1096     FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
1097     Changed |= FP->doInitialization(M);
1098   }
1099
1100   return Changed;
1101 }
1102
1103 inline bool FunctionPassManagerImpl_New::doFinalization(Module &M) {
1104   bool Changed = false;
1105
1106   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1107          e = passVectorEnd(); itr != e; ++itr) {
1108     Pass *P = *itr;
1109     
1110     FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
1111     Changed |= FP->doFinalization(M);
1112   }
1113
1114   return Changed;
1115 }
1116
1117 // Execute all the passes managed by this top level manager.
1118 // Return true if any function is modified by a pass.
1119 bool FunctionPassManagerImpl_New::run(Function &F) {
1120
1121   bool Changed = false;
1122   for (std::vector<Pass *>::iterator I = passManagersBegin(),
1123          E = passManagersEnd(); I != E; ++I) {
1124     FunctionPassManagerImpl_New *FP = 
1125       dynamic_cast<FunctionPassManagerImpl_New *>(*I);
1126     Changed |= FP->runOnFunction(F);
1127   }
1128   return Changed;
1129 }
1130
1131 //===----------------------------------------------------------------------===//
1132 // ModulePassManager implementation
1133
1134 /// Add P into pass vector if it is manageble. If P is a FunctionPass
1135 /// then use FunctionPassManagerImpl_New to manage it. Return false if P
1136 /// is not manageable by this manager.
1137 bool
1138 ModulePassManager::addPass(Pass *P) {
1139
1140   // If P is FunctionPass then use function pass maanager.
1141   if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P)) {
1142
1143     if (!activeFunctionPassManager || !activeFunctionPassManager->addPass(P)) {
1144
1145       // If active manager exists then clear its analysis info.
1146       if (activeFunctionPassManager) 
1147         activeFunctionPassManager->initializeAnalysisInfo();
1148
1149       // Create and add new manager
1150       activeFunctionPassManager = 
1151         new FunctionPassManagerImpl_New(getDepth() + 1);
1152       
1153       // Add new manager into current manager's list
1154       addPassToManager(activeFunctionPassManager, false);
1155
1156       // Inherit top level manager
1157       activeFunctionPassManager->setTopLevelManager(this->getTopLevelManager());
1158
1159       // Add new manager into top level manager's indirect passes list
1160       PMDataManager *PMD = dynamic_cast<PMDataManager *>(activeFunctionPassManager);
1161       assert (PMD && "Manager is not Pass Manager");
1162       TPM->addIndirectPassManager(PMD);
1163       
1164       // Add pass into new manager. This time it must succeed.
1165       if (!activeFunctionPassManager->addPass(FP))
1166         assert(0 && "Unable to add pass");
1167     }
1168
1169     if (!ForcedLastUses.empty())
1170       TPM->setLastUser(ForcedLastUses, this);
1171
1172     return true;
1173   }
1174
1175   ModulePass *MP = dynamic_cast<ModulePass *>(P);
1176   if (!MP)
1177     return false;
1178
1179   // If this pass does not preserve anlysis that is used by other passes
1180   // managed by this manager than it is not a suiable pass for this manager.
1181   if (!manageablePass(P))
1182     return false;
1183
1184   addPassToManager(MP);
1185   // If active manager exists then clear its analysis info.
1186   if (activeFunctionPassManager) {
1187     activeFunctionPassManager->initializeAnalysisInfo();
1188     activeFunctionPassManager = NULL;
1189   }
1190
1191   return true;
1192 }
1193
1194
1195 /// Execute all of the passes scheduled for execution by invoking 
1196 /// runOnModule method.  Keep track of whether any of the passes modifies 
1197 /// the module, and if so, return true.
1198 bool
1199 ModulePassManager::runOnModule(Module &M) {
1200   bool Changed = false;
1201   initializeAnalysisInfo();
1202
1203   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
1204          e = passVectorEnd(); itr != e; ++itr) {
1205     Pass *P = *itr;
1206     initializeAnalysisImpl(P);
1207     ModulePass *MP = dynamic_cast<ModulePass*>(P);
1208     Changed |= MP->runOnModule(M);
1209     removeNotPreservedAnalysis(P);
1210     recordAvailableAnalysis(P);
1211     removeDeadPasses(P);
1212   }
1213   return Changed;
1214 }
1215
1216 //===----------------------------------------------------------------------===//
1217 // PassManagerImpl implementation
1218 //
1219 /// Add P into active pass manager or use new module pass manager to
1220 /// manage it.
1221 bool PassManagerImpl_New::addPass(Pass *P) {
1222
1223   if (!activeManager || !activeManager->addPass(P)) {
1224     activeManager = new ModulePassManager(getDepth() + 1);
1225     // Inherit top level manager
1226     activeManager->setTopLevelManager(this->getTopLevelManager());
1227
1228     // This top level manager is going to manage activeManager. 
1229     // Set up analysis resolver to connect them.
1230     AnalysisResolver_New *AR = new AnalysisResolver_New(*this);
1231     activeManager->setResolver(AR);
1232
1233     addPassManager(activeManager);
1234     return activeManager->addPass(P);
1235   }
1236   return true;
1237 }
1238
1239 /// run - Execute all of the passes scheduled for execution.  Keep track of
1240 /// whether any of the passes modifies the module, and if so, return true.
1241 bool PassManagerImpl_New::run(Module &M) {
1242
1243   bool Changed = false;
1244   for (std::vector<Pass *>::iterator I = passManagersBegin(),
1245          E = passManagersEnd(); I != E; ++I) {
1246     ModulePassManager *MP = dynamic_cast<ModulePassManager *>(*I);
1247     Changed |= MP->runOnModule(M);
1248   }
1249   return Changed;
1250 }
1251
1252 //===----------------------------------------------------------------------===//
1253 // PassManager implementation
1254
1255 /// Create new pass manager
1256 PassManager::PassManager() {
1257   PM = new PassManagerImpl_New(0);
1258   // PM is the top level manager
1259   PM->setTopLevelManager(PM);
1260 }
1261
1262 PassManager::~PassManager() {
1263   delete PM;
1264 }
1265
1266 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1267 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1268 /// will be destroyed as well, so there is no need to delete the pass.  This
1269 /// implies that all passes MUST be allocated with 'new'.
1270 void 
1271 PassManager::add(Pass *P) {
1272   PM->add(P);
1273 }
1274
1275 /// run - Execute all of the passes scheduled for execution.  Keep track of
1276 /// whether any of the passes modifies the module, and if so, return true.
1277 bool
1278 PassManager::run(Module &M) {
1279   return PM->run(M);
1280 }
1281
1282 #endif