Dramatically simplify how -time-passes works.
[oota-llvm.git] / lib / VMCore / PassManagerT.h
1 //===- PassManagerT.h - Container for Passes ---------------------*- C++ -*--=//
2 //
3 // This file defines the PassManagerT class.  This class is used to hold,
4 // maintain, and optimize execution of Pass's.  The PassManager class ensures
5 // that analysis results are available before a pass runs, and that Pass's are
6 // destroyed when the PassManager is destroyed.
7 //
8 // The PassManagerT template is instantiated three times to do its job.  The
9 // public PassManager class is a Pimpl around the PassManagerT<Module> interface
10 // to avoid having all of the PassManager clients being exposed to the
11 // implementation details herein.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_PASSMANAGER_T_H
16 #define LLVM_PASSMANAGER_T_H
17
18 #include "llvm/Pass.h"
19 #include "Support/CommandLine.h"
20 #include "Support/LeakDetector.h"
21 #include "Support/Timer.h"
22 #include <algorithm>
23 #include <iostream>
24 class Annotable;
25
26 //===----------------------------------------------------------------------===//
27 // Pass debugging information.  Often it is useful to find out what pass is
28 // running when a crash occurs in a utility.  When this library is compiled with
29 // debugging on, a command line option (--debug-pass) is enabled that causes the
30 // pass name to be printed before it executes.
31 //
32
33 // Different debug levels that can be enabled...
34 enum PassDebugLevel {
35   None, Arguments, Structure, Executions, Details
36 };
37
38 static cl::opt<enum PassDebugLevel>
39 PassDebugging("debug-pass", cl::Hidden,
40               cl::desc("Print PassManager debugging information"),
41               cl::values(
42   clEnumVal(None      , "disable debug output"),
43   clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
44   clEnumVal(Structure , "print pass structure before run()"),
45   clEnumVal(Executions, "print pass name before it is executed"),
46   clEnumVal(Details   , "print pass details when it is executed"),
47                          0));
48
49 //===----------------------------------------------------------------------===//
50 // PMDebug class - a set of debugging functions, that are not to be
51 // instantiated by the template.
52 //
53 struct PMDebug {
54   static void PerformPassStartupStuff(Pass *P) {
55     // If debugging is enabled, print out argument information...
56     if (PassDebugging >= Arguments) {
57       std::cerr << "Pass Arguments: ";
58       PrintArgumentInformation(P);
59       std::cerr << "\n";
60
61       // Print the pass execution structure
62       if (PassDebugging >= Structure)
63         P->dumpPassStructure();
64     }
65   }
66
67   static void PrintArgumentInformation(const Pass *P);
68   static void PrintPassInformation(unsigned,const char*,Pass *, Annotable *);
69   static void PrintAnalysisSetInfo(unsigned,const char*,Pass *P,
70                                    const std::vector<AnalysisID> &);
71 };
72
73
74 //===----------------------------------------------------------------------===//
75 // TimingInfo Class - This class is used to calculate information about the
76 // amount of time each pass takes to execute.  This only happens when
77 // -time-passes is enabled on the command line.
78 //
79
80 class TimingInfo {
81   std::map<Pass*, Timer> TimingData;
82   TimerGroup TG;
83
84   // Private ctor, must use 'create' member
85   TimingInfo() : TG("... Pass execution timing report ...") {}
86 public:
87   // TimingDtor - Print out information about timing information
88   ~TimingInfo() {
89     // Delete all of the timers...
90     TimingData.clear();
91     // TimerGroup is deleted next, printing the report.
92   }
93
94   // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
95   // to a non null value (if the -time-passes option is enabled) or it leaves it
96   // null.  It may be called multiple times.
97   static void createTheTimeInfo();
98
99   void passStarted(Pass *P) {
100     if (dynamic_cast<AnalysisResolver*>(P)) return;
101     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
102     if (I == TimingData.end())
103       I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
104     I->second.startTimer();
105   }
106   void passEnded(Pass *P) {
107     if (dynamic_cast<AnalysisResolver*>(P)) return;
108     std::map<Pass*, Timer>::iterator I = TimingData.find(P);
109     assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
110     I->second.stopTimer();
111   }
112 };
113
114 static TimingInfo *TheTimeInfo;
115
116 //===----------------------------------------------------------------------===//
117 // Declare the PassManagerTraits which will be specialized...
118 //
119 template<class UnitType> class PassManagerTraits;   // Do not define.
120
121
122 //===----------------------------------------------------------------------===//
123 // PassManagerT - Container object for passes.  The PassManagerT destructor
124 // deletes all passes contained inside of the PassManagerT, so you shouldn't 
125 // delete passes manually, and all passes should be dynamically allocated.
126 //
127 template<typename UnitType>
128 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
129   typedef PassManagerTraits<UnitType> Traits;
130   typedef typename Traits::PassClass       PassClass;
131   typedef typename Traits::SubPassClass SubPassClass;
132   typedef typename Traits::BatcherClass BatcherClass;
133   typedef typename Traits::ParentClass   ParentClass;
134
135   friend class PassManagerTraits<UnitType>::PassClass;
136   friend class PassManagerTraits<UnitType>::SubPassClass;  
137   friend class Traits;
138   friend class ImmutablePass;
139
140   std::vector<PassClass*> Passes;    // List of passes to run
141   std::vector<ImmutablePass*> ImmutablePasses;  // List of immutable passes
142
143   // The parent of this pass manager...
144   ParentClass * const Parent;
145
146   // The current batcher if one is in use, or null
147   BatcherClass *Batcher;
148
149   // CurrentAnalyses - As the passes are being run, this map contains the
150   // analyses that are available to the current pass for use.  This is accessed
151   // through the getAnalysis() function in this class and in Pass.
152   //
153   std::map<AnalysisID, Pass*> CurrentAnalyses;
154
155   // LastUseOf - This map keeps track of the last usage in our pipeline of a
156   // particular pass.  When executing passes, the memory for .first is free'd
157   // after .second is run.
158   //
159   std::map<Pass*, Pass*> LastUseOf;
160
161 public:
162   PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
163   ~PassManagerT() {
164     // Delete all of the contained passes...
165     for (typename std::vector<PassClass*>::iterator
166            I = Passes.begin(), E = Passes.end(); I != E; ++I)
167       delete *I;
168
169     for (std::vector<ImmutablePass*>::iterator
170            I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
171       delete *I;
172   }
173
174   // run - Run all of the queued passes on the specified module in an optimal
175   // way.
176   virtual bool runOnUnit(UnitType *M) {
177     bool MadeChanges = false;
178     closeBatcher();
179     CurrentAnalyses.clear();
180
181     TimingInfo::createTheTimeInfo();
182
183     // Add any immutable passes to the CurrentAnalyses set...
184     for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
185       ImmutablePass *IPass = ImmutablePasses[i];
186       if (const PassInfo *PI = IPass->getPassInfo()) {
187         CurrentAnalyses[PI] = IPass;
188
189         const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
190         for (unsigned i = 0, e = II.size(); i != e; ++i)
191           CurrentAnalyses[II[i]] = IPass;
192       }
193     }
194
195     // LastUserOf - This contains the inverted LastUseOfMap...
196     std::map<Pass *, std::vector<Pass*> > LastUserOf;
197     for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
198                                           E = LastUseOf.end(); I != E; ++I)
199       LastUserOf[I->second].push_back(I->first);
200
201
202     // Output debug information...
203     if (Parent == 0) PMDebug::PerformPassStartupStuff(this);
204
205     // Run all of the passes
206     for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
207       PassClass *P = Passes[i];
208       
209       PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
210                                     (Annotable*)M);
211
212       // Get information about what analyses the pass uses...
213       AnalysisUsage AnUsage;
214       P->getAnalysisUsage(AnUsage);
215       PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
216                                     AnUsage.getRequiredSet());
217
218       // All Required analyses should be available to the pass as it runs!  Here
219       // we fill in the AnalysisImpls member of the pass so that it can
220       // successfully use the getAnalysis() method to retrieve the
221       // implementations it needs.
222       //
223       P->AnalysisImpls.clear();
224       P->AnalysisImpls.reserve(AnUsage.getRequiredSet().size());
225       for (std::vector<const PassInfo *>::const_iterator
226              I = AnUsage.getRequiredSet().begin(), 
227              E = AnUsage.getRequiredSet().end(); I != E; ++I) {
228         Pass *Impl = getAnalysisOrNullUp(*I);
229         if (Impl == 0) {
230           std::cerr << "Analysis '" << (*I)->getPassName()
231                     << "' used but not available!";
232           assert(0 && "Analysis used but not available!");
233         } else if (PassDebugging == Details) {
234           if ((*I)->getPassName() != std::string(Impl->getPassName()))
235             std::cerr << "    Interface '" << (*I)->getPassName()
236                     << "' implemented by '" << Impl->getPassName() << "'\n";
237         }
238         P->AnalysisImpls.push_back(std::make_pair(*I, Impl));
239       }
240
241       // Run the sub pass!
242       if (TheTimeInfo) TheTimeInfo->passStarted(P);
243       bool Changed = runPass(P, M);
244       if (TheTimeInfo) TheTimeInfo->passEnded(P);
245       MadeChanges |= Changed;
246
247       // Check for memory leaks by the pass...
248       LeakDetector::checkForGarbage(std::string("after running pass '") +
249                                     P->getPassName() + "'");
250
251       if (Changed)
252         PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
253                                       (Annotable*)M);
254       PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
255                                     AnUsage.getPreservedSet());
256
257
258       // Erase all analyses not in the preserved set...
259       if (!AnUsage.getPreservesAll()) {
260         const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
261         for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
262                E = CurrentAnalyses.end(); I != E; )
263           if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
264               PreservedSet.end())
265             ++I; // This analysis is preserved, leave it in the available set...
266           else {
267             if (!dynamic_cast<ImmutablePass*>(I->second)) {
268               std::map<AnalysisID, Pass*>::iterator J = I++;
269               CurrentAnalyses.erase(J);   // Analysis not preserved!
270             } else {
271               ++I;
272             }
273           }
274       }
275
276       // Add the current pass to the set of passes that have been run, and are
277       // thus available to users.
278       //
279       if (const PassInfo *PI = P->getPassInfo()) {
280         CurrentAnalyses[PI] = P;
281
282         // This pass is the current implementation of all of the interfaces it
283         // implements as well.
284         //
285         const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
286         for (unsigned i = 0, e = II.size(); i != e; ++i)
287           CurrentAnalyses[II[i]] = P;
288       }
289
290       // Free memory for any passes that we are the last use of...
291       std::vector<Pass*> &DeadPass = LastUserOf[P];
292       for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
293            I != E; ++I) {
294         PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
295                                       (Annotable*)M);
296         (*I)->releaseMemory();
297       }
298
299       // Make sure to remove dead passes from the CurrentAnalyses list...
300       for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin();
301            I != CurrentAnalyses.end(); ) {
302         std::vector<Pass*>::iterator DPI = std::find(DeadPass.begin(),
303                                                      DeadPass.end(), I->second);
304         if (DPI != DeadPass.end()) {    // This pass is dead now... remove it
305           std::map<AnalysisID, Pass*>::iterator IDead = I++;
306           CurrentAnalyses.erase(IDead);
307         } else {
308           ++I;  // Move on to the next element...
309         }
310       }
311     }
312
313     return MadeChanges;
314   }
315
316   // dumpPassStructure - Implement the -debug-passes=PassStructure option
317   virtual void dumpPassStructure(unsigned Offset = 0) {
318     // Print out the immutable passes...
319     for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i)
320       ImmutablePasses[i]->dumpPassStructure(0);
321
322     std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
323               << " Pass Manager\n";
324     for (typename std::vector<PassClass*>::iterator
325            I = Passes.begin(), E = Passes.end(); I != E; ++I) {
326       PassClass *P = *I;
327       P->dumpPassStructure(Offset+1);
328
329       // Loop through and see which classes are destroyed after this one...
330       for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
331                                             E = LastUseOf.end(); I != E; ++I) {
332         if (P == I->second) {
333           std::cerr << "--" << std::string(Offset*2, ' ');
334           I->first->dumpPassStructure(0);
335         }
336       }
337     }
338   }
339
340   Pass *getImmutablePassOrNull(const PassInfo *ID) const {
341     for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
342       const PassInfo *IPID = ImmutablePasses[i]->getPassInfo();
343       if (IPID == ID)
344         return ImmutablePasses[i];
345       
346       // This pass is the current implementation of all of the interfaces it
347       // implements as well.
348       //
349       const std::vector<const PassInfo*> &II =
350         IPID->getInterfacesImplemented();
351       for (unsigned j = 0, e = II.size(); j != e; ++j)
352         if (II[j] == ID) return ImmutablePasses[i];
353     }
354     return 0;
355   }
356
357   Pass *getAnalysisOrNullDown(const PassInfo *ID) const {
358     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
359
360     if (I != CurrentAnalyses.end())
361       return I->second;  // Found it.
362
363     if (Pass *P = getImmutablePassOrNull(ID))
364       return P;
365
366     if (Batcher)
367       return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
368     return 0;
369   }
370
371   Pass *getAnalysisOrNullUp(const PassInfo *ID) const {
372     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
373     if (I != CurrentAnalyses.end())
374       return I->second;  // Found it.
375
376     if (Parent)          // Try scanning...
377       return Parent->getAnalysisOrNullUp(ID);
378     else if (!ImmutablePasses.empty())
379       return getImmutablePassOrNull(ID);
380     return 0;
381   }
382
383   // markPassUsed - Inform higher level pass managers (and ourselves)
384   // that these analyses are being used by this pass.  This is used to
385   // make sure that analyses are not free'd before we have to use
386   // them...
387   //
388   void markPassUsed(const PassInfo *P, Pass *User) {
389     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(P);
390
391     if (I != CurrentAnalyses.end()) {
392       LastUseOf[I->second] = User;    // Local pass, extend the lifetime
393     } else {
394       // Pass not in current available set, must be a higher level pass
395       // available to us, propagate to parent pass manager...  We tell the
396       // parent that we (the passmanager) are using the analysis so that it
397       // frees the analysis AFTER this pass manager runs.
398       //
399       if (Parent) {
400         Parent->markPassUsed(P, this);
401       } else {
402         assert(getAnalysisOrNullUp(P) && 
403                dynamic_cast<ImmutablePass*>(getAnalysisOrNullUp(P)) &&
404                "Pass available but not found! "
405                "Perhaps this is a module pass requiring a function pass?");
406       }
407     }
408   }
409   
410   // Return the number of parent PassManagers that exist
411   virtual unsigned getDepth() const {
412     if (Parent == 0) return 0;
413     return 1 + Parent->getDepth();
414   }
415
416   virtual unsigned getNumContainedPasses() const { return Passes.size(); }
417   virtual const Pass *getContainedPass(unsigned N) const {
418     assert(N < Passes.size() && "Pass number out of range!");
419     return Passes[N];
420   }
421
422   // add - Add a pass to the queue of passes to run.  This gives ownership of
423   // the Pass to the PassManager.  When the PassManager is destroyed, the pass
424   // will be destroyed as well, so there is no need to delete the pass.  This
425   // implies that all passes MUST be new'd.
426   //
427   void add(PassClass *P) {
428     // Get information about what analyses the pass uses...
429     AnalysisUsage AnUsage;
430     P->getAnalysisUsage(AnUsage);
431     const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
432
433     // Loop over all of the analyses used by this pass,
434     for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
435            E = Required.end(); I != E; ++I) {
436       if (getAnalysisOrNullDown(*I) == 0)
437         add((PassClass*)(*I)->createPass());
438     }
439
440     // Tell the pass to add itself to this PassManager... the way it does so
441     // depends on the class of the pass, and is critical to laying out passes in
442     // an optimal order..
443     //
444     P->addToPassManager(this, AnUsage);
445   }
446
447 private:
448
449   // addPass - These functions are used to implement the subclass specific
450   // behaviors present in PassManager.  Basically the add(Pass*) method ends up
451   // reflecting its behavior into a Pass::addToPassManager call.  Subclasses of
452   // Pass override it specifically so that they can reflect the type
453   // information inherent in "this" back to the PassManager.
454   //
455   // For generic Pass subclasses (which are interprocedural passes), we simply
456   // add the pass to the end of the pass list and terminate any accumulation of
457   // FunctionPass's that are present.
458   //
459   void addPass(PassClass *P, AnalysisUsage &AnUsage) {
460     const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
461
462     // FIXME: If this pass being added isn't killed by any of the passes in the
463     // batcher class then we can reorder to pass to execute before the batcher
464     // does, which will potentially allow us to batch more passes!
465     //
466     //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
467     if (Batcher /*&& ProvidedSet.empty()*/)
468       closeBatcher();                     // This pass cannot be batched!
469     
470     // Set the Resolver instance variable in the Pass so that it knows where to 
471     // find this object...
472     //
473     setAnalysisResolver(P, this);
474     Passes.push_back(P);
475
476     // Inform higher level pass managers (and ourselves) that these analyses are
477     // being used by this pass.  This is used to make sure that analyses are not
478     // free'd before we have to use them...
479     //
480     for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
481            E = RequiredSet.end(); I != E; ++I)
482       markPassUsed(*I, P);     // Mark *I as used by P
483
484     // Erase all analyses not in the preserved set...
485     if (!AnUsage.getPreservesAll()) {
486       const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
487       for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
488              E = CurrentAnalyses.end(); I != E; ) {
489         if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) ==
490             PreservedSet.end()) {             // Analysis not preserved!
491           CurrentAnalyses.erase(I);           // Remove from available analyses
492           I = CurrentAnalyses.begin();
493         } else {
494           ++I;
495         }
496       }
497     }
498
499     // Add this pass to the currently available set...
500     if (const PassInfo *PI = P->getPassInfo()) {
501       CurrentAnalyses[PI] = P;
502
503       // This pass is the current implementation of all of the interfaces it
504       // implements as well.
505       //
506       const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
507       for (unsigned i = 0, e = II.size(); i != e; ++i)
508         CurrentAnalyses[II[i]] = P;
509     }
510
511     // For now assume that our results are never used...
512     LastUseOf[P] = P;
513   }
514   
515   // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
516   // together in a BatcherClass object so that all of the analyses are run
517   // together a function at a time.
518   //
519   void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
520     if (Batcher == 0) // If we don't have a batcher yet, make one now.
521       Batcher = new BatcherClass(this);
522     // The Batcher will queue the passes up
523     MP->addToPassManager(Batcher, AnUsage);
524   }
525
526   // closeBatcher - Terminate the batcher that is being worked on.
527   void closeBatcher() {
528     if (Batcher) {
529       Passes.push_back(Batcher);
530       Batcher = 0;
531     }
532   }
533
534 public:
535   // When an ImmutablePass is added, it gets added to the top level pass
536   // manager.
537   void addPass(ImmutablePass *IP, AnalysisUsage &AU) {
538     if (Parent) { // Make sure this request goes to the top level passmanager...
539       Parent->addPass(IP, AU);
540       return;
541     }
542
543     // Set the Resolver instance variable in the Pass so that it knows where to 
544     // find this object...
545     //
546     setAnalysisResolver(IP, this);
547     ImmutablePasses.push_back(IP);
548
549     // All Required analyses should be available to the pass as it initializes!
550     // Here we fill in the AnalysisImpls member of the pass so that it can
551     // successfully use the getAnalysis() method to retrieve the implementations
552     // it needs.
553     //
554     IP->AnalysisImpls.clear();
555     IP->AnalysisImpls.reserve(AU.getRequiredSet().size());
556     for (std::vector<const PassInfo *>::const_iterator 
557            I = AU.getRequiredSet().begin(),
558            E = AU.getRequiredSet().end(); I != E; ++I) {
559       Pass *Impl = getAnalysisOrNullUp(*I);
560       if (Impl == 0) {
561         std::cerr << "Analysis '" << (*I)->getPassName()
562                   << "' used but not available!";
563         assert(0 && "Analysis used but not available!");
564       } else if (PassDebugging == Details) {
565         if ((*I)->getPassName() != std::string(Impl->getPassName()))
566           std::cerr << "    Interface '" << (*I)->getPassName()
567                     << "' implemented by '" << Impl->getPassName() << "'\n";
568       }
569       IP->AnalysisImpls.push_back(std::make_pair(*I, Impl));
570     }
571     
572     // Initialize the immutable pass...
573     IP->initializePass();
574   }
575 };
576
577
578
579 //===----------------------------------------------------------------------===//
580 // PassManagerTraits<BasicBlock> Specialization
581 //
582 // This pass manager is used to group together all of the BasicBlockPass's
583 // into a single unit.
584 //
585 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
586   // PassClass - The type of passes tracked by this PassManager
587   typedef BasicBlockPass PassClass;
588
589   // SubPassClass - The types of classes that should be collated together
590   // This is impossible to match, so BasicBlock instantiations of PassManagerT
591   // do not collate.
592   //
593   typedef PassManagerT<Module> SubPassClass;
594
595   // BatcherClass - The type to use for collation of subtypes... This class is
596   // never instantiated for the PassManager<BasicBlock>, but it must be an 
597   // instance of PassClass to typecheck.
598   //
599   typedef PassClass BatcherClass;
600
601   // ParentClass - The type of the parent PassManager...
602   typedef PassManagerT<Function> ParentClass;
603
604   // PMType - The type of the passmanager that subclasses this class
605   typedef PassManagerT<BasicBlock> PMType;
606
607   // runPass - Specify how the pass should be run on the UnitType
608   static bool runPass(PassClass *P, BasicBlock *M) {
609     // todo, init and finalize
610     return P->runOnBasicBlock(*M);
611   }
612
613   // getPMName() - Return the name of the unit the PassManager operates on for
614   // debugging.
615   const char *getPMName() const { return "BasicBlock"; }
616   virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
617
618   // Implement the BasicBlockPass interface...
619   virtual bool doInitialization(Module &M);
620   virtual bool doInitialization(Function &F);
621   virtual bool runOnBasicBlock(BasicBlock &BB);
622   virtual bool doFinalization(Function &F);
623   virtual bool doFinalization(Module &M);
624
625   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
626     AU.setPreservesAll();
627   }
628 };
629
630
631
632 //===----------------------------------------------------------------------===//
633 // PassManagerTraits<Function> Specialization
634 //
635 // This pass manager is used to group together all of the FunctionPass's
636 // into a single unit.
637 //
638 template<> struct PassManagerTraits<Function> : public FunctionPass {
639   // PassClass - The type of passes tracked by this PassManager
640   typedef FunctionPass PassClass;
641
642   // SubPassClass - The types of classes that should be collated together
643   typedef BasicBlockPass SubPassClass;
644
645   // BatcherClass - The type to use for collation of subtypes...
646   typedef PassManagerT<BasicBlock> BatcherClass;
647
648   // ParentClass - The type of the parent PassManager...
649   typedef PassManagerT<Module> ParentClass;
650
651   // PMType - The type of the passmanager that subclasses this class
652   typedef PassManagerT<Function> PMType;
653
654   // runPass - Specify how the pass should be run on the UnitType
655   static bool runPass(PassClass *P, Function *F) {
656     return P->runOnFunction(*F);
657   }
658
659   // getPMName() - Return the name of the unit the PassManager operates on for
660   // debugging.
661   const char *getPMName() const { return "Function"; }
662   virtual const char *getPassName() const { return "Function Pass Manager"; }
663
664   // Implement the FunctionPass interface...
665   virtual bool doInitialization(Module &M);
666   virtual bool runOnFunction(Function &F);
667   virtual bool doFinalization(Module &M);
668
669   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
670     AU.setPreservesAll();
671   }
672 };
673
674
675
676 //===----------------------------------------------------------------------===//
677 // PassManagerTraits<Module> Specialization
678 //
679 // This is the top level PassManager implementation that holds generic passes.
680 //
681 template<> struct PassManagerTraits<Module> : public Pass {
682   // PassClass - The type of passes tracked by this PassManager
683   typedef Pass PassClass;
684
685   // SubPassClass - The types of classes that should be collated together
686   typedef FunctionPass SubPassClass;
687
688   // BatcherClass - The type to use for collation of subtypes...
689   typedef PassManagerT<Function> BatcherClass;
690
691   // ParentClass - The type of the parent PassManager...
692   typedef AnalysisResolver ParentClass;
693
694   // runPass - Specify how the pass should be run on the UnitType
695   static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
696
697   // getPMName() - Return the name of the unit the PassManager operates on for
698   // debugging.
699   const char *getPMName() const { return "Module"; }
700   virtual const char *getPassName() const { return "Module Pass Manager"; }
701
702   // run - Implement the PassManager interface...
703   bool run(Module &M) {
704     return ((PassManagerT<Module>*)this)->runOnUnit(&M);
705   }
706 };
707
708
709
710 //===----------------------------------------------------------------------===//
711 // PassManagerTraits Method Implementations
712 //
713
714 // PassManagerTraits<BasicBlock> Implementations
715 //
716 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
717   bool Changed = false;
718   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
719     ((PMType*)this)->Passes[i]->doInitialization(M);
720   return Changed;
721 }
722
723 inline bool PassManagerTraits<BasicBlock>::doInitialization(Function &F) {
724   bool Changed = false;
725   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
726     ((PMType*)this)->Passes[i]->doInitialization(F);
727   return Changed;
728 }
729
730 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
731   return ((PMType*)this)->runOnUnit(&BB);
732 }
733
734 inline bool PassManagerTraits<BasicBlock>::doFinalization(Function &F) {
735   bool Changed = false;
736   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
737     ((PMType*)this)->Passes[i]->doFinalization(F);
738   return Changed;
739 }
740
741 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
742   bool Changed = false;
743   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
744     ((PMType*)this)->Passes[i]->doFinalization(M);
745   return Changed;
746 }
747
748
749 // PassManagerTraits<Function> Implementations
750 //
751 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
752   bool Changed = false;
753   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
754     ((PMType*)this)->Passes[i]->doInitialization(M);
755   return Changed;
756 }
757
758 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
759   return ((PMType*)this)->runOnUnit(&F);
760 }
761
762 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
763   bool Changed = false;
764   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
765     ((PMType*)this)->Passes[i]->doFinalization(M);
766   return Changed;
767 }
768
769 #endif