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