Remove dead code.
[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/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include <vector>
23 #include <map>
24
25 using namespace llvm;
26 class llvm::PMDataManager;
27 class llvm::PMStack;
28
29 //===----------------------------------------------------------------------===//
30 // Overview:
31 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
32 // 
33 //   o Manage optimization pass execution order
34 //   o Make required Analysis information available before pass P is run
35 //   o Release memory occupied by dead passes
36 //   o If Analysis information is dirtied by a pass then regenerate Analysis 
37 //     information before it is consumed by another pass.
38 //
39 // Pass Manager Infrastructure uses multiple pass managers.  They are
40 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
41 // This class hierarcy uses multiple inheritance but pass managers do not derive
42 // from another pass manager.
43 //
44 // PassManager and FunctionPassManager are two top-level pass manager that
45 // represents the external interface of this entire pass manager infrastucture.
46 //
47 // Important classes :
48 //
49 // [o] class PMTopLevelManager;
50 //
51 // Two top level managers, PassManager and FunctionPassManager, derive from 
52 // PMTopLevelManager. PMTopLevelManager manages information used by top level 
53 // managers such as last user info.
54 //
55 // [o] class PMDataManager;
56 //
57 // PMDataManager manages information, e.g. list of available analysis info, 
58 // used by a pass manager to manage execution order of passes. It also provides
59 // a place to implement common pass manager APIs. All pass managers derive from
60 // PMDataManager.
61 //
62 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
63 //
64 // BBPassManager manages BasicBlockPasses.
65 //
66 // [o] class FunctionPassManager;
67 //
68 // This is a external interface used by JIT to manage FunctionPasses. This
69 // interface relies on FunctionPassManagerImpl to do all the tasks.
70 //
71 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
72 //                                     public PMTopLevelManager;
73 //
74 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
75 //
76 // [o] class FPPassManager : public ModulePass, public PMDataManager;
77 //
78 // FPPassManager manages FunctionPasses and BBPassManagers
79 //
80 // [o] class MPPassManager : public Pass, public PMDataManager;
81 //
82 // MPPassManager manages ModulePasses and FPPassManagers
83 //
84 // [o] class PassManager;
85 //
86 // This is a external interface used by various tools to manages passes. It
87 // relies on PassManagerImpl to do all the tasks.
88 //
89 // [o] class PassManagerImpl : public Pass, public PMDataManager,
90 //                             public PMDTopLevelManager
91 //
92 // PassManagerImpl is a top level pass manager responsible for managing
93 // MPPassManagers.
94 //===----------------------------------------------------------------------===//
95
96 namespace llvm {
97
98 //===----------------------------------------------------------------------===//
99 // Pass debugging information.  Often it is useful to find out what pass is
100 // running when a crash occurs in a utility.  When this library is compiled with
101 // debugging on, a command line option (--debug-pass) is enabled that causes the
102 // pass name to be printed before it executes.
103 //
104
105 // Different debug levels that can be enabled...
106 enum PassDebugLevel {
107   None, Arguments, Structure, Executions, Details
108 };
109
110 static cl::opt<enum PassDebugLevel>
111 PassDebugging_New("debug-pass", cl::Hidden,
112                   cl::desc("Print PassManager debugging information"),
113                   cl::values(
114   clEnumVal(None      , "disable debug output"),
115   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
116   clEnumVal(Structure , "print pass structure before run()"),
117   clEnumVal(Executions, "print pass name before it is executed"),
118   clEnumVal(Details   , "print pass details when it is executed"),
119                              clEnumValEnd));
120 } // End of llvm namespace
121
122 namespace {
123
124 //===----------------------------------------------------------------------===//
125 // PMTopLevelManager
126 //
127 /// PMTopLevelManager manages LastUser info and collects common APIs used by
128 /// top level pass managers.
129 class VISIBILITY_HIDDEN PMTopLevelManager {
130 public:
131
132   virtual unsigned getNumContainedManagers() {
133     return PassManagers.size();
134   }
135
136   /// Schedule pass P for execution. Make sure that passes required by
137   /// P are run before P is run. Update analysis info maintained by
138   /// the manager. Remove dead passes. This is a recursive function.
139   void schedulePass(Pass *P);
140
141   /// This is implemented by top level pass manager and used by 
142   /// schedulePass() to add analysis info passes that are not available.
143   virtual void addTopLevelPass(Pass  *P) = 0;
144
145   /// Set pass P as the last user of the given analysis passes.
146   void setLastUser(std::vector<Pass *> &AnalysisPasses, Pass *P);
147
148   /// Collect passes whose last user is P
149   void collectLastUses(std::vector<Pass *> &LastUses, Pass *P);
150
151   /// Find the pass that implements Analysis AID. Search immutable
152   /// passes and all pass managers. If desired pass is not found
153   /// then return NULL.
154   Pass *findAnalysisPass(AnalysisID AID);
155
156   virtual ~PMTopLevelManager() {
157     for (std::vector<Pass *>::iterator I = PassManagers.begin(),
158            E = PassManagers.end(); I != E; ++I)
159       delete *I;
160
161     for (std::vector<ImmutablePass *>::iterator
162            I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
163       delete *I;
164
165     PassManagers.clear();
166   }
167
168   /// Add immutable pass and initialize it.
169   inline void addImmutablePass(ImmutablePass *P) {
170     P->initializePass();
171     ImmutablePasses.push_back(P);
172   }
173
174   inline std::vector<ImmutablePass *>& getImmutablePasses() {
175     return ImmutablePasses;
176   }
177
178   void addPassManager(Pass *Manager) {
179     PassManagers.push_back(Manager);
180   }
181
182   // Add Manager into the list of managers that are not directly
183   // maintained by this top level pass manager
184   inline void addIndirectPassManager(PMDataManager *Manager) {
185     IndirectPassManagers.push_back(Manager);
186   }
187
188   // Print passes managed by this top level manager.
189   void dumpPasses() const;
190   void dumpArguments() const;
191
192   void initializeAllAnalysisInfo();
193
194   // Active Pass Managers
195   PMStack activeStack;
196
197 protected:
198   
199   /// Collection of pass managers
200   std::vector<Pass *> PassManagers;
201
202 private:
203
204   /// Collection of pass managers that are not directly maintained
205   /// by this pass manager
206   std::vector<PMDataManager *> IndirectPassManagers;
207
208   // Map to keep track of last user of the analysis pass.
209   // LastUser->second is the last user of Lastuser->first.
210   std::map<Pass *, Pass *> LastUser;
211
212   /// Immutable passes are managed by top level manager.
213   std::vector<ImmutablePass *> ImmutablePasses;
214 };
215
216 } // End of anon namespace
217   
218 //===----------------------------------------------------------------------===//
219 // PMDataManager
220
221 namespace llvm {
222 /// PMDataManager provides the common place to manage the analysis data
223 /// used by pass managers.
224 class PMDataManager {
225 public:
226   PMDataManager(int Depth) : TPM(NULL), Depth(Depth) {
227     initializeAnalysisInfo();
228   }
229
230   virtual ~PMDataManager() {
231
232     for (std::vector<Pass *>::iterator I = PassVector.begin(),
233            E = PassVector.end(); I != E; ++I)
234       delete *I;
235
236     PassVector.clear();
237   }
238
239   /// Return true IFF pass P's required analysis set does not required new
240   /// manager.
241   bool manageablePass(Pass *P);
242
243   /// Augment AvailableAnalysis by adding analysis made available by pass P.
244   void recordAvailableAnalysis(Pass *P);
245
246   /// Remove Analysis that is not preserved by the pass
247   void removeNotPreservedAnalysis(Pass *P);
248   
249   /// Remove dead passes
250   void removeDeadPasses(Pass *P, std::string &Msg);
251
252   /// Add pass P into the PassVector. Update 
253   /// AvailableAnalysis appropriately if ProcessAnalysis is true.
254   void addPassToManager(Pass *P, bool ProcessAnalysis = true);
255
256   /// Initialize available analysis information.
257   void initializeAnalysisInfo() { 
258     TransferLastUses.clear();
259     AvailableAnalysis.clear();
260   }
261
262   /// Populate RequiredPasses with the analysis pass that are required by
263   /// pass P.
264   void collectRequiredAnalysisPasses(std::vector<Pass *> &RequiredPasses,
265                                      Pass *P);
266
267   /// All Required analyses should be available to the pass as it runs!  Here
268   /// we fill in the AnalysisImpls member of the pass so that it can
269   /// successfully use the getAnalysis() method to retrieve the
270   /// implementations it needs.
271   void initializeAnalysisImpl(Pass *P);
272
273   /// Find the pass that implements Analysis AID. If desired pass is not found
274   /// then return NULL.
275   Pass *findAnalysisPass(AnalysisID AID, bool Direction);
276
277   // Access toplevel manager
278   PMTopLevelManager *getTopLevelManager() { return TPM; }
279   void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
280
281   unsigned getDepth() const { return Depth; }
282
283   // Print routines used by debug-pass
284   void dumpLastUses(Pass *P, unsigned Offset) const;
285   void dumpPassArguments() const;
286   void dumpPassInfo(Pass *P,  std::string &Msg1, std::string &Msg2) const;
287   void dumpAnalysisSetInfo(const char *Msg, Pass *P,
288                            const std::vector<AnalysisID> &Set) const;
289
290   std::vector<Pass *>& getTransferredLastUses() {
291     return TransferLastUses;
292   }
293
294   virtual unsigned getNumContainedPasses() { 
295     return PassVector.size();
296   }
297
298   virtual PassManagerType getPassManagerType() { 
299     assert ( 0 && "Invalid use of getPassManagerType");
300     return PMT_Unknown; 
301   }
302 protected:
303
304   // If a FunctionPass F is the last user of ModulePass info M
305   // then the F's manager, not F, records itself as a last user of M.
306   // Current pass manage is requesting parent manager to record parent
307   // manager as the last user of these TrransferLastUses passes.
308   std::vector<Pass *> TransferLastUses;
309
310   // Top level manager.
311   PMTopLevelManager *TPM;
312
313   // Collection of pass that are managed by this manager
314   std::vector<Pass *> PassVector;
315
316 private:
317   // Set of available Analysis. This information is used while scheduling 
318   // pass. If a pass requires an analysis which is not not available then 
319   // equired analysis pass is scheduled to run before the pass itself is 
320   // scheduled to run.
321   std::map<AnalysisID, Pass*> AvailableAnalysis;
322
323   unsigned Depth;
324 };
325
326 //===----------------------------------------------------------------------===//
327 // BBPassManager
328 //
329 /// BBPassManager manages BasicBlockPass. It batches all the
330 /// pass together and sequence them to process one basic block before
331 /// processing next basic block.
332 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager, 
333                                         public FunctionPass {
334
335 public:
336   BBPassManager(int Depth) : PMDataManager(Depth) { }
337
338   /// Execute all of the passes scheduled for execution.  Keep track of
339   /// whether any of the passes modifies the function, and if so, return true.
340   bool runOnFunction(Function &F);
341
342   /// Pass Manager itself does not invalidate any analysis info.
343   void getAnalysisUsage(AnalysisUsage &Info) const {
344     Info.setPreservesAll();
345   }
346
347   bool doInitialization(Module &M);
348   bool doInitialization(Function &F);
349   bool doFinalization(Module &M);
350   bool doFinalization(Function &F);
351
352   // Print passes managed by this manager
353   void dumpPassStructure(unsigned Offset) {
354     llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
355     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
356       BasicBlockPass *BP = getContainedPass(Index);
357       BP->dumpPassStructure(Offset + 1);
358       dumpLastUses(BP, Offset+1);
359     }
360   }
361
362   BasicBlockPass *getContainedPass(unsigned N) {
363     assert ( N < PassVector.size() && "Pass number out of range!");
364     BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
365     return BP;
366   }
367
368   virtual PassManagerType getPassManagerType() { 
369     return PMT_BasicBlockPassManager; 
370   }
371 };
372
373 //===----------------------------------------------------------------------===//
374 // FPPassManager
375 //
376 /// FPPassManager manages BBPassManagers and FunctionPasses.
377 /// It batches all function passes and basic block pass managers together and 
378 /// sequence them to process one function at a time before processing next 
379 /// function.
380
381 class FPPassManager : public ModulePass, public PMDataManager {
382  
383 public:
384   FPPassManager(int Depth) : PMDataManager(Depth) { }
385   
386   /// run - Execute all of the passes scheduled for execution.  Keep track of
387   /// whether any of the passes modifies the module, and if so, return true.
388   bool runOnFunction(Function &F);
389   bool runOnModule(Module &M);
390
391   /// doInitialization - Run all of the initializers for the function passes.
392   ///
393   bool doInitialization(Module &M);
394   
395   /// doFinalization - Run all of the initializers for the function passes.
396   ///
397   bool doFinalization(Module &M);
398
399   /// Pass Manager itself does not invalidate any analysis info.
400   void getAnalysisUsage(AnalysisUsage &Info) const {
401     Info.setPreservesAll();
402   }
403
404   // Print passes managed by this manager
405   void dumpPassStructure(unsigned Offset) {
406     llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
407     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
408       FunctionPass *FP = getContainedPass(Index);
409       FP->dumpPassStructure(Offset + 1);
410       dumpLastUses(FP, Offset+1);
411     }
412   }
413
414   FunctionPass *getContainedPass(unsigned N) {
415     assert ( N < PassVector.size() && "Pass number out of range!");
416     FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
417     return FP;
418   }
419
420   virtual PassManagerType getPassManagerType() { 
421     return PMT_FunctionPassManager; 
422   }
423 };
424
425 //===----------------------------------------------------------------------===//
426 // FunctionPassManagerImpl
427 //
428 /// FunctionPassManagerImpl manages FPPassManagers
429 class FunctionPassManagerImpl : public Pass,
430                                 public PMDataManager,
431                                 public PMTopLevelManager {
432 public:
433
434   FunctionPassManagerImpl(int Depth) : PMDataManager(Depth) { }
435
436   /// add - Add a pass to the queue of passes to run.  This passes ownership of
437   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
438   /// will be destroyed as well, so there is no need to delete the pass.  This
439   /// implies that all passes MUST be allocated with 'new'.
440   void add(Pass *P) {
441     schedulePass(P);
442   }
443  
444   /// run - Execute all of the passes scheduled for execution.  Keep track of
445   /// whether any of the passes modifies the module, and if so, return true.
446   bool run(Function &F);
447
448   /// doInitialization - Run all of the initializers for the function passes.
449   ///
450   bool doInitialization(Module &M);
451   
452   /// doFinalization - Run all of the initializers for the function passes.
453   ///
454   bool doFinalization(Module &M);
455
456   /// Pass Manager itself does not invalidate any analysis info.
457   void getAnalysisUsage(AnalysisUsage &Info) const {
458     Info.setPreservesAll();
459   }
460
461   inline void addTopLevelPass(Pass *P) {
462
463     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
464       
465       // P is a immutable pass and it will be managed by this
466       // top level manager. Set up analysis resolver to connect them.
467       AnalysisResolver *AR = new AnalysisResolver(*this);
468       P->setResolver(AR);
469       initializeAnalysisImpl(P);
470       addImmutablePass(IP);
471       recordAvailableAnalysis(IP);
472     } else {
473       // Assign manager
474       if (activeStack.empty()) {
475         FPPassManager *FPP = new FPPassManager(getDepth() + 1);
476         FPP->setTopLevelManager(this->getTopLevelManager());
477         addPassManager(FPP);
478         activeStack.push(FPP);
479       }
480       P->assignPassManager(activeStack);
481     }
482
483   }
484
485   FPPassManager *getContainedManager(unsigned N) {
486     assert ( N < PassManagers.size() && "Pass number out of range!");
487     FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
488     return FP;
489   }
490
491 };
492
493 //===----------------------------------------------------------------------===//
494 // MPPassManager
495 //
496 /// MPPassManager manages ModulePasses and function pass managers.
497 /// It batches all Module passes  passes and function pass managers together and
498 /// sequence them to process one module.
499 class MPPassManager : public Pass, public PMDataManager {
500  
501 public:
502   MPPassManager(int Depth) : PMDataManager(Depth) { }
503   
504   /// run - Execute all of the passes scheduled for execution.  Keep track of
505   /// whether any of the passes modifies the module, and if so, return true.
506   bool runOnModule(Module &M);
507
508   /// Pass Manager itself does not invalidate any analysis info.
509   void getAnalysisUsage(AnalysisUsage &Info) const {
510     Info.setPreservesAll();
511   }
512
513   // Print passes managed by this manager
514   void dumpPassStructure(unsigned Offset) {
515     llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
516     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
517       ModulePass *MP = getContainedPass(Index);
518       MP->dumpPassStructure(Offset + 1);
519       dumpLastUses(MP, Offset+1);
520     }
521   }
522
523   ModulePass *getContainedPass(unsigned N) {
524     assert ( N < PassVector.size() && "Pass number out of range!");
525     ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
526     return MP;
527   }
528
529   virtual PassManagerType getPassManagerType() { return PMT_ModulePassManager; }
530 };
531
532 //===----------------------------------------------------------------------===//
533 // PassManagerImpl
534 //
535 /// PassManagerImpl manages MPPassManagers
536 class PassManagerImpl : public Pass,
537                         public PMDataManager,
538                         public PMTopLevelManager {
539
540 public:
541
542   PassManagerImpl(int Depth) : PMDataManager(Depth) { }
543
544   /// add - Add a pass to the queue of passes to run.  This passes ownership of
545   /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
546   /// will be destroyed as well, so there is no need to delete the pass.  This
547   /// implies that all passes MUST be allocated with 'new'.
548   void add(Pass *P) {
549     schedulePass(P);
550   }
551  
552   /// run - Execute all of the passes scheduled for execution.  Keep track of
553   /// whether any of the passes modifies the module, and if so, return true.
554   bool run(Module &M);
555
556   /// Pass Manager itself does not invalidate any analysis info.
557   void getAnalysisUsage(AnalysisUsage &Info) const {
558     Info.setPreservesAll();
559   }
560
561   inline void addTopLevelPass(Pass *P) {
562
563     if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
564       
565       // P is a immutable pass and it will be managed by this
566       // top level manager. Set up analysis resolver to connect them.
567       AnalysisResolver *AR = new AnalysisResolver(*this);
568       P->setResolver(AR);
569       initializeAnalysisImpl(P);
570       addImmutablePass(IP);
571       recordAvailableAnalysis(IP);
572     } else {
573
574       // Assign manager
575       if (activeStack.empty()) {
576         MPPassManager *MPP = new MPPassManager(getDepth() + 1);
577         MPP->setTopLevelManager(this->getTopLevelManager());
578         addPassManager(MPP);
579         activeStack.push(MPP);
580       }
581       
582       P->assignPassManager(activeStack);
583     }
584
585   }
586
587   MPPassManager *getContainedManager(unsigned N) {
588     assert ( N < PassManagers.size() && "Pass number out of range!");
589     MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
590     return MP;
591   }
592
593 };
594
595 } // End of llvm namespace
596
597 namespace {
598
599 //===----------------------------------------------------------------------===//
600 // TimingInfo Class - This class is used to calculate information about the
601 // amount of time each pass takes to execute.  This only happens when
602 // -time-passes is enabled on the command line.
603 //
604
605 class VISIBILITY_HIDDEN TimingInfo {
606   std::map<Pass*, Timer> TimingData;
607   TimerGroup TG;
608
609 public:
610   // Use 'create' member to get this.
611   TimingInfo() : TG("... Pass execution timing report ...") {}
612   
613   // TimingDtor - Print out information about timing information
614   ~TimingInfo() {
615     // Delete all of the timers...
616     TimingData.clear();
617     // TimerGroup is deleted next, printing the report.
618   }
619
620   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
621   // to a non null value (if the -time-passes option is enabled) or it leaves it
622   // null.  It may be called multiple times.
623   static void createTheTimeInfo();
624
625   void passStarted(Pass *P) {
626
627     if (dynamic_cast<PMDataManager *>(P)) 
628       return;
629
630     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
631     if (I == TimingData.end())
632       I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
633     I->second.startTimer();
634   }
635   void passEnded(Pass *P) {
636
637     if (dynamic_cast<PMDataManager *>(P)) 
638       return;
639
640     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
641     assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
642     I->second.stopTimer();
643   }
644 };
645
646 static TimingInfo *TheTimeInfo;
647
648 } // End of anon namespace
649
650 //===----------------------------------------------------------------------===//
651 // PMTopLevelManager implementation
652
653 /// Set pass P as the last user of the given analysis passes.
654 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses, 
655                                     Pass *P) {
656
657   for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
658          E = AnalysisPasses.end(); I != E; ++I) {
659     Pass *AP = *I;
660     LastUser[AP] = P;
661     // If AP is the last user of other passes then make P last user of
662     // such passes.
663     for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
664            LUE = LastUser.end(); LUI != LUE; ++LUI) {
665       if (LUI->second == AP)
666         LastUser[LUI->first] = P;
667     }
668   }
669 }
670
671 /// Collect passes whose last user is P
672 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
673                                             Pass *P) {
674    for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
675           LUE = LastUser.end(); LUI != LUE; ++LUI)
676       if (LUI->second == P)
677         LastUses.push_back(LUI->first);
678 }
679
680 /// Schedule pass P for execution. Make sure that passes required by
681 /// P are run before P is run. Update analysis info maintained by
682 /// the manager. Remove dead passes. This is a recursive function.
683 void PMTopLevelManager::schedulePass(Pass *P) {
684
685   // TODO : Allocate function manager for this pass, other wise required set
686   // may be inserted into previous function manager
687
688   AnalysisUsage AnUsage;
689   P->getAnalysisUsage(AnUsage);
690   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
691   for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
692          E = RequiredSet.end(); I != E; ++I) {
693
694     Pass *AnalysisPass = findAnalysisPass(*I);
695     if (!AnalysisPass) {
696       // Schedule this analysis run first.
697       AnalysisPass = (*I)->createPass();
698       schedulePass(AnalysisPass);
699     }
700   }
701
702   // Now all required passes are available.
703   addTopLevelPass(P);
704 }
705
706 /// Find the pass that implements Analysis AID. Search immutable
707 /// passes and all pass managers. If desired pass is not found
708 /// then return NULL.
709 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
710
711   Pass *P = NULL;
712   // Check pass managers
713   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
714          E = PassManagers.end(); P == NULL && I != E; ++I) {
715     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
716     assert(PMD && "This is not a PassManager");
717     P = PMD->findAnalysisPass(AID, false);
718   }
719
720   // Check other pass managers
721   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
722          E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
723     P = (*I)->findAnalysisPass(AID, false);
724
725   for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
726          E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
727     const PassInfo *PI = (*I)->getPassInfo();
728     if (PI == AID)
729       P = *I;
730
731     // If Pass not found then check the interfaces implemented by Immutable Pass
732     if (!P) {
733       const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
734       if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
735         P = *I;
736     }
737   }
738
739   return P;
740 }
741
742 // Print passes managed by this top level manager.
743 void PMTopLevelManager::dumpPasses() const {
744
745   if (PassDebugging_New < Structure)
746     return;
747
748   // Print out the immutable passes
749   for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
750     ImmutablePasses[i]->dumpPassStructure(0);
751   }
752   
753   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
754          E = PassManagers.end(); I != E; ++I)
755     (*I)->dumpPassStructure(1);
756 }
757
758 void PMTopLevelManager::dumpArguments() const {
759
760   if (PassDebugging_New < Arguments)
761     return;
762
763   cerr << "Pass Arguments: ";
764   for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
765          E = PassManagers.end(); I != E; ++I) {
766     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
767     assert(PMD && "This is not a PassManager");
768     PMD->dumpPassArguments();
769   }
770   cerr << "\n";
771 }
772
773 void PMTopLevelManager::initializeAllAnalysisInfo() {
774   
775   for (std::vector<Pass *>::iterator I = PassManagers.begin(),
776          E = PassManagers.end(); I != E; ++I) {
777     PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
778     assert(PMD && "This is not a PassManager");
779     PMD->initializeAnalysisInfo();
780   }
781   
782   // Initailize other pass managers
783   for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
784          E = IndirectPassManagers.end(); I != E; ++I)
785     (*I)->initializeAnalysisInfo();
786 }
787
788 //===----------------------------------------------------------------------===//
789 // PMDataManager implementation
790
791 /// Return true IFF pass P's required analysis set does not required new
792 /// manager.
793 bool PMDataManager::manageablePass(Pass *P) {
794
795   // TODO 
796   // If this pass is not preserving information that is required by a
797   // pass maintained by higher level pass manager then do not insert
798   // this pass into current manager. Use new manager. For example,
799   // For example, If FunctionPass F is not preserving ModulePass Info M1
800   // that is used by another ModulePass M2 then do not insert F in
801   // current function pass manager.
802   return true;
803 }
804
805 /// Augement AvailableAnalysis by adding analysis made available by pass P.
806 void PMDataManager::recordAvailableAnalysis(Pass *P) {
807                                                 
808   if (const PassInfo *PI = P->getPassInfo()) {
809     AvailableAnalysis[PI] = P;
810
811     //This pass is the current implementation of all of the interfaces it
812     //implements as well.
813     const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
814     for (unsigned i = 0, e = II.size(); i != e; ++i)
815       AvailableAnalysis[II[i]] = P;
816   }
817 }
818
819 /// Remove Analyss not preserved by Pass P
820 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
821   AnalysisUsage AnUsage;
822   P->getAnalysisUsage(AnUsage);
823
824   if (AnUsage.getPreservesAll())
825     return;
826
827   const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
828   for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
829          E = AvailableAnalysis.end(); I != E; ) {
830     std::map<AnalysisID, Pass*>::iterator Info = I++;
831     if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) == 
832         PreservedSet.end()) {
833       // Remove this analysis
834       if (!dynamic_cast<ImmutablePass*>(Info->second))
835         AvailableAnalysis.erase(Info);
836     }
837   }
838 }
839
840 /// Remove analysis passes that are not used any longer
841 void PMDataManager::removeDeadPasses(Pass *P, std::string &Msg) {
842
843   std::vector<Pass *> DeadPasses;
844   TPM->collectLastUses(DeadPasses, P);
845
846   for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
847          E = DeadPasses.end(); I != E; ++I) {
848
849     std::string Msg1 = "  Freeing Pass '";
850     dumpPassInfo(*I, Msg1, Msg);
851
852     if (TheTimeInfo) TheTimeInfo->passStarted(P);
853     (*I)->releaseMemory();
854     if (TheTimeInfo) TheTimeInfo->passEnded(P);
855
856     std::map<AnalysisID, Pass*>::iterator Pos = 
857       AvailableAnalysis.find((*I)->getPassInfo());
858     
859     // It is possible that pass is already removed from the AvailableAnalysis
860     if (Pos != AvailableAnalysis.end())
861       AvailableAnalysis.erase(Pos);
862   }
863 }
864
865 /// Add pass P into the PassVector. Update 
866 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
867 void PMDataManager::addPassToManager(Pass *P, 
868                                      bool ProcessAnalysis) {
869
870   // This manager is going to manage pass P. Set up analysis resolver
871   // to connect them.
872   AnalysisResolver *AR = new AnalysisResolver(*this);
873   P->setResolver(AR);
874
875   if (ProcessAnalysis) {
876
877     // At the moment, this pass is the last user of all required passes.
878     std::vector<Pass *> LastUses;
879     std::vector<Pass *> RequiredPasses;
880     unsigned PDepth = this->getDepth();
881
882     collectRequiredAnalysisPasses(RequiredPasses, P);
883     for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
884            E = RequiredPasses.end(); I != E; ++I) {
885       Pass *PRequired = *I;
886       unsigned RDepth = 0;
887
888       PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
889       RDepth = DM.getDepth();
890
891       if (PDepth == RDepth)
892         LastUses.push_back(PRequired);
893       else if (PDepth >  RDepth) {
894         // Let the parent claim responsibility of last use
895         TransferLastUses.push_back(PRequired);
896       } else {
897         // Note : This feature is not yet implemented
898         assert (0 && 
899                 "Unable to handle Pass that requires lower level Analysis pass");
900       }
901     }
902
903     LastUses.push_back(P);
904     TPM->setLastUser(LastUses, P);
905
906     // Take a note of analysis required and made available by this pass.
907     // Remove the analysis not preserved by this pass
908     removeNotPreservedAnalysis(P);
909     recordAvailableAnalysis(P);
910   }
911
912   // Add pass
913   PassVector.push_back(P);
914 }
915
916 /// Populate RequiredPasses with the analysis pass that are required by
917 /// pass P.
918 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
919                                                   Pass *P) {
920   AnalysisUsage AnUsage;
921   P->getAnalysisUsage(AnUsage);
922   const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
923   for (std::vector<AnalysisID>::const_iterator 
924          I = RequiredSet.begin(), E = RequiredSet.end();
925        I != E; ++I) {
926     Pass *AnalysisPass = findAnalysisPass(*I, true);
927     assert (AnalysisPass && "Analysis pass is not available");
928     RP.push_back(AnalysisPass);
929   }
930
931   const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
932   for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
933          E = IDs.end(); I != E; ++I) {
934     Pass *AnalysisPass = findAnalysisPass(*I, true);
935     assert (AnalysisPass && "Analysis pass is not available");
936     RP.push_back(AnalysisPass);
937   }
938 }
939
940 // All Required analyses should be available to the pass as it runs!  Here
941 // we fill in the AnalysisImpls member of the pass so that it can
942 // successfully use the getAnalysis() method to retrieve the
943 // implementations it needs.
944 //
945 void PMDataManager::initializeAnalysisImpl(Pass *P) {
946   AnalysisUsage AnUsage;
947   P->getAnalysisUsage(AnUsage);
948  
949   for (std::vector<const PassInfo *>::const_iterator
950          I = AnUsage.getRequiredSet().begin(),
951          E = AnUsage.getRequiredSet().end(); I != E; ++I) {
952     Pass *Impl = findAnalysisPass(*I, true);
953     if (Impl == 0)
954       assert(0 && "Analysis used but not available!");
955     AnalysisResolver *AR = P->getResolver();
956     AR->addAnalysisImplsPair(*I, Impl);
957   }
958 }
959
960 /// Find the pass that implements Analysis AID. If desired pass is not found
961 /// then return NULL.
962 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
963
964   // Check if AvailableAnalysis map has one entry.
965   std::map<AnalysisID, Pass*>::const_iterator I =  AvailableAnalysis.find(AID);
966
967   if (I != AvailableAnalysis.end())
968     return I->second;
969
970   // Search Parents through TopLevelManager
971   if (SearchParent)
972     return TPM->findAnalysisPass(AID);
973   
974   return NULL;
975 }
976
977 // Print list of passes that are last used by P.
978 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
979
980   std::vector<Pass *> LUses;
981   
982   assert (TPM && "Top Level Manager is missing");
983   TPM->collectLastUses(LUses, P);
984   
985   for (std::vector<Pass *>::iterator I = LUses.begin(),
986          E = LUses.end(); I != E; ++I) {
987     llvm::cerr << "--" << std::string(Offset*2, ' ');
988     (*I)->dumpPassStructure(0);
989   }
990 }
991
992 void PMDataManager::dumpPassArguments() const {
993   for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
994         E = PassVector.end(); I != E; ++I) {
995     if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
996       PMD->dumpPassArguments();
997     else
998       if (const PassInfo *PI = (*I)->getPassInfo())
999         if (!PI->isAnalysisGroup())
1000           cerr << " -" << PI->getPassArgument();
1001   }
1002 }
1003
1004 void PMDataManager:: dumpPassInfo(Pass *P,  std::string &Msg1, 
1005                                   std::string &Msg2) const {
1006   if (PassDebugging_New < Executions)
1007     return;
1008   cerr << (void*)this << std::string(getDepth()*2+1, ' ');
1009   cerr << Msg1;
1010   cerr << P->getPassName();
1011   cerr << Msg2;
1012 }
1013
1014 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
1015                                         const std::vector<AnalysisID> &Set) 
1016   const {
1017   if (PassDebugging_New >= Details && !Set.empty()) {
1018     cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1019       for (unsigned i = 0; i != Set.size(); ++i) {
1020         if (i) cerr << ",";
1021         cerr << " " << Set[i]->getPassName();
1022       }
1023       cerr << "\n";
1024   }
1025 }
1026
1027 //===----------------------------------------------------------------------===//
1028 // NOTE: Is this the right place to define this method ?
1029 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
1030 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
1031   return PM.findAnalysisPass(ID, dir);
1032 }
1033
1034 //===----------------------------------------------------------------------===//
1035 // BBPassManager implementation
1036
1037 /// Execute all of the passes scheduled for execution by invoking 
1038 /// runOnBasicBlock method.  Keep track of whether any of the passes modifies 
1039 /// the function, and if so, return true.
1040 bool
1041 BBPassManager::runOnFunction(Function &F) {
1042
1043   if (F.isExternal())
1044     return false;
1045
1046   bool Changed = doInitialization(F);
1047
1048   std::string Msg1 = "Executing Pass '";
1049   std::string Msg3 = "' Made Modification '";
1050
1051   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1052     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1053       BasicBlockPass *BP = getContainedPass(Index);
1054       AnalysisUsage AnUsage;
1055       BP->getAnalysisUsage(AnUsage);
1056
1057       std::string Msg2 = "' on BasicBlock '" + (*I).getName() + "'...\n";
1058       dumpPassInfo(BP, Msg1, Msg2);
1059       dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
1060
1061       initializeAnalysisImpl(BP);
1062
1063       if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1064       Changed |= BP->runOnBasicBlock(*I);
1065       if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1066
1067       if (Changed)
1068         dumpPassInfo(BP, Msg3, Msg2);
1069       dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
1070
1071       removeNotPreservedAnalysis(BP);
1072       recordAvailableAnalysis(BP);
1073       removeDeadPasses(BP, Msg2);
1074     }
1075   return Changed |= doFinalization(F);
1076 }
1077
1078 // Implement doInitialization and doFinalization
1079 inline bool BBPassManager::doInitialization(Module &M) {
1080   bool Changed = false;
1081
1082   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1083     BasicBlockPass *BP = getContainedPass(Index);
1084     Changed |= BP->doInitialization(M);
1085   }
1086
1087   return Changed;
1088 }
1089
1090 inline bool BBPassManager::doFinalization(Module &M) {
1091   bool Changed = false;
1092
1093   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1094     BasicBlockPass *BP = getContainedPass(Index);
1095     Changed |= BP->doFinalization(M);
1096   }
1097
1098   return Changed;
1099 }
1100
1101 inline bool BBPassManager::doInitialization(Function &F) {
1102   bool Changed = false;
1103
1104   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1105     BasicBlockPass *BP = getContainedPass(Index);
1106     Changed |= BP->doInitialization(F);
1107   }
1108
1109   return Changed;
1110 }
1111
1112 inline bool BBPassManager::doFinalization(Function &F) {
1113   bool Changed = false;
1114
1115   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1116     BasicBlockPass *BP = getContainedPass(Index);
1117     Changed |= BP->doFinalization(F);
1118   }
1119
1120   return Changed;
1121 }
1122
1123
1124 //===----------------------------------------------------------------------===//
1125 // FunctionPassManager implementation
1126
1127 /// Create new Function pass manager
1128 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1129   FPM = new FunctionPassManagerImpl(0);
1130   // FPM is the top level manager.
1131   FPM->setTopLevelManager(FPM);
1132
1133   PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
1134   AnalysisResolver *AR = new AnalysisResolver(*PMD);
1135   FPM->setResolver(AR);
1136   
1137   MP = P;
1138 }
1139
1140 FunctionPassManager::~FunctionPassManager() {
1141   delete FPM;
1142 }
1143
1144 /// add - Add a pass to the queue of passes to run.  This passes
1145 /// ownership of the Pass to the PassManager.  When the
1146 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1147 /// there is no need to delete the pass. (TODO delete passes.)
1148 /// This implies that all passes MUST be allocated with 'new'.
1149 void FunctionPassManager::add(Pass *P) { 
1150   FPM->add(P);
1151 }
1152
1153 /// run - Execute all of the passes scheduled for execution.  Keep
1154 /// track of whether any of the passes modifies the function, and if
1155 /// so, return true.
1156 ///
1157 bool FunctionPassManager::run(Function &F) {
1158   std::string errstr;
1159   if (MP->materializeFunction(&F, &errstr)) {
1160     cerr << "Error reading bytecode file: " << errstr << "\n";
1161     abort();
1162   }
1163   return FPM->run(F);
1164 }
1165
1166
1167 /// doInitialization - Run all of the initializers for the function passes.
1168 ///
1169 bool FunctionPassManager::doInitialization() {
1170   return FPM->doInitialization(*MP->getModule());
1171 }
1172
1173 /// doFinalization - Run all of the initializers for the function passes.
1174 ///
1175 bool FunctionPassManager::doFinalization() {
1176   return FPM->doFinalization(*MP->getModule());
1177 }
1178
1179 //===----------------------------------------------------------------------===//
1180 // FunctionPassManagerImpl implementation
1181 //
1182 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1183   bool Changed = false;
1184
1185   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1186     FPPassManager *FP = getContainedManager(Index);
1187     Changed |= FP->doInitialization(M);
1188   }
1189
1190   return Changed;
1191 }
1192
1193 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1194   bool Changed = false;
1195
1196   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1197     FPPassManager *FP = getContainedManager(Index);
1198     Changed |= FP->doFinalization(M);
1199   }
1200
1201   return Changed;
1202 }
1203
1204 // Execute all the passes managed by this top level manager.
1205 // Return true if any function is modified by a pass.
1206 bool FunctionPassManagerImpl::run(Function &F) {
1207
1208   bool Changed = false;
1209
1210   TimingInfo::createTheTimeInfo();
1211
1212   dumpArguments();
1213   dumpPasses();
1214
1215   initializeAllAnalysisInfo();
1216   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1217     FPPassManager *FP = getContainedManager(Index);
1218     Changed |= FP->runOnFunction(F);
1219   }
1220   return Changed;
1221 }
1222
1223 //===----------------------------------------------------------------------===//
1224 // FPPassManager implementation
1225
1226 /// Execute all of the passes scheduled for execution by invoking 
1227 /// runOnFunction method.  Keep track of whether any of the passes modifies 
1228 /// the function, and if so, return true.
1229 bool FPPassManager::runOnFunction(Function &F) {
1230
1231   bool Changed = false;
1232
1233   if (F.isExternal())
1234     return false;
1235
1236   std::string Msg1 = "Executing Pass '";
1237   std::string Msg3 = "' Made Modification '";
1238
1239   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1240     FunctionPass *FP = getContainedPass(Index);
1241
1242     AnalysisUsage AnUsage;
1243     FP->getAnalysisUsage(AnUsage);
1244
1245     std::string Msg2 = "' on Function '" + F.getName() + "'...\n";
1246     dumpPassInfo(FP, Msg1, Msg2);
1247     dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1248
1249     initializeAnalysisImpl(FP);
1250
1251     if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1252     Changed |= FP->runOnFunction(F);
1253     if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1254
1255     if (Changed)
1256       dumpPassInfo(FP, Msg3, Msg2);
1257     dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1258
1259     removeNotPreservedAnalysis(FP);
1260     recordAvailableAnalysis(FP);
1261     removeDeadPasses(FP, Msg2);
1262   }
1263   return Changed;
1264 }
1265
1266 bool FPPassManager::runOnModule(Module &M) {
1267
1268   bool Changed = doInitialization(M);
1269
1270   for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1271     this->runOnFunction(*I);
1272
1273   return Changed |= doFinalization(M);
1274 }
1275
1276 inline bool FPPassManager::doInitialization(Module &M) {
1277   bool Changed = false;
1278
1279   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1280     FunctionPass *FP = getContainedPass(Index);
1281     Changed |= FP->doInitialization(M);
1282   }
1283
1284   return Changed;
1285 }
1286
1287 inline bool FPPassManager::doFinalization(Module &M) {
1288   bool Changed = false;
1289
1290   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {  
1291     FunctionPass *FP = getContainedPass(Index);
1292     Changed |= FP->doFinalization(M);
1293   }
1294
1295   return Changed;
1296 }
1297
1298 //===----------------------------------------------------------------------===//
1299 // MPPassManager implementation
1300
1301 /// Execute all of the passes scheduled for execution by invoking 
1302 /// runOnModule method.  Keep track of whether any of the passes modifies 
1303 /// the module, and if so, return true.
1304 bool
1305 MPPassManager::runOnModule(Module &M) {
1306   bool Changed = false;
1307
1308   std::string Msg1 = "Executing Pass '";
1309   std::string Msg3 = "' Made Modification '";
1310
1311   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1312     ModulePass *MP = getContainedPass(Index);
1313
1314     AnalysisUsage AnUsage;
1315     MP->getAnalysisUsage(AnUsage);
1316
1317     std::string Msg2 = "' on Module '" + M.getModuleIdentifier() + "'...\n";
1318     dumpPassInfo(MP, Msg1, Msg2);
1319     dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1320
1321     initializeAnalysisImpl(MP);
1322
1323     if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1324     Changed |= MP->runOnModule(M);
1325     if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1326
1327     if (Changed)
1328       dumpPassInfo(MP, Msg3, Msg2);
1329     dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1330       
1331     removeNotPreservedAnalysis(MP);
1332     recordAvailableAnalysis(MP);
1333     removeDeadPasses(MP, Msg2);
1334   }
1335   return Changed;
1336 }
1337
1338 //===----------------------------------------------------------------------===//
1339 // PassManagerImpl implementation
1340 //
1341 /// run - Execute all of the passes scheduled for execution.  Keep track of
1342 /// whether any of the passes modifies the module, and if so, return true.
1343 bool PassManagerImpl::run(Module &M) {
1344
1345   bool Changed = false;
1346
1347   TimingInfo::createTheTimeInfo();
1348
1349   dumpArguments();
1350   dumpPasses();
1351
1352   initializeAllAnalysisInfo();
1353   for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {  
1354     MPPassManager *MP = getContainedManager(Index);
1355     Changed |= MP->runOnModule(M);
1356   }
1357   return Changed;
1358 }
1359
1360 //===----------------------------------------------------------------------===//
1361 // PassManager implementation
1362
1363 /// Create new pass manager
1364 PassManager::PassManager() {
1365   PM = new PassManagerImpl(0);
1366   // PM is the top level manager
1367   PM->setTopLevelManager(PM);
1368 }
1369
1370 PassManager::~PassManager() {
1371   delete PM;
1372 }
1373
1374 /// add - Add a pass to the queue of passes to run.  This passes ownership of
1375 /// the Pass to the PassManager.  When the PassManager is destroyed, the pass
1376 /// will be destroyed as well, so there is no need to delete the pass.  This
1377 /// implies that all passes MUST be allocated with 'new'.
1378 void 
1379 PassManager::add(Pass *P) {
1380   PM->add(P);
1381 }
1382
1383 /// run - Execute all of the passes scheduled for execution.  Keep track of
1384 /// whether any of the passes modifies the module, and if so, return true.
1385 bool
1386 PassManager::run(Module &M) {
1387   return PM->run(M);
1388 }
1389
1390 //===----------------------------------------------------------------------===//
1391 // TimingInfo Class - This class is used to calculate information about the
1392 // amount of time each pass takes to execute.  This only happens with
1393 // -time-passes is enabled on the command line.
1394 //
1395 bool llvm::TimePassesIsEnabled = false;
1396 static cl::opt<bool,true>
1397 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1398             cl::desc("Time each pass, printing elapsed time for each on exit"));
1399
1400 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1401 // a non null value (if the -time-passes option is enabled) or it leaves it
1402 // null.  It may be called multiple times.
1403 void TimingInfo::createTheTimeInfo() {
1404   if (!TimePassesIsEnabled || TheTimeInfo) return;
1405
1406   // Constructed the first time this is called, iff -time-passes is enabled.
1407   // This guarantees that the object will be constructed before static globals,
1408   // thus it will be destroyed before them.
1409   static ManagedStatic<TimingInfo> TTI;
1410   TheTimeInfo = &*TTI;
1411 }
1412
1413 //===----------------------------------------------------------------------===//
1414 // PMStack implementation
1415 //
1416
1417 // Pop Pass Manager from the stack and clear its analysis info.
1418 void PMStack::pop() {
1419
1420   PMDataManager *Top = this->top();
1421   Top->initializeAnalysisInfo();
1422
1423   S.pop_back();
1424 }
1425
1426 // Push PM on the stack and set its top level manager.
1427 void PMStack::push(Pass *P) {
1428
1429   PMDataManager *Top = NULL;
1430   PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1431   assert (PM && "Unable to push. Pass Manager expected");
1432
1433   if (this->empty()) {
1434     Top = PM;
1435   } 
1436   else {
1437     Top = this->top();
1438     PMTopLevelManager *TPM = Top->getTopLevelManager();
1439
1440     assert (TPM && "Unable to find top level manager");
1441     TPM->addIndirectPassManager(PM);
1442     PM->setTopLevelManager(TPM);
1443   }
1444
1445   AnalysisResolver *AR = new AnalysisResolver(*Top);
1446   P->setResolver(AR);
1447
1448   S.push_back(PM);
1449 }
1450
1451 // Dump content of the pass manager stack.
1452 void PMStack::dump() {
1453   for(std::deque<PMDataManager *>::iterator I = S.begin(),
1454         E = S.end(); I != E; ++I) {
1455     Pass *P = dynamic_cast<Pass *>(*I);
1456     printf ("%s ", P->getPassName());
1457   }
1458   if (!S.empty())
1459     printf ("\n");
1460 }
1461
1462 // Walk Pass Manager stack and set LastUse markers if any
1463 // manager is transfering this priviledge to its parent manager
1464 void PMStack::handleLastUserOverflow() {
1465
1466   for(PMStack::iterator I = this->begin(), E = this->end(); I != E;) {
1467
1468     PMDataManager *Child = *I++;
1469     if (I != E) {
1470       PMDataManager *Parent = *I++;
1471       PMTopLevelManager *TPM = Parent->getTopLevelManager();
1472       std::vector<Pass *> &TLU = Child->getTransferredLastUses();
1473       if (!TLU.empty()) {
1474         Pass *P = dynamic_cast<Pass *>(Parent);
1475         TPM->setLastUser(TLU, P);
1476       }
1477     }
1478   }
1479 }
1480
1481 /// Find appropriate Module Pass Manager in the PM Stack and
1482 /// add self into that manager. 
1483 void ModulePass::assignPassManager(PMStack &PMS) {
1484
1485   // Find Module Pass Manager
1486   while(!PMS.empty()) {
1487     if (PMS.top()->getPassManagerType() > PMT_ModulePassManager)
1488       PMS.pop();    // Pop children pass managers
1489     else
1490       break;
1491   }
1492   MPPassManager *MPP = dynamic_cast<MPPassManager *>(PMS.top());
1493
1494   assert(MPP && "Unable to find Module Pass Manager");
1495   MPP->addPassToManager(this);
1496 }
1497
1498 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1499 /// in the PM Stack and add self into that manager. 
1500 void FunctionPass::assignPassManager(PMStack &PMS) {
1501
1502   // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1503   while(!PMS.empty()) {
1504     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1505       PMS.pop();
1506     else
1507       break; 
1508   }
1509   FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1510
1511   // Create new Function Pass Manager
1512   if (!FPP) {
1513     assert(!PMS.empty() && "Unable to create Function Pass Manager");
1514     PMDataManager *PMD = PMS.top();
1515
1516     // [1] Create new Function Pass Manager
1517     FPP = new FPPassManager(PMD->getDepth() + 1);
1518
1519     // [2] Set up new manager's top level manager
1520     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1521     TPM->addIndirectPassManager(FPP);
1522
1523     // [3] Assign manager to manage this new manager. This may create
1524     // and push new managers into PMS
1525     Pass *P = dynamic_cast<Pass *>(FPP);
1526     P->assignPassManager(PMS);
1527
1528     // [4] Push new manager into PMS
1529     PMS.push(FPP);
1530   }
1531
1532   // Assign FPP as the manager of this pass.
1533   FPP->addPassToManager(this);
1534 }
1535
1536 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1537 /// in the PM Stack and add self into that manager. 
1538 void BasicBlockPass::assignPassManager(PMStack &PMS) {
1539
1540   BBPassManager *BBP = NULL;
1541
1542   // Basic Pass Manager is a leaf pass manager. It does not handle
1543   // any other pass manager.
1544   if (!PMS.empty()) {
1545     BBP = dynamic_cast<BBPassManager *>(PMS.top());
1546   }
1547
1548   // If leaf manager is not Basic Block Pass manager then create new
1549   // basic Block Pass manager.
1550
1551   if (!BBP) {
1552     assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1553     PMDataManager *PMD = PMS.top();
1554
1555     // [1] Create new Basic Block Manager
1556     BBP = new BBPassManager(PMD->getDepth() + 1);
1557
1558     // [2] Set up new manager's top level manager
1559     // Basic Block Pass Manager does not live by itself
1560     PMTopLevelManager *TPM = PMD->getTopLevelManager();
1561     TPM->addIndirectPassManager(BBP);
1562
1563     // [3] Assign manager to manage this new manager. This may create
1564     // and push new managers into PMS
1565     Pass *P = dynamic_cast<Pass *>(BBP);
1566     P->assignPassManager(PMS);
1567
1568     // [4] Push new manager into PMS
1569     PMS.push(BBP);
1570   }
1571
1572   // Assign BBP as the manager of this pass.
1573   BBP->addPassToManager(this);
1574 }
1575
1576