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