* Standardize how analysis results/passes as printed with the print() virtual
[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 <string>
20 #include <algorithm>
21 class Annotable;
22
23 //===----------------------------------------------------------------------===//
24 // PMDebug class - a set of debugging functions, that are not to be
25 // instantiated by the template.
26 //
27 struct PMDebug {
28   // If compiled in debug mode, these functions can be enabled by setting
29   // -debug-pass on the command line of the tool being used.
30   //
31   static void PrintPassStructure(Pass *P);
32   static void PrintPassInformation(unsigned,const char*,Pass *, Annotable *);
33   static void PrintAnalysisSetInfo(unsigned,const char*,Pass *P,
34                                    const std::vector<AnalysisID> &);
35 };
36
37
38 //===----------------------------------------------------------------------===//
39 // TimingInfo Class - This class is used to calculate information about the
40 // amount of time each pass takes to execute.  This only happens when
41 // -time-passes is enabled on the command line.
42 //
43 class TimingInfo {
44   std::map<Pass*, double> TimingData;
45   TimingInfo() {}   // Private ctor, must use create member
46 public:
47   // Create method.  If Timing is enabled, this creates and returns a new timing
48   // object, otherwise it returns null.
49   //
50   static TimingInfo *create();
51
52   // TimingDtor - Print out information about timing information
53   ~TimingInfo();
54
55   void passStarted(Pass *P);
56   void passEnded(Pass *P);
57 };
58
59
60
61 //===----------------------------------------------------------------------===//
62 // Declare the PassManagerTraits which will be specialized...
63 //
64 template<class UnitType> class PassManagerTraits;   // Do not define.
65
66
67 //===----------------------------------------------------------------------===//
68 // PassManagerT - Container object for passes.  The PassManagerT destructor
69 // deletes all passes contained inside of the PassManagerT, so you shouldn't 
70 // delete passes manually, and all passes should be dynamically allocated.
71 //
72 template<typename UnitType>
73 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
74   typedef PassManagerTraits<UnitType> Traits;
75   typedef typename Traits::PassClass       PassClass;
76   typedef typename Traits::SubPassClass SubPassClass;
77   typedef typename Traits::BatcherClass BatcherClass;
78   typedef typename Traits::ParentClass   ParentClass;
79
80   friend typename Traits::PassClass;
81   friend typename Traits::SubPassClass;  
82   friend class Traits;
83
84   std::vector<PassClass*> Passes;    // List of pass's to run
85
86   // The parent of this pass manager...
87   ParentClass * const Parent;
88
89   // The current batcher if one is in use, or null
90   BatcherClass *Batcher;
91
92   // CurrentAnalyses - As the passes are being run, this map contains the
93   // analyses that are available to the current pass for use.  This is accessed
94   // through the getAnalysis() function in this class and in Pass.
95   //
96   std::map<AnalysisID, Pass*> CurrentAnalyses;
97
98   // LastUseOf - This map keeps track of the last usage in our pipeline of a
99   // particular pass.  When executing passes, the memory for .first is free'd
100   // after .second is run.
101   //
102   std::map<Pass*, Pass*> LastUseOf;
103
104 public:
105   PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
106   ~PassManagerT() {
107     // Delete all of the contained passes...
108     for (typename std::vector<PassClass*>::iterator
109            I = Passes.begin(), E = Passes.end(); I != E; ++I)
110       delete *I;
111   }
112
113   // run - Run all of the queued passes on the specified module in an optimal
114   // way.
115   virtual bool runOnUnit(UnitType *M) {
116     bool MadeChanges = false;
117     closeBatcher();
118     CurrentAnalyses.clear();
119
120     // LastUserOf - This contains the inverted LastUseOfMap...
121     std::map<Pass *, std::vector<Pass*> > LastUserOf;
122     for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
123                                           E = LastUseOf.end(); I != E; ++I)
124       LastUserOf[I->second].push_back(I->first);
125
126
127     // Output debug information...
128     if (Parent == 0) PMDebug::PrintPassStructure(this);
129
130     // Run all of the passes
131     for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
132       PassClass *P = Passes[i];
133       
134       PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
135                                     (Annotable*)M);
136
137       // Get information about what analyses the pass uses...
138       AnalysisUsage AnUsage;
139       P->getAnalysisUsage(AnUsage);
140       PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
141                                     AnUsage.getRequiredSet());
142
143 #ifndef NDEBUG
144       // All Required analyses should be available to the pass as it runs!
145       for (std::vector<AnalysisID>::const_iterator
146              I = AnUsage.getRequiredSet().begin(), 
147              E = AnUsage.getRequiredSet().end(); I != E; ++I) {
148         assert(getAnalysisOrNullUp(*I) && "Analysis used but not available!");
149       }
150 #endif
151
152       // Run the sub pass!
153       startPass(P);
154       bool Changed = runPass(P, M);
155       endPass(P);
156       MadeChanges |= Changed;
157
158       if (Changed)
159         PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
160                                       (Annotable*)M);
161       PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
162                                     AnUsage.getPreservedSet());
163       PMDebug::PrintAnalysisSetInfo(getDepth(), "Provided", P,
164                                     AnUsage.getProvidedSet());
165
166
167       // Erase all analyses not in the preserved set...
168       if (!AnUsage.preservesAll()) {
169         const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
170         for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
171                E = CurrentAnalyses.end(); I != E; )
172           if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
173               PreservedSet.end())
174             ++I; // This analysis is preserved, leave it in the available set...
175           else {
176 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
177             I = CurrentAnalyses.erase(I);   // Analysis not preserved!
178 #else
179             // GCC 2.95.3 STL doesn't have correct erase member!
180             CurrentAnalyses.erase(I);
181             I = CurrentAnalyses.begin();
182 #endif
183           }
184       }
185
186       // Add all analyses in the provided set...
187       for (std::vector<AnalysisID>::const_iterator
188              I = AnUsage.getProvidedSet().begin(),
189              E = AnUsage.getProvidedSet().end(); I != E; ++I)
190         CurrentAnalyses[*I] = P;
191
192       // Free memory for any passes that we are the last use of...
193       std::vector<Pass*> &DeadPass = LastUserOf[P];
194       for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
195            I != E; ++I) {
196         PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
197                                       (Annotable*)M);
198         (*I)->releaseMemory();
199       }
200     }
201     return MadeChanges;
202   }
203
204   // dumpPassStructure - Implement the -debug-passes=PassStructure option
205   virtual void dumpPassStructure(unsigned Offset = 0) {
206     std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
207               << " Pass Manager\n";
208     for (typename std::vector<PassClass*>::iterator
209            I = Passes.begin(), E = Passes.end(); I != E; ++I) {
210       PassClass *P = *I;
211       P->dumpPassStructure(Offset+1);
212
213       // Loop through and see which classes are destroyed after this one...
214       for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
215                                             E = LastUseOf.end(); I != E; ++I) {
216         if (P == I->second) {
217           std::cerr << "Fr" << std::string(Offset*2, ' ');
218           I->first->dumpPassStructure(0);
219         }
220       }
221     }
222   }
223
224   Pass *getAnalysisOrNullDown(AnalysisID ID) const {
225     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
226     if (I == CurrentAnalyses.end()) {
227       if (Batcher)
228         return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
229       return 0;
230     }
231     return I->second;
232   }
233
234   Pass *getAnalysisOrNullUp(AnalysisID ID) const {
235     std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
236     if (I == CurrentAnalyses.end()) {
237       if (Parent)
238         return Parent->getAnalysisOrNullUp(ID);
239       return 0;
240     }
241     return I->second;
242   }
243
244   // {start/end}Pass - Called when a pass is started, it just propogates
245   // information up to the top level PassManagerT object to tell it that a pass
246   // has started or ended.  This is used to gather timing information about
247   // passes.
248   //
249   void startPass(Pass *P) {
250     if (Parent) Parent->startPass(P);
251     else PassStarted(P);
252   }
253   void endPass(Pass *P) {
254     if (Parent) Parent->endPass(P);
255     else PassEnded(P);
256   }
257
258   // markPassUsed - Inform higher level pass managers (and ourselves)
259   // that these analyses are being used by this pass.  This is used to
260   // make sure that analyses are not free'd before we have to use
261   // them...
262   //
263   void markPassUsed(AnalysisID P, Pass *User) {
264     std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.find(P);
265     if (I != CurrentAnalyses.end()) {
266       LastUseOf[I->second] = User;    // Local pass, extend the lifetime
267     } else {
268       // Pass not in current available set, must be a higher level pass
269       // available to us, propogate to parent pass manager...  We tell the
270       // parent that we (the passmanager) are using the analysis so that it
271       // frees the analysis AFTER this pass manager runs.
272       //
273       assert(Parent != 0 && "Pass available but not found! "
274              "Did your analysis pass 'Provide' itself?");
275       Parent->markPassUsed(P, this);
276     }
277   }
278
279   // Return the number of parent PassManagers that exist
280   virtual unsigned getDepth() const {
281     if (Parent == 0) return 0;
282     return 1 + Parent->getDepth();
283   }
284
285   // add - Add a pass to the queue of passes to run.  This passes ownership of
286   // the Pass to the PassManager.  When the PassManager is destroyed, the pass
287   // will be destroyed as well, so there is no need to delete the pass.  This
288   // implies that all passes MUST be new'd.
289   //
290   void add(PassClass *P) {
291     // Get information about what analyses the pass uses...
292     AnalysisUsage AnUsage;
293     P->getAnalysisUsage(AnUsage);
294     const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
295
296     // Loop over all of the analyses used by this pass,
297     for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
298            E = Required.end(); I != E; ++I) {
299       if (getAnalysisOrNullDown(*I) == 0)
300         add((PassClass*)(*I)->createPass());
301     }
302
303     // Tell the pass to add itself to this PassManager... the way it does so
304     // depends on the class of the pass, and is critical to laying out passes in
305     // an optimal order..
306     //
307     P->addToPassManager(this, AnUsage);
308   }
309
310 private:
311
312   // addPass - These functions are used to implement the subclass specific
313   // behaviors present in PassManager.  Basically the add(Pass*) method ends up
314   // reflecting its behavior into a Pass::addToPassManager call.  Subclasses of
315   // Pass override it specifically so that they can reflect the type
316   // information inherent in "this" back to the PassManager.
317   //
318   // For generic Pass subclasses (which are interprocedural passes), we simply
319   // add the pass to the end of the pass list and terminate any accumulation of
320   // FunctionPass's that are present.
321   //
322   void addPass(PassClass *P, AnalysisUsage &AnUsage) {
323     const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
324     const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
325
326     // Providers are analysis classes which are forbidden to modify the module
327     // they are operating on, so they are allowed to be reordered to before the
328     // batcher...
329     //
330     if (Batcher && ProvidedSet.empty())
331       closeBatcher();                     // This pass cannot be batched!
332     
333     // Set the Resolver instance variable in the Pass so that it knows where to 
334     // find this object...
335     //
336     setAnalysisResolver(P, this);
337     Passes.push_back(P);
338
339     // Inform higher level pass managers (and ourselves) that these analyses are
340     // being used by this pass.  This is used to make sure that analyses are not
341     // free'd before we have to use them...
342     //
343     for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
344            E = RequiredSet.end(); I != E; ++I)
345       markPassUsed(*I, P);     // Mark *I as used by P
346
347     // Erase all analyses not in the preserved set...
348     if (!AnUsage.preservesAll()) {
349       const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
350       for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
351              E = CurrentAnalyses.end(); I != E; )
352         if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
353             PreservedSet.end())
354           ++I;  // This analysis is preserved, leave it in the available set...
355         else {
356 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
357           I = CurrentAnalyses.erase(I);   // Analysis not preserved!
358 #else
359           CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
360           I = CurrentAnalyses.begin();
361 #endif
362         }
363     }
364
365     // Add all analyses in the provided set...
366     for (std::vector<AnalysisID>::const_iterator I = ProvidedSet.begin(),
367            E = ProvidedSet.end(); I != E; ++I)
368       CurrentAnalyses[*I] = P;
369
370     // For now assume that our results are never used...
371     LastUseOf[P] = P;
372   }
373   
374   // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
375   // together in a BatcherClass object so that all of the analyses are run
376   // together a function at a time.
377   //
378   void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
379     if (Batcher == 0) // If we don't have a batcher yet, make one now.
380       Batcher = new BatcherClass(this);
381     // The Batcher will queue them passes up
382     MP->addToPassManager(Batcher, AnUsage);
383   }
384
385   // closeBatcher - Terminate the batcher that is being worked on.
386   void closeBatcher() {
387     if (Batcher) {
388       Passes.push_back(Batcher);
389       Batcher = 0;
390     }
391   }
392 };
393
394
395
396 //===----------------------------------------------------------------------===//
397 // PassManagerTraits<BasicBlock> Specialization
398 //
399 // This pass manager is used to group together all of the BasicBlockPass's
400 // into a single unit.
401 //
402 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
403   // PassClass - The type of passes tracked by this PassManager
404   typedef BasicBlockPass PassClass;
405
406   // SubPassClass - The types of classes that should be collated together
407   // This is impossible to match, so BasicBlock instantiations of PassManagerT
408   // do not collate.
409   //
410   typedef PassManagerT<Module> SubPassClass;
411
412   // BatcherClass - The type to use for collation of subtypes... This class is
413   // never instantiated for the PassManager<BasicBlock>, but it must be an 
414   // instance of PassClass to typecheck.
415   //
416   typedef PassClass BatcherClass;
417
418   // ParentClass - The type of the parent PassManager...
419   typedef PassManagerT<Function> ParentClass;
420
421   // PMType - The type of the passmanager that subclasses this class
422   typedef PassManagerT<BasicBlock> PMType;
423
424   // runPass - Specify how the pass should be run on the UnitType
425   static bool runPass(PassClass *P, BasicBlock *M) {
426     // todo, init and finalize
427     return P->runOnBasicBlock(*M);
428   }
429
430   // Dummy implementation of PassStarted/PassEnded
431   static void PassStarted(Pass *P) {}
432   static void PassEnded(Pass *P) {}
433
434   // getPMName() - Return the name of the unit the PassManager operates on for
435   // debugging.
436   const char *getPMName() const { return "BasicBlock"; }
437   virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
438
439   // Implement the BasicBlockPass interface...
440   virtual bool doInitialization(Module &M);
441   virtual bool runOnBasicBlock(BasicBlock &BB);
442   virtual bool doFinalization(Module &M);
443
444   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
445     AU.setPreservesAll();
446   }
447 };
448
449
450
451 //===----------------------------------------------------------------------===//
452 // PassManagerTraits<Function> Specialization
453 //
454 // This pass manager is used to group together all of the FunctionPass's
455 // into a single unit.
456 //
457 template<> struct PassManagerTraits<Function> : public FunctionPass {
458   // PassClass - The type of passes tracked by this PassManager
459   typedef FunctionPass PassClass;
460
461   // SubPassClass - The types of classes that should be collated together
462   typedef BasicBlockPass SubPassClass;
463
464   // BatcherClass - The type to use for collation of subtypes...
465   typedef PassManagerT<BasicBlock> BatcherClass;
466
467   // ParentClass - The type of the parent PassManager...
468   typedef PassManagerT<Module> ParentClass;
469
470   // PMType - The type of the passmanager that subclasses this class
471   typedef PassManagerT<Function> PMType;
472
473   // runPass - Specify how the pass should be run on the UnitType
474   static bool runPass(PassClass *P, Function *F) {
475     return P->runOnFunction(*F);
476   }
477
478   // Dummy implementation of PassStarted/PassEnded
479   static void PassStarted(Pass *P) {}
480   static void PassEnded(Pass *P) {}
481
482   // getPMName() - Return the name of the unit the PassManager operates on for
483   // debugging.
484   const char *getPMName() const { return "Function"; }
485   virtual const char *getPassName() const { return "Function Pass Manager"; }
486
487   // Implement the FunctionPass interface...
488   virtual bool doInitialization(Module &M);
489   virtual bool runOnFunction(Function &F);
490   virtual bool doFinalization(Module &M);
491
492   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
493     AU.setPreservesAll();
494   }
495 };
496
497
498
499 //===----------------------------------------------------------------------===//
500 // PassManagerTraits<Module> Specialization
501 //
502 // This is the top level PassManager implementation that holds generic passes.
503 //
504 template<> struct PassManagerTraits<Module> : public Pass {
505   // PassClass - The type of passes tracked by this PassManager
506   typedef Pass PassClass;
507
508   // SubPassClass - The types of classes that should be collated together
509   typedef FunctionPass SubPassClass;
510
511   // BatcherClass - The type to use for collation of subtypes...
512   typedef PassManagerT<Function> BatcherClass;
513
514   // ParentClass - The type of the parent PassManager...
515   typedef AnalysisResolver ParentClass;
516
517   // runPass - Specify how the pass should be run on the UnitType
518   static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
519
520   // getPMName() - Return the name of the unit the PassManager operates on for
521   // debugging.
522   const char *getPMName() const { return "Module"; }
523   virtual const char *getPassName() const { return "Module Pass Manager"; }
524
525   // TimingInformation - This data member maintains timing information for each
526   // of the passes that is executed.
527   //
528   TimingInfo *TimeInfo;
529
530   // PassStarted/Ended - This callback is notified any time a pass is started
531   // or stops.  This is used to collect timing information about the different
532   // passes being executed.
533   //
534   void PassStarted(Pass *P) {
535     if (TimeInfo) TimeInfo->passStarted(P);
536   }
537   void PassEnded(Pass *P) {
538     if (TimeInfo) TimeInfo->passEnded(P);
539   }
540
541   // run - Implement the PassManager interface...
542   bool run(Module &M) {
543     TimeInfo = TimingInfo::create();
544     bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
545     if (TimeInfo) {
546       delete TimeInfo;
547       TimeInfo = 0;
548     }
549     return Result;
550   }
551
552   // PassManagerTraits constructor - Create a timing info object if the user
553   // specified timing info should be collected on the command line.
554   //
555   PassManagerTraits() : TimeInfo(0) {}
556 };
557
558
559
560 //===----------------------------------------------------------------------===//
561 // PassManagerTraits Method Implementations
562 //
563
564 // PassManagerTraits<BasicBlock> Implementations
565 //
566 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
567   bool Changed = false;
568   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
569     ((PMType*)this)->Passes[i]->doInitialization(M);
570   return Changed;
571 }
572
573 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
574   return ((PMType*)this)->runOnUnit(&BB);
575 }
576
577 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
578   bool Changed = false;
579   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
580     ((PMType*)this)->Passes[i]->doFinalization(M);
581   return Changed;
582 }
583
584
585 // PassManagerTraits<Function> Implementations
586 //
587 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
588   bool Changed = false;
589   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
590     ((PMType*)this)->Passes[i]->doInitialization(M);
591   return Changed;
592 }
593
594 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
595   return ((PMType*)this)->runOnUnit(&F);
596 }
597
598 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
599   bool Changed = false;
600   for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
601     ((PMType*)this)->Passes[i]->doFinalization(M);
602   return Changed;
603 }
604
605 #endif