If pass reserves all analysis info then each info is not separately
[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
440   if (AnUsage.getPreservesAll())
441     return;
442
443   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
444   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
445          E = AvailableAnalysis.end(); I != E; ++I ) {
446     if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) == 
447         PreservedSet.end()) {
448       // Remove this analysis
449       std::map<AnalysisID, Pass*>::iterator J = I++;
450       AvailableAnalysis.erase(J);
451     }
452   }
453 }
454
455 /// Remove analysis passes that are not used any longer
456 void PMDataManager::removeDeadPasses(Pass *P) {
457
458   for (std::map<Pass *, Pass *>::iterator I = LastUser.begin(),
459          E = LastUser.end(); I !=E; ++I) {
460     if (I->second == P) {
461       Pass *deadPass = I->first;
462       deadPass->releaseMemory();
463
464       std::map<AnalysisID, Pass*>::iterator Pos = 
465         AvailableAnalysis.find(deadPass->getPassInfo());
466       
467       assert (Pos != AvailableAnalysis.end() &&
468               "Pass is not available");
469       AvailableAnalysis.erase(Pos);
470     }
471   }
472 }
473
474 /// Add pass P into the PassVector. Update 
475 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
476 void PMDataManager::addPassToManager(Pass *P, 
477                                      bool ProcessAnalysis) {
478
479   if (ProcessAnalysis) {
480     // Take a note of analysis required and made available by this pass
481     initializeAnalysisImpl(P);
482     recordAvailableAnalysis(P);
483
484     // Remove the analysis not preserved by this pass
485     removeNotPreservedAnalysis(P);
486   }
487
488   // Add pass
489   PassVector.push_back(P);
490 }
491
492 // All Required analyses should be available to the pass as it runs!  Here
493 // we fill in the AnalysisImpls member of the pass so that it can
494 // successfully use the getAnalysis() method to retrieve the
495 // implementations it needs.
496 //
497 void PMDataManager::initializeAnalysisImpl(Pass *P) {
498   AnalysisUsage AnUsage;
499   P->getAnalysisUsage(AnUsage);
500  
501   for (std::vector<const PassInfo *>::const_iterator
502          I = AnUsage.getRequiredSet().begin(),
503          E = AnUsage.getRequiredSet().end(); I != E; ++I) {
504     Pass *Impl = getAnalysisPass(*I);
505     if (Impl == 0)
506       assert(0 && "Analysis used but not available!");
507     // TODO:  P->AnalysisImpls.push_back(std::make_pair(*I, Impl));
508   }
509 }
510
511 //===----------------------------------------------------------------------===//
512 // BasicBlockPassManager_New implementation
513
514 /// Add pass P into PassVector and return true. If this pass is not
515 /// manageable by this manager then return false.
516 bool
517 BasicBlockPassManager_New::addPass(Pass *P) {
518
519   BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
520   if (!BP)
521     return false;
522
523   // If this pass does not preserve anlysis that is used by other passes
524   // managed by this manager than it is not a suiable pass for this manager.
525   if (!manageablePass(P))
526     return false;
527
528   addPassToManager (BP);
529
530   return true;
531 }
532
533 /// Execute all of the passes scheduled for execution by invoking 
534 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
535 /// the function, and if so, return true.
536 bool
537 BasicBlockPassManager_New::runOnFunction(Function &F) {
538
539   bool Changed = false;
540   initializeAnalysisInfo();
541
542   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
543     for (std::vector<Pass *>::iterator itr = passVectorBegin(),
544            e = passVectorEnd(); itr != e; ++itr) {
545       Pass *P = *itr;
546       
547       recordAvailableAnalysis(P);
548       BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P);
549       Changed |= BP->runOnBasicBlock(*I);
550       removeNotPreservedAnalysis(P);
551       removeDeadPasses(P);
552     }
553   return Changed;
554 }
555
556 /// Return true IFF AnalysisID AID is currently available.
557 Pass * BasicBlockPassManager_New::getAnalysisPassFromManager(AnalysisID AID) {
558   return getAnalysisPass(AID);
559 }
560
561 //===----------------------------------------------------------------------===//
562 // FunctionPassManager_New implementation
563
564 /// Create new Function pass manager
565 FunctionPassManager_New::FunctionPassManager_New() {
566   FPM = new FunctionPassManagerImpl_New();
567 }
568
569 /// add - Add a pass to the queue of passes to run.  This passes
570 /// ownership of the Pass to the PassManager.  When the
571 /// PassManager_X is destroyed, the pass will be destroyed as well, so
572 /// there is no need to delete the pass. (TODO delete passes.)
573 /// This implies that all passes MUST be allocated with 'new'.
574 void FunctionPassManager_New::add(Pass *P) { 
575   FPM->add(P);
576 }
577
578 /// Execute all of the passes scheduled for execution.  Keep
579 /// track of whether any of the passes modifies the function, and if
580 /// so, return true.
581 bool FunctionPassManager_New::runOnModule(Module &M) {
582   return FPM->runOnModule(M);
583 }
584
585 /// run - Execute all of the passes scheduled for execution.  Keep
586 /// track of whether any of the passes modifies the function, and if
587 /// so, return true.
588 ///
589 bool FunctionPassManager_New::run(Function &F) {
590   std::string errstr;
591   if (MP->materializeFunction(&F, &errstr)) {
592     cerr << "Error reading bytecode file: " << errstr << "\n";
593     abort();
594   }
595   return FPM->runOnFunction(F);
596 }
597
598
599 /// doInitialization - Run all of the initializers for the function passes.
600 ///
601 bool FunctionPassManager_New::doInitialization() {
602   return FPM->doInitialization(*MP->getModule());
603 }
604
605 /// doFinalization - Run all of the initializers for the function passes.
606 ///
607 bool FunctionPassManager_New::doFinalization() {
608   return FPM->doFinalization(*MP->getModule());
609 }
610
611 //===----------------------------------------------------------------------===//
612 // FunctionPassManagerImpl_New implementation
613
614 /// Add pass P into the pass manager queue. If P is a BasicBlockPass then
615 /// either use it into active basic block pass manager or create new basic
616 /// block pass manager to handle pass P.
617 bool
618 FunctionPassManagerImpl_New::addPass(Pass *P) {
619
620   // If P is a BasicBlockPass then use BasicBlockPassManager_New.
621   if (BasicBlockPass *BP = dynamic_cast<BasicBlockPass*>(P)) {
622
623     if (!activeBBPassManager
624         || !activeBBPassManager->addPass(BP)) {
625
626       activeBBPassManager = new BasicBlockPassManager_New();
627       addPassToManager(activeBBPassManager, false);
628       if (!activeBBPassManager->addPass(BP))
629         assert(0 && "Unable to add Pass");
630     }
631     return true;
632   }
633
634   FunctionPass *FP = dynamic_cast<FunctionPass *>(P);
635   if (!FP)
636     return false;
637
638   // If this pass does not preserve anlysis that is used by other passes
639   // managed by this manager than it is not a suiable pass for this manager.
640   if (!manageablePass(P))
641     return false;
642
643   addPassToManager (FP);
644   activeBBPassManager = NULL;
645   return true;
646 }
647
648 /// Execute all of the passes scheduled for execution by invoking 
649 /// runOnFunction method.  Keep track of whether any of the passes modifies 
650 /// the function, and if so, return true.
651 bool FunctionPassManagerImpl_New::runOnModule(Module &M) {
652
653   bool Changed = false;
654   initializeAnalysisInfo();
655
656   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
657     for (std::vector<Pass *>::iterator itr = passVectorBegin(),
658            e = passVectorEnd(); itr != e; ++itr) {
659       Pass *P = *itr;
660       
661       recordAvailableAnalysis(P);
662       FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
663       Changed |= FP->runOnFunction(*I);
664       removeNotPreservedAnalysis(P);
665       removeDeadPasses(P);
666     }
667   return Changed;
668 }
669
670 /// Execute all of the passes scheduled for execution by invoking 
671 /// runOnFunction method.  Keep track of whether any of the passes modifies 
672 /// the function, and if so, return true.
673 bool FunctionPassManagerImpl_New::runOnFunction(Function &F) {
674
675   bool Changed = false;
676   initializeAnalysisInfo();
677
678   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
679          e = passVectorEnd(); itr != e; ++itr) {
680     Pass *P = *itr;
681     
682     recordAvailableAnalysis(P);
683     FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
684     Changed |= FP->runOnFunction(F);
685     removeNotPreservedAnalysis(P);
686     removeDeadPasses(P);
687   }
688   return Changed;
689 }
690
691
692 /// Return true IFF AnalysisID AID is currently available.
693 Pass *FunctionPassManagerImpl_New::getAnalysisPassFromManager(AnalysisID AID) {
694
695   Pass *P = getAnalysisPass(AID);
696   if (P)
697     return P;
698
699   if (activeBBPassManager && 
700       activeBBPassManager->getAnalysisPass(AID) != 0)
701     return activeBBPassManager->getAnalysisPass(AID);
702
703   // TODO : Check inactive managers
704   return NULL;
705 }
706
707 inline bool FunctionPassManagerImpl_New::doInitialization(Module &M) {
708   bool Changed = false;
709
710   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
711          e = passVectorEnd(); itr != e; ++itr) {
712     Pass *P = *itr;
713     
714     FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
715     Changed |= FP->doInitialization(M);
716   }
717
718   return Changed;
719 }
720
721 inline bool FunctionPassManagerImpl_New::doFinalization(Module &M) {
722   bool Changed = false;
723
724   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
725          e = passVectorEnd(); itr != e; ++itr) {
726     Pass *P = *itr;
727     
728     FunctionPass *FP = dynamic_cast<FunctionPass*>(P);
729     Changed |= FP->doFinalization(M);
730   }
731
732
733   return Changed;
734 }
735
736 //===----------------------------------------------------------------------===//
737 // ModulePassManager implementation
738
739 /// Add P into pass vector if it is manageble. If P is a FunctionPass
740 /// then use FunctionPassManagerImpl_New to manage it. Return false if P
741 /// is not manageable by this manager.
742 bool
743 ModulePassManager_New::addPass(Pass *P) {
744
745   // If P is FunctionPass then use function pass maanager.
746   if (FunctionPass *FP = dynamic_cast<FunctionPass*>(P)) {
747
748     activeFunctionPassManager = NULL;
749
750     if (!activeFunctionPassManager
751         || !activeFunctionPassManager->addPass(P)) {
752
753       activeFunctionPassManager = new FunctionPassManagerImpl_New();
754       addPassToManager(activeFunctionPassManager, false);
755       if (!activeFunctionPassManager->addPass(FP))
756         assert(0 && "Unable to add pass");
757     }
758     return true;
759   }
760
761   ModulePass *MP = dynamic_cast<ModulePass *>(P);
762   if (!MP)
763     return false;
764
765   // If this pass does not preserve anlysis that is used by other passes
766   // managed by this manager than it is not a suiable pass for this manager.
767   if (!manageablePass(P))
768     return false;
769
770   addPassToManager(MP);
771   activeFunctionPassManager = NULL;
772   return true;
773 }
774
775
776 /// Execute all of the passes scheduled for execution by invoking 
777 /// runOnModule method.  Keep track of whether any of the passes modifies 
778 /// the module, and if so, return true.
779 bool
780 ModulePassManager_New::runOnModule(Module &M) {
781   bool Changed = false;
782   initializeAnalysisInfo();
783
784   for (std::vector<Pass *>::iterator itr = passVectorBegin(),
785          e = passVectorEnd(); itr != e; ++itr) {
786     Pass *P = *itr;
787
788     recordAvailableAnalysis(P);
789     ModulePass *MP = dynamic_cast<ModulePass*>(P);
790     Changed |= MP->runOnModule(M);
791     removeNotPreservedAnalysis(P);
792     removeDeadPasses(P);
793   }
794   return Changed;
795 }
796
797 /// Return true IFF AnalysisID AID is currently available.
798 Pass *ModulePassManager_New::getAnalysisPassFromManager(AnalysisID AID) {
799
800   
801   Pass *P = getAnalysisPass(AID);
802   if (P)
803     return P;
804
805   if (activeFunctionPassManager && 
806       activeFunctionPassManager->getAnalysisPass(AID) != 0)
807     return activeFunctionPassManager->getAnalysisPass(AID);
808
809   // TODO : Check inactive managers
810   return NULL;
811 }
812
813 //===----------------------------------------------------------------------===//
814 // PassManagerImpl implementation
815
816 /// Return true IFF AnalysisID AID is currently available.
817 Pass *PassManagerImpl_New::getAnalysisPassFromManager(AnalysisID AID) {
818
819   Pass *P = NULL;
820   for (std::vector<ModulePassManager_New *>::iterator itr = PassManagers.begin(),
821          e = PassManagers.end(); !P && itr != e; ++itr)
822     P  = (*itr)->getAnalysisPassFromManager(AID);
823   return P;
824 }
825
826 /// Schedule pass P for execution. Make sure that passes required by
827 /// P are run before P is run. Update analysis info maintained by
828 /// the manager. Remove dead passes. This is a recursive function.
829 void PassManagerImpl_New::schedulePass(Pass *P) {
830
831   AnalysisUsage AnUsage;
832   P->getAnalysisUsage(AnUsage);
833   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
834   for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
835          E = RequiredSet.end(); I != E; ++I) {
836
837     Pass *AnalysisPass = getAnalysisPassFromManager(*I);
838     if (!AnalysisPass) {
839       // Schedule this analysis run first.
840       AnalysisPass = (*I)->createPass();
841       schedulePass(AnalysisPass);
842     }
843     setLastUser (AnalysisPass, P);
844
845     // Prolong live range of analyses that are needed after an analysis pass
846     // is destroyed, for querying by subsequent passes
847     const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
848     for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
849            E = IDs.end(); I != E; ++I) {
850       Pass *AP = getAnalysisPassFromManager(*I);
851       assert (AP && "Analysis pass is not available");
852       setLastUser(AP, P);
853     }
854   }
855   addPass(P);
856 }
857
858 /// Schedule all passes from the queue by adding them in their
859 /// respective manager's queue. 
860 void PassManagerImpl_New::schedulePasses() {
861   for (std::vector<Pass *>::iterator I = passVectorBegin(),
862          E = passVectorEnd(); I != E; ++I)
863     schedulePass (*I);
864 }
865
866 /// Add pass P to the queue of passes to run.
867 void PassManagerImpl_New::add(Pass *P) {
868   // Do not process Analysis now. Analysis is process while scheduling
869   // the pass vector.
870   addPassToManager(P, false);
871 }
872
873 // PassManager_New implementation
874 /// Add P into active pass manager or use new module pass manager to
875 /// manage it.
876 bool PassManagerImpl_New::addPass(Pass *P) {
877
878   if (!activeManager || !activeManager->addPass(P)) {
879     activeManager = new ModulePassManager_New();
880     PassManagers.push_back(activeManager);
881   }
882
883   return activeManager->addPass(P);
884 }
885
886 /// run - Execute all of the passes scheduled for execution.  Keep track of
887 /// whether any of the passes modifies the module, and if so, return true.
888 bool PassManagerImpl_New::run(Module &M) {
889
890   schedulePasses();
891   bool Changed = false;
892   for (std::vector<ModulePassManager_New *>::iterator itr = PassManagers.begin(),
893          e = PassManagers.end(); itr != e; ++itr) {
894     ModulePassManager_New *pm = *itr;
895     Changed |= pm->runOnModule(M);
896   }
897   return Changed;
898 }
899
900 //===----------------------------------------------------------------------===//
901 // PassManager implementation
902
903 /// Create new pass manager
904 PassManager_New::PassManager_New() {
905   PM = new PassManagerImpl_New();
906 }
907
908 /// add - Add a pass to the queue of passes to run.  This passes ownership of
909 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
910 /// will be destroyed as well, so there is no need to delete the pass.  This
911 /// implies that all passes MUST be allocated with 'new'.
912 void 
913 PassManager_New::add(Pass *P) {
914   PM->add(P);
915 }
916
917 /// run - Execute all of the passes scheduled for execution.  Keep track of
918 /// whether any of the passes modifies the module, and if so, return true.
919 bool
920 PassManager_New::run(Module &M) {
921   return PM->run(M);
922 }
923