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