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