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