Pass Managers themselves do not invalidate any analysis info.
[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, Pass *PM);
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   virtual ~PMTopLevelManager() {
122     PassManagers.clear();
123   }
124
125 private:
126   
127   /// Collection of pass managers
128   std::vector<Pass *> PassManagers;
129
130   // Map to keep track of last user of the analysis pass.
131   // LastUser->second is the last user of Lastuser->first.
132   std::map<Pass *, Pass *> LastUser;
133 };
134   
135 /// Set pass P as the last user of the given analysis passes.
136 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses, 
137                                     Pass *P) {
138
139   for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
140          E = AnalysisPasses.end(); I != E; ++I) {
141     Pass *AP = *I;
142     LastUser[AP] = P;
143     // If AP is the last user of other passes then make P last user of
144     // such passes.
145     for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
146            LUE = LastUser.end(); LUI != LUE; ++LUI) {
147       if (LUI->second == AP)
148         LastUser[LUI->first] = P;
149     }
150   }
151
152 }
153
154 /// Collect passes whose last user is P
155 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
156                                             Pass *P) {
157    for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
158           LUE = LastUser.end(); LUI != LUE; ++LUI)
159       if (LUI->second == P)
160         LastUses.push_back(LUI->first);
161 }
162
163 //===----------------------------------------------------------------------===//
164 // PMDataManager
165
166 /// PMDataManager provides the common place to manage the analysis data
167 /// used by pass managers.
168 class PMDataManager {
169
170 public:
171
172   PMDataManager() : TPM(NULL) {
173     initializeAnalysisInfo();
174   }
175
176   /// Return true IFF pass P's required analysis set does not required new
177   /// manager.
178   bool manageablePass(Pass *P);
179
180   Pass *getAnalysisPass(AnalysisID AID) const {
181
182     std::map<AnalysisID, Pass*>::const_iterator I = 
183       AvailableAnalysis.find(AID);
184
185     if (I != AvailableAnalysis.end())
186       return NULL;
187     else
188       return I->second;
189   }
190
191   /// Augment AvailableAnalysis by adding analysis made available by pass P.
192   void recordAvailableAnalysis(Pass *P);
193
194   /// Remove Analysis that is not preserved by the pass
195   void removeNotPreservedAnalysis(Pass *P);
196   
197   /// Remove dead passes
198   void removeDeadPasses(Pass *P);
199
200   /// Add pass P into the PassVector. Update 
201   /// AvailableAnalysis appropriately if ProcessAnalysis is true.
202   void addPassToManager (Pass *P, bool ProcessAnalysis = true);
203
204   // Initialize available analysis information.
205   void initializeAnalysisInfo() { 
206     AvailableAnalysis.clear();
207     LastUser.clear();
208   }
209
210   // All Required analyses should be available to the pass as it runs!  Here
211   // we fill in the AnalysisImpls member of the pass so that it can
212   // successfully use the getAnalysis() method to retrieve the
213   // implementations it needs.
214   //
215  void initializeAnalysisImpl(Pass *P);
216
217   inline std::vector<Pass *>::iterator passVectorBegin() { 
218     return PassVector.begin(); 
219   }
220
221   inline std::vector<Pass *>::iterator passVectorEnd() { 
222     return PassVector.end();
223   }
224
225   inline void setLastUser(Pass *P, Pass *LU) {
226     LastUser[P] = LU; 
227     // TODO : Check if pass P is available.
228   }
229
230   // Access toplevel manager
231   PMTopLevelManager *getTopLevelManager() { return TPM; }
232   void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
233
234 private:
235   // Set of available Analysis. This information is used while scheduling 
236   // pass. If a pass requires an analysis which is not not available then 
237   // equired analysis pass is scheduled to run before the pass itself is 
238   // scheduled to run.
239   std::map<AnalysisID, Pass*> AvailableAnalysis;
240
241   // Map to keep track of last user of the analysis pass.
242   // LastUser->second is the last user of Lastuser->first.
243   std::map<Pass *, Pass *> LastUser;
244
245   // Collection of pass that are managed by this manager
246   std::vector<Pass *> PassVector;
247
248   // Top level manager.
249   // TODO : Make it a reference.
250   PMTopLevelManager *TPM;
251 };
252
253 /// BasicBlockPassManager_New manages BasicBlockPass. It batches all the
254 /// pass together and sequence them to process one basic block before
255 /// processing next basic block.
256 class BasicBlockPassManager_New : public PMDataManager, 
257                                   public FunctionPass {
258
259 public:
260   BasicBlockPassManager_New() { }
261
262   /// Add a pass into a passmanager queue. 
263   bool addPass(Pass *p);
264   
265   /// Execute all of the passes scheduled for execution.  Keep track of
266   /// whether any of the passes modifies the function, and if so, return true.
267   bool runOnFunction(Function &F);
268
269   /// Return true IFF AnalysisID AID is currently available.
270   Pass *getAnalysisPassFromManager(AnalysisID AID);
271
272   /// Pass Manager itself does not invalidate any analysis info.
273   void getAnalysisUsage(AnalysisUsage &Info) const {
274     Info.setPreservesAll();
275   }
276
277 private:
278 };
279
280 /// FunctionPassManagerImpl_New manages FunctionPasses and BasicBlockPassManagers.
281 /// It batches all function passes and basic block pass managers together and
282 /// sequence them to process one function at a time before processing next
283 /// function.
284 class FunctionPassManagerImpl_New : public PMDataManager,
285                                     public ModulePass {
286 public:
287   FunctionPassManagerImpl_New(ModuleProvider *P) { /* TODO */ }
288   FunctionPassManagerImpl_New() { 
289     activeBBPassManager = NULL;
290   }
291   ~FunctionPassManagerImpl_New() { /* TODO */ };
292  
293   /// add - Add a pass to the queue of passes to run.  This passes
294   /// ownership of the Pass to the PassManager.  When the
295   /// PassManager_X is destroyed, the pass will be destroyed as well, so
296   /// there is no need to delete the pass. (TODO delete passes.)
297   /// This implies that all passes MUST be allocated with 'new'.
298   void add(Pass *P) { /* TODO*/  }
299
300   /// Add pass into the pass manager queue.
301   bool addPass(Pass *P);
302
303   /// Execute all of the passes scheduled for execution.  Keep
304   /// track of whether any of the passes modifies the function, and if
305   /// so, return true.
306   bool runOnModule(Module &M);
307   bool runOnFunction(Function &F);
308
309   /// Return true IFF AnalysisID AID is currently available.
310   Pass *getAnalysisPassFromManager(AnalysisID AID);
311
312   /// doInitialization - Run all of the initializers for the function passes.
313   ///
314   bool doInitialization(Module &M);
315   
316   /// doFinalization - Run all of the initializers for the function passes.
317   ///
318   bool doFinalization(Module &M);
319
320   /// Pass Manager itself does not invalidate any analysis info.
321   void getAnalysisUsage(AnalysisUsage &Info) const {
322     Info.setPreservesAll();
323   }
324
325 private:
326   // Active Pass Managers
327   BasicBlockPassManager_New *activeBBPassManager;
328 };
329
330 /// ModulePassManager_New manages ModulePasses and function pass managers.
331 /// It batches all Module passes  passes and function pass managers together and
332 /// sequence them to process one module.
333 class ModulePassManager_New : public PMDataManager {
334  
335 public:
336   ModulePassManager_New() { activeFunctionPassManager = NULL; }
337   
338   /// Add a pass into a passmanager queue. 
339   bool addPass(Pass *p);
340   
341   /// run - Execute all of the passes scheduled for execution.  Keep track of
342   /// whether any of the passes modifies the module, and if so, return true.
343   bool runOnModule(Module &M);
344
345   /// Return true IFF AnalysisID AID is currently available.
346   Pass *getAnalysisPassFromManager(AnalysisID AID);
347
348   /// Pass Manager itself does not invalidate any analysis info.
349   void getAnalysisUsage(AnalysisUsage &Info) const {
350     Info.setPreservesAll();
351   }
352
353 private:
354   // Active Pass Manager
355   FunctionPassManagerImpl_New *activeFunctionPassManager;
356 };
357
358 /// PassManager_New manages ModulePassManagers
359 class PassManagerImpl_New : public PMDataManager {
360
361 public:
362
363   /// add - Add a pass to the queue of passes to run.  This passes ownership of
364   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
365   /// will be destroyed as well, so there is no need to delete the pass.  This
366   /// implies that all passes MUST be allocated with 'new'.
367   void add(Pass *P);
368  
369   /// run - Execute all of the passes scheduled for execution.  Keep track of
370   /// whether any of the passes modifies the module, and if so, return true.
371   bool run(Module &M);
372
373   /// Return true IFF AnalysisID AID is currently available.
374   Pass *getAnalysisPassFromManager(AnalysisID AID);
375
376   /// Pass Manager itself does not invalidate any analysis info.
377   void getAnalysisUsage(AnalysisUsage &Info) const {
378     Info.setPreservesAll();
379   }
380
381 private:
382
383   /// Add a pass into a passmanager queue. This is used by schedulePasses
384   bool addPass(Pass *p);
385
386   /// Schedule pass P for execution. Make sure that passes required by
387   /// P are run before P is run. Update analysis info maintained by
388   /// the manager. Remove dead passes. This is a recursive function.
389   void schedulePass(Pass *P);
390
391   /// Schedule all passes collected in pass queue using add(). Add all the
392   /// schedule passes into various manager's queue using addPass().
393   void schedulePasses();
394
395   // Collection of pass managers
396   std::vector<ModulePassManager_New *> PassManagers;
397
398   // Active Pass Manager
399   ModulePassManager_New *activeManager;
400 };
401
402 } // End of llvm namespace
403
404 //===----------------------------------------------------------------------===//
405 // PMDataManager implementation
406
407 /// Return true IFF pass P's required analysis set does not required new
408 /// manager.
409 bool PMDataManager::manageablePass(Pass *P) {
410
411   // TODO 
412   // If this pass is not preserving information that is required by a
413   // pass maintained by higher level pass manager then do not insert
414   // this pass into current manager. Use new manager. For example,
415   // For example, If FunctionPass F is not preserving ModulePass Info M1
416   // that is used by another ModulePass M2 then do not insert F in
417   // current function pass manager.
418   return true;
419 }
420
421 /// Augement AvailableAnalysis by adding analysis made available by pass P.
422 void PMDataManager::recordAvailableAnalysis(Pass *P) {
423                                                 
424   if (const PassInfo *PI = P->getPassInfo()) {
425     AvailableAnalysis[PI] = P;
426
427     //This pass is the current implementation of all of the interfaces it
428     //implements as well.
429     const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
430     for (unsigned i = 0, e = II.size(); i != e; ++i)
431       AvailableAnalysis[II[i]] = P;
432   }
433 }
434
435 /// Remove Analyss not preserved by Pass P
436 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
437   AnalysisUsage AnUsage;
438   P->getAnalysisUsage(AnUsage);
439   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
440
441   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
442          E = AvailableAnalysis.end(); I != E; ++I ) {
443     if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) == 
444         PreservedSet.end()) {
445       // Remove this analysis
446       std::map<AnalysisID, Pass*>::iterator J = I++;
447       AvailableAnalysis.erase(J);
448     }
449   }
450 }
451
452 /// Remove analysis passes that are not used any longer
453 void PMDataManager::removeDeadPasses(Pass *P) {
454
455   for (std::map<Pass *, Pass *>::iterator I = LastUser.begin(),
456          E = LastUser.end(); I !=E; ++I) {
457     if (I->second == P) {
458       Pass *deadPass = I->first;
459       deadPass->releaseMemory();
460
461       std::map<AnalysisID, Pass*>::iterator Pos = 
462         AvailableAnalysis.find(deadPass->getPassInfo());
463       
464       assert (Pos != AvailableAnalysis.end() &&
465               "Pass is not available");
466       AvailableAnalysis.erase(Pos);
467     }
468   }
469 }
470
471 /// Add pass P into the PassVector. Update 
472 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
473 void PMDataManager::addPassToManager (Pass *P, 
474                                               bool ProcessAnalysis) {
475
476   if (ProcessAnalysis) {
477     // Take a note of analysis required and made available by this pass
478     initializeAnalysisImpl(P);
479     recordAvailableAnalysis(P);
480
481     // Remove the analysis not preserved by this pass
482     removeNotPreservedAnalysis(P);
483   }
484
485   // Add pass
486   PassVector.push_back(P);
487 }
488
489 // All Required analyses should be available to the pass as it runs!  Here
490 // we fill in the AnalysisImpls member of the pass so that it can
491 // successfully use the getAnalysis() method to retrieve the
492 // implementations it needs.
493 //
494 void PMDataManager::initializeAnalysisImpl(Pass *P) {
495   AnalysisUsage AnUsage;
496   P->getAnalysisUsage(AnUsage);
497  
498   for (std::vector<const PassInfo *>::const_iterator
499          I = AnUsage.getRequiredSet().begin(),
500          E = AnUsage.getRequiredSet().end(); I != E; ++I) {
501     Pass *Impl = getAnalysisPass(*I);
502     if (Impl == 0)
503       assert(0 && "Analysis used but not available!");
504     // TODO:  P->AnalysisImpls.push_back(std::make_pair(*I, Impl));
505   }
506 }
507
508 //===----------------------------------------------------------------------===//
509 // BasicBlockPassManager_New implementation
510
511 /// Add pass P into PassVector and return true. If this pass is not
512 /// manageable by this manager then return false.
513 bool
514 BasicBlockPassManager_New::addPass(Pass *P) {
515
516   BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
517   if (!BP)
518     return false;
519
520   // If this pass does not preserve anlysis that is used by other passes
521   // managed by this manager than it is not a suiable pass for this manager.
522   if (!manageablePass(P))
523     return false;
524
525   addPassToManager (BP);
526
527   return true;
528 }
529
530 /// Execute all of the passes scheduled for execution by invoking 
531 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
532 /// the function, and if so, return true.
533 bool
534 BasicBlockPassManager_New::runOnFunction(Function &F) {
535
536   bool Changed = false;
537   initializeAnalysisInfo();
538
539   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
540     for (std::vector<Pass *>::iterator itr = passVectorBegin(),
541            e = passVectorEnd(); itr != e; ++itr) {
542       Pass *P = *itr;
543       
544       recordAvailableAnalysis(P);
545       BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
546       Changed |= BP->runOnBasicBlock(*I);
547       removeNotPreservedAnalysis(P);
548       removeDeadPasses(P);
549     }
550   return Changed;
551 }
552
553 /// Return true IFF AnalysisID AID is currently available.
554 Pass * BasicBlockPassManager_New::getAnalysisPassFromManager(AnalysisID AID) {
555   return getAnalysisPass(AID);
556 }
557
558 //===----------------------------------------------------------------------===//
559 // FunctionPassManager_New implementation
560
561 /// Create new Function pass manager
562 FunctionPassManager_New::FunctionPassManager_New() {
563   FPM = new FunctionPassManagerImpl_New();
564 }
565
566 /// add - Add a pass to the queue of passes to run.  This passes
567 /// ownership of the Pass to the PassManager.  When the
568 /// PassManager_X is destroyed, the pass will be destroyed as well, so
569 /// there is no need to delete the pass. (TODO delete passes.)
570 /// This implies that all passes MUST be allocated with 'new'.
571 void FunctionPassManager_New::add(Pass *P) { 
572   FPM->add(P);
573 }
574
575 /// Execute all of the passes scheduled for execution.  Keep
576 /// track of whether any of the passes modifies the function, and if
577 /// so, return true.
578 bool FunctionPassManager_New::runOnModule(Module &M) {
579   return FPM->runOnModule(M);
580 }
581
582 /// run - Execute all of the passes scheduled for execution.  Keep
583 /// track of whether any of the passes modifies the function, and if
584 /// so, return true.
585 ///
586 bool FunctionPassManager_New::run(Function &F) {
587   std::string errstr;
588   if (MP->materializeFunction(&F, &errstr)) {
589     cerr << "Error reading bytecode file: " << errstr << "\n";
590     abort();
591   }
592   return FPM->runOnFunction(F);
593 }
594
595
596 /// doInitialization - Run all of the initializers for the function passes.
597 ///
598 bool FunctionPassManager_New::doInitialization() {
599   return FPM->doInitialization(*MP->getModule());
600 }
601
602 /// doFinalization - Run all of the initializers for the function passes.
603 ///
604 bool FunctionPassManager_New::doFinalization() {
605   return FPM->doFinalization(*MP->getModule());
606 }
607
608 //===----------------------------------------------------------------------===//
609 // FunctionPassManagerImpl_New implementation
610
611 /// Add pass P into the pass manager queue. If P is a BasicBlockPass then
612 /// either use it into active basic block pass manager or create new basic
613 /// block pass manager to handle pass P.
614 bool
615 FunctionPassManagerImpl_New::addPass(Pass *P) {
616
617   // If P is a BasicBlockPass then use BasicBlockPassManager_New.
618   if (BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P)) {
619
620     if (!activeBBPassManager
621         || !activeBBPassManager->addPass(BP)) {
622
623       activeBBPassManager = new BasicBlockPassManager_New();
624       addPassToManager(activeBBPassManager, false);
625       if (!activeBBPassManager->addPass(BP))
626         assert(0 && "Unable to add Pass");
627     }
628     return true;
629   }
630
631   FunctionPass *FP = dynamic_cast<FunctionPass *>(P);
632   if (!FP)
633     return false;
634
635   // If this pass does not preserve anlysis that is used by other passes
636   // managed by this manager than it is not a suiable pass for this manager.
637   if (!manageablePass(P))
638     return false;
639
640   addPassToManager (FP);
641   activeBBPassManager = NULL;
642   return true;
643 }
644
645 /// Execute all of the passes scheduled for execution by invoking 
646 /// runOnFunction method.  Keep track of whether any of the passes modifies 
647 /// the function, and if so, return true.
648 bool FunctionPassManagerImpl_New::runOnModule(Module &M) {
649
650   bool Changed = false;
651   initializeAnalysisInfo();
652
653   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
654     for (std::vector<Pass *>::iterator itr = passVectorBegin(),
655            e = passVectorEnd(); itr != e; ++itr) {
656       Pass *P = *itr;
657       
658       recordAvailableAnalysis(P);
659       FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
660       Changed |= FP->runOnFunction(*I);
661       removeNotPreservedAnalysis(P);
662       removeDeadPasses(P);
663     }
664   return Changed;
665 }
666
667 /// Execute all of the passes scheduled for execution by invoking 
668 /// runOnFunction method.  Keep track of whether any of the passes modifies 
669 /// the function, and if so, return true.
670 bool FunctionPassManagerImpl_New::runOnFunction(Function &F) {
671
672   bool Changed = false;
673   initializeAnalysisInfo();
674
675   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
676          e = passVectorEnd(); itr != e; ++itr) {
677     Pass *P = *itr;
678     
679     recordAvailableAnalysis(P);
680     FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
681     Changed |= FP->runOnFunction(F);
682     removeNotPreservedAnalysis(P);
683     removeDeadPasses(P);
684   }
685   return Changed;
686 }
687
688
689 /// Return true IFF AnalysisID AID is currently available.
690 Pass *FunctionPassManagerImpl_New::getAnalysisPassFromManager(AnalysisID AID) {
691
692   Pass *P = getAnalysisPass(AID);
693   if (P)
694     return P;
695
696   if (activeBBPassManager && 
697       activeBBPassManager->getAnalysisPass(AID) != 0)
698     return activeBBPassManager->getAnalysisPass(AID);
699
700   // TODO : Check inactive managers
701   return NULL;
702 }
703
704 inline bool FunctionPassManagerImpl_New::doInitialization(Module &M) {
705   bool Changed = false;
706
707   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
708          e = passVectorEnd(); itr != e; ++itr) {
709     Pass *P = *itr;
710     
711     FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
712     Changed |= FP->doInitialization(M);
713   }
714
715   return Changed;
716 }
717
718 inline bool FunctionPassManagerImpl_New::doFinalization(Module &M) {
719   bool Changed = false;
720
721   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
722          e = passVectorEnd(); itr != e; ++itr) {
723     Pass *P = *itr;
724     
725     FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
726     Changed |= FP->doFinalization(M);
727   }
728
729
730   return Changed;
731 }
732
733 //===----------------------------------------------------------------------===//
734 // ModulePassManager implementation
735
736 /// Add P into pass vector if it is manageble. If P is a FunctionPass
737 /// then use FunctionPassManagerImpl_New to manage it. Return false if P
738 /// is not manageable by this manager.
739 bool
740 ModulePassManager_New::addPass(Pass *P) {
741
742   // If P is FunctionPass then use function pass maanager.
743   if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P)) {
744
745     activeFunctionPassManager = NULL;
746
747     if (!activeFunctionPassManager
748         || !activeFunctionPassManager->addPass(P)) {
749
750       activeFunctionPassManager = new FunctionPassManagerImpl_New();
751       addPassToManager(activeFunctionPassManager, false);
752       if (!activeFunctionPassManager->addPass(FP))
753         assert(0 && "Unable to add pass");
754     }
755     return true;
756   }
757
758   ModulePass *MP = dynamic_cast<ModulePass *>(P);
759   if (!MP)
760     return false;
761
762   // If this pass does not preserve anlysis that is used by other passes
763   // managed by this manager than it is not a suiable pass for this manager.
764   if (!manageablePass(P))
765     return false;
766
767   addPassToManager(MP);
768   activeFunctionPassManager = NULL;
769   return true;
770 }
771
772
773 /// Execute all of the passes scheduled for execution by invoking 
774 /// runOnModule method.  Keep track of whether any of the passes modifies 
775 /// the module, and if so, return true.
776 bool
777 ModulePassManager_New::runOnModule(Module &M) {
778   bool Changed = false;
779   initializeAnalysisInfo();
780
781   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
782          e = passVectorEnd(); itr != e; ++itr) {
783     Pass *P = *itr;
784
785     recordAvailableAnalysis(P);
786     ModulePass *MP = dynamic_cast<ModulePass*>(P);
787     Changed |= MP->runOnModule(M);
788     removeNotPreservedAnalysis(P);
789     removeDeadPasses(P);
790   }
791   return Changed;
792 }
793
794 /// Return true IFF AnalysisID AID is currently available.
795 Pass *ModulePassManager_New::getAnalysisPassFromManager(AnalysisID AID) {
796
797   
798   Pass *P = getAnalysisPass(AID);
799   if (P)
800     return P;
801
802   if (activeFunctionPassManager && 
803       activeFunctionPassManager->getAnalysisPass(AID) != 0)
804     return activeFunctionPassManager->getAnalysisPass(AID);
805
806   // TODO : Check inactive managers
807   return NULL;
808 }
809
810 //===----------------------------------------------------------------------===//
811 // PassManagerImpl implementation
812
813 /// Return true IFF AnalysisID AID is currently available.
814 Pass *PassManagerImpl_New::getAnalysisPassFromManager(AnalysisID AID) {
815
816   Pass *P = NULL;
817   for (std::vector<ModulePassManager_New *>::iterator itr = PassManagers.begin(),
818          e = PassManagers.end(); !P && itr != e; ++itr)
819     P  = (*itr)->getAnalysisPassFromManager(AID);
820   return P;
821 }
822
823 /// Schedule pass P for execution. Make sure that passes required by
824 /// P are run before P is run. Update analysis info maintained by
825 /// the manager. Remove dead passes. This is a recursive function.
826 void PassManagerImpl_New::schedulePass(Pass *P) {
827
828   AnalysisUsage AnUsage;
829   P->getAnalysisUsage(AnUsage);
830   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
831   for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
832          E = RequiredSet.end(); I != E; ++I) {
833
834     Pass *AnalysisPass = getAnalysisPassFromManager(*I);
835     if (!AnalysisPass) {
836       // Schedule this analysis run first.
837       AnalysisPass = (*I)->createPass();
838       schedulePass(AnalysisPass);
839     }
840     setLastUser (AnalysisPass, P);
841
842     // Prolong live range of analyses that are needed after an analysis pass
843     // is destroyed, for querying by subsequent passes
844     const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
845     for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
846            E = IDs.end(); I != E; ++I) {
847       Pass *AP = getAnalysisPassFromManager(*I);
848       assert (AP && "Analysis pass is not available");
849       setLastUser(AP, P);
850     }
851   }
852   addPass(P);
853 }
854
855 /// Schedule all passes from the queue by adding them in their
856 /// respective manager's queue. 
857 void PassManagerImpl_New::schedulePasses() {
858   for (std::vector<Pass *>::iterator I = passVectorBegin(),
859          E = passVectorEnd(); I != E; ++I)
860     schedulePass (*I);
861 }
862
863 /// Add pass P to the queue of passes to run.
864 void PassManagerImpl_New::add(Pass *P) {
865   // Do not process Analysis now. Analysis is process while scheduling
866   // the pass vector.
867   addPassToManager(P, false);
868 }
869
870 // PassManager_New implementation
871 /// Add P into active pass manager or use new module pass manager to
872 /// manage it.
873 bool PassManagerImpl_New::addPass(Pass *P) {
874
875   if (!activeManager || !activeManager->addPass(P)) {
876     activeManager = new ModulePassManager_New();
877     PassManagers.push_back(activeManager);
878   }
879
880   return activeManager->addPass(P);
881 }
882
883 /// run - Execute all of the passes scheduled for execution.  Keep track of
884 /// whether any of the passes modifies the module, and if so, return true.
885 bool PassManagerImpl_New::run(Module &M) {
886
887   schedulePasses();
888   bool Changed = false;
889   for (std::vector<ModulePassManager_New *>::iterator itr = PassManagers.begin(),
890          e = PassManagers.end(); itr != e; ++itr) {
891     ModulePassManager_New *pm = *itr;
892     Changed |= pm->runOnModule(M);
893   }
894   return Changed;
895 }
896
897 //===----------------------------------------------------------------------===//
898 // PassManager implementation
899
900 /// Create new pass manager
901 PassManager_New::PassManager_New() {
902   PM = new PassManagerImpl_New();
903 }
904
905 /// add - Add a pass to the queue of passes to run.  This passes ownership of
906 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
907 /// will be destroyed as well, so there is no need to delete the pass.  This
908 /// implies that all passes MUST be allocated with 'new'.
909 void 
910 PassManager_New::add(Pass *P) {
911   PM->add(P);
912 }
913
914 /// run - Execute all of the passes scheduled for execution.  Keep track of
915 /// whether any of the passes modifies the module, and if so, return true.
916 bool
917 PassManager_New::run(Module &M) {
918   return PM->run(M);
919 }
920