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