1 //===- PassManagerT.h - Container for Passes ---------------------*- C++ -*--=//
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.
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.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_PASSMANAGER_T_H
16 #define LLVM_PASSMANAGER_T_H
18 #include "llvm/Pass.h"
19 #include "Support/CommandLine.h"
20 #include "Support/LeakDetector.h"
25 //===----------------------------------------------------------------------===//
26 // Pass debugging information. Often it is useful to find out what pass is
27 // running when a crash occurs in a utility. When this library is compiled with
28 // debugging on, a command line option (--debug-pass) is enabled that causes the
29 // pass name to be printed before it executes.
32 // Different debug levels that can be enabled...
34 None, Arguments, Structure, Executions, Details
37 static cl::opt<enum PassDebugLevel>
38 PassDebugging("debug-pass", cl::Hidden,
39 cl::desc("Print PassManager debugging information"),
41 clEnumVal(None , "disable debug output"),
42 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
43 clEnumVal(Structure , "print pass structure before run()"),
44 clEnumVal(Executions, "print pass name before it is executed"),
45 clEnumVal(Details , "print pass details when it is executed"),
48 //===----------------------------------------------------------------------===//
49 // PMDebug class - a set of debugging functions, that are not to be
50 // instantiated by the template.
53 static void PerformPassStartupStuff(Pass *P) {
54 // If debugging is enabled, print out argument information...
55 if (PassDebugging >= Arguments) {
56 std::cerr << "Pass Arguments: ";
57 PrintArgumentInformation(P);
60 // Print the pass execution structure
61 if (PassDebugging >= Structure)
62 P->dumpPassStructure();
66 static void PrintArgumentInformation(const Pass *P);
67 static void PrintPassInformation(unsigned,const char*,Pass *, Annotable *);
68 static void PrintAnalysisSetInfo(unsigned,const char*,Pass *P,
69 const std::vector<AnalysisID> &);
73 //===----------------------------------------------------------------------===//
74 // TimingInfo Class - This class is used to calculate information about the
75 // amount of time each pass takes to execute. This only happens when
76 // -time-passes is enabled on the command line.
78 struct TimeRecord { // TimeRecord - Data we collect and print for each pass
79 double Elapsed; // Wall clock time elapsed in seconds
80 double UserTime; // User time elapsed
81 double SystemTime; // System time elapsed
82 unsigned long MaxRSS; // Maximum resident set size (in bytes)
83 unsigned long RSSTemp; // Temp for calculating maxrss
85 TimeRecord() : Elapsed(0), UserTime(0), SystemTime(0), MaxRSS(0) {}
86 void passStart(const TimeRecord &T);
87 void passEnd(const TimeRecord &T);
88 void sum(const TimeRecord &TR);
89 bool operator<(const TimeRecord &TR) const;
91 void print(const char *PassName, const TimeRecord &TotalTime) const;
95 std::map<Pass*, TimeRecord> TimingData;
96 TimingInfo() {} // Private ctor, must use create member
98 // Create method. If Timing is enabled, this creates and returns a new timing
99 // object, otherwise it returns null.
101 static TimingInfo *create();
103 // TimingDtor - Print out information about timing information
106 void passStarted(Pass *P);
107 void passEnded(Pass *P);
110 //===----------------------------------------------------------------------===//
111 // Declare the PassManagerTraits which will be specialized...
113 template<class UnitType> class PassManagerTraits; // Do not define.
116 //===----------------------------------------------------------------------===//
117 // PassManagerT - Container object for passes. The PassManagerT destructor
118 // deletes all passes contained inside of the PassManagerT, so you shouldn't
119 // delete passes manually, and all passes should be dynamically allocated.
121 template<typename UnitType>
122 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
123 typedef PassManagerTraits<UnitType> Traits;
124 typedef typename Traits::PassClass PassClass;
125 typedef typename Traits::SubPassClass SubPassClass;
126 typedef typename Traits::BatcherClass BatcherClass;
127 typedef typename Traits::ParentClass ParentClass;
129 friend typename Traits::PassClass;
130 friend typename Traits::SubPassClass;
133 std::vector<PassClass*> Passes; // List of passes to run
135 // The parent of this pass manager...
136 ParentClass * const Parent;
138 // The current batcher if one is in use, or null
139 BatcherClass *Batcher;
141 // CurrentAnalyses - As the passes are being run, this map contains the
142 // analyses that are available to the current pass for use. This is accessed
143 // through the getAnalysis() function in this class and in Pass.
145 std::map<AnalysisID, Pass*> CurrentAnalyses;
147 // LastUseOf - This map keeps track of the last usage in our pipeline of a
148 // particular pass. When executing passes, the memory for .first is free'd
149 // after .second is run.
151 std::map<Pass*, Pass*> LastUseOf;
154 PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
156 // Delete all of the contained passes...
157 for (typename std::vector<PassClass*>::iterator
158 I = Passes.begin(), E = Passes.end(); I != E; ++I)
162 // run - Run all of the queued passes on the specified module in an optimal
164 virtual bool runOnUnit(UnitType *M) {
165 bool MadeChanges = false;
167 CurrentAnalyses.clear();
169 // LastUserOf - This contains the inverted LastUseOfMap...
170 std::map<Pass *, std::vector<Pass*> > LastUserOf;
171 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
172 E = LastUseOf.end(); I != E; ++I)
173 LastUserOf[I->second].push_back(I->first);
176 // Output debug information...
177 if (Parent == 0) PMDebug::PerformPassStartupStuff(this);
179 // Run all of the passes
180 for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
181 PassClass *P = Passes[i];
183 PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
186 // Get information about what analyses the pass uses...
187 AnalysisUsage AnUsage;
188 P->getAnalysisUsage(AnUsage);
189 PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
190 AnUsage.getRequiredSet());
192 // All Required analyses should be available to the pass as it runs! Here
193 // we fill in the AnalysisImpls member of the pass so that it can
194 // successfully use the getAnalysis() method to retrieve the
195 // implementations it needs.
197 P->AnalysisImpls.clear();
198 P->AnalysisImpls.reserve(AnUsage.getRequiredSet().size());
199 for (std::vector<const PassInfo *>::const_iterator
200 I = AnUsage.getRequiredSet().begin(),
201 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
202 Pass *Impl = getAnalysisOrNullUp(*I);
204 std::cerr << "Analysis '" << (*I)->getPassName()
205 << "' used but not available!";
206 assert(0 && "Analysis used but not available!");
207 } else if (PassDebugging == Details) {
208 if ((*I)->getPassName() != std::string(Impl->getPassName()))
209 std::cerr << " Interface '" << (*I)->getPassName()
210 << "' implemented by '" << Impl->getPassName() << "'\n";
212 P->AnalysisImpls.push_back(std::make_pair(*I, Impl));
217 bool Changed = runPass(P, M);
219 MadeChanges |= Changed;
221 // Check for memory leaks by the pass...
222 LeakDetector::checkForGarbage(std::string("after running pass '") +
223 P->getPassName() + "'");
226 PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
228 PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
229 AnUsage.getPreservedSet());
232 // Erase all analyses not in the preserved set...
233 if (!AnUsage.preservesAll()) {
234 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
235 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
236 E = CurrentAnalyses.end(); I != E; )
237 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
239 ++I; // This analysis is preserved, leave it in the available set...
241 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
242 I = CurrentAnalyses.erase(I); // Analysis not preserved!
244 // GCC 2.95.3 STL doesn't have correct erase member!
245 CurrentAnalyses.erase(I);
246 I = CurrentAnalyses.begin();
251 // Add the current pass to the set of passes that have been run, and are
252 // thus available to users.
254 if (const PassInfo *PI = P->getPassInfo()) {
255 CurrentAnalyses[PI] = P;
257 // This pass is the current implementation of all of the interfaces it
258 // implements as well.
260 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
261 for (unsigned i = 0, e = II.size(); i != e; ++i)
262 CurrentAnalyses[II[i]] = P;
265 // Free memory for any passes that we are the last use of...
266 std::vector<Pass*> &DeadPass = LastUserOf[P];
267 for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
269 PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
271 (*I)->releaseMemory();
277 // dumpPassStructure - Implement the -debug-passes=PassStructure option
278 virtual void dumpPassStructure(unsigned Offset = 0) {
279 std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
280 << " Pass Manager\n";
281 for (typename std::vector<PassClass*>::iterator
282 I = Passes.begin(), E = Passes.end(); I != E; ++I) {
284 P->dumpPassStructure(Offset+1);
286 // Loop through and see which classes are destroyed after this one...
287 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
288 E = LastUseOf.end(); I != E; ++I) {
289 if (P == I->second) {
290 std::cerr << "--" << std::string(Offset*2, ' ');
291 I->first->dumpPassStructure(0);
297 Pass *getAnalysisOrNullDown(const PassInfo *ID) const {
298 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
300 if (I != CurrentAnalyses.end())
301 return I->second; // Found it.
304 return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
308 Pass *getAnalysisOrNullUp(const PassInfo *ID) const {
309 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
310 if (I != CurrentAnalyses.end())
311 return I->second; // Found it.
313 if (Parent) // Try scanning...
314 return Parent->getAnalysisOrNullUp(ID);
318 // {start/end}Pass - Called when a pass is started, it just propogates
319 // information up to the top level PassManagerT object to tell it that a pass
320 // has started or ended. This is used to gather timing information about
323 void startPass(Pass *P) {
324 if (Parent) Parent->startPass(P);
327 void endPass(Pass *P) {
328 if (Parent) Parent->endPass(P);
332 // markPassUsed - Inform higher level pass managers (and ourselves)
333 // that these analyses are being used by this pass. This is used to
334 // make sure that analyses are not free'd before we have to use
337 void markPassUsed(const PassInfo *P, Pass *User) {
338 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(P);
340 if (I != CurrentAnalyses.end()) {
341 LastUseOf[I->second] = User; // Local pass, extend the lifetime
343 // Pass not in current available set, must be a higher level pass
344 // available to us, propogate to parent pass manager... We tell the
345 // parent that we (the passmanager) are using the analysis so that it
346 // frees the analysis AFTER this pass manager runs.
348 assert(Parent != 0 && "Pass available but not found!");
349 Parent->markPassUsed(P, this);
353 // Return the number of parent PassManagers that exist
354 virtual unsigned getDepth() const {
355 if (Parent == 0) return 0;
356 return 1 + Parent->getDepth();
359 virtual unsigned getNumContainedPasses() const { return Passes.size(); }
360 virtual const Pass *getContainedPass(unsigned N) const {
361 assert(N < Passes.size() && "Pass number out of range!");
365 // add - Add a pass to the queue of passes to run. This gives ownership of
366 // the Pass to the PassManager. When the PassManager is destroyed, the pass
367 // will be destroyed as well, so there is no need to delete the pass. This
368 // implies that all passes MUST be new'd.
370 void add(PassClass *P) {
371 // Get information about what analyses the pass uses...
372 AnalysisUsage AnUsage;
373 P->getAnalysisUsage(AnUsage);
374 const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
376 // Loop over all of the analyses used by this pass,
377 for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
378 E = Required.end(); I != E; ++I) {
379 if (getAnalysisOrNullDown(*I) == 0)
380 add((PassClass*)(*I)->createPass());
383 // Tell the pass to add itself to this PassManager... the way it does so
384 // depends on the class of the pass, and is critical to laying out passes in
385 // an optimal order..
387 P->addToPassManager(this, AnUsage);
392 // addPass - These functions are used to implement the subclass specific
393 // behaviors present in PassManager. Basically the add(Pass*) method ends up
394 // reflecting its behavior into a Pass::addToPassManager call. Subclasses of
395 // Pass override it specifically so that they can reflect the type
396 // information inherent in "this" back to the PassManager.
398 // For generic Pass subclasses (which are interprocedural passes), we simply
399 // add the pass to the end of the pass list and terminate any accumulation of
400 // FunctionPass's that are present.
402 void addPass(PassClass *P, AnalysisUsage &AnUsage) {
403 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
405 // FIXME: If this pass being added isn't killed by any of the passes in the
406 // batcher class then we can reorder to pass to execute before the batcher
407 // does, which will potentially allow us to batch more passes!
409 //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
410 if (Batcher /*&& ProvidedSet.empty()*/)
411 closeBatcher(); // This pass cannot be batched!
413 // Set the Resolver instance variable in the Pass so that it knows where to
414 // find this object...
416 setAnalysisResolver(P, this);
419 // Inform higher level pass managers (and ourselves) that these analyses are
420 // being used by this pass. This is used to make sure that analyses are not
421 // free'd before we have to use them...
423 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
424 E = RequiredSet.end(); I != E; ++I)
425 markPassUsed(*I, P); // Mark *I as used by P
427 // Erase all analyses not in the preserved set...
428 if (!AnUsage.preservesAll()) {
429 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
430 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
431 E = CurrentAnalyses.end(); I != E; )
432 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
434 ++I; // This analysis is preserved, leave it in the available set...
436 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
437 I = CurrentAnalyses.erase(I); // Analysis not preserved!
439 CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
440 I = CurrentAnalyses.begin();
445 // Add this pass to the currently available set...
446 if (const PassInfo *PI = P->getPassInfo()) {
447 CurrentAnalyses[PI] = P;
449 // This pass is the current implementation of all of the interfaces it
450 // implements as well.
452 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
453 for (unsigned i = 0, e = II.size(); i != e; ++i)
454 CurrentAnalyses[II[i]] = P;
457 // For now assume that our results are never used...
461 // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
462 // together in a BatcherClass object so that all of the analyses are run
463 // together a function at a time.
465 void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
466 if (Batcher == 0) // If we don't have a batcher yet, make one now.
467 Batcher = new BatcherClass(this);
468 // The Batcher will queue the passes up
469 MP->addToPassManager(Batcher, AnUsage);
472 // closeBatcher - Terminate the batcher that is being worked on.
473 void closeBatcher() {
475 Passes.push_back(Batcher);
483 //===----------------------------------------------------------------------===//
484 // PassManagerTraits<BasicBlock> Specialization
486 // This pass manager is used to group together all of the BasicBlockPass's
487 // into a single unit.
489 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
490 // PassClass - The type of passes tracked by this PassManager
491 typedef BasicBlockPass PassClass;
493 // SubPassClass - The types of classes that should be collated together
494 // This is impossible to match, so BasicBlock instantiations of PassManagerT
497 typedef PassManagerT<Module> SubPassClass;
499 // BatcherClass - The type to use for collation of subtypes... This class is
500 // never instantiated for the PassManager<BasicBlock>, but it must be an
501 // instance of PassClass to typecheck.
503 typedef PassClass BatcherClass;
505 // ParentClass - The type of the parent PassManager...
506 typedef PassManagerT<Function> ParentClass;
508 // PMType - The type of the passmanager that subclasses this class
509 typedef PassManagerT<BasicBlock> PMType;
511 // runPass - Specify how the pass should be run on the UnitType
512 static bool runPass(PassClass *P, BasicBlock *M) {
513 // todo, init and finalize
514 return P->runOnBasicBlock(*M);
517 // Dummy implementation of PassStarted/PassEnded
518 static void PassStarted(Pass *P) {}
519 static void PassEnded(Pass *P) {}
521 // getPMName() - Return the name of the unit the PassManager operates on for
523 const char *getPMName() const { return "BasicBlock"; }
524 virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
526 // Implement the BasicBlockPass interface...
527 virtual bool doInitialization(Module &M);
528 virtual bool runOnBasicBlock(BasicBlock &BB);
529 virtual bool doFinalization(Module &M);
531 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
532 AU.setPreservesAll();
538 //===----------------------------------------------------------------------===//
539 // PassManagerTraits<Function> Specialization
541 // This pass manager is used to group together all of the FunctionPass's
542 // into a single unit.
544 template<> struct PassManagerTraits<Function> : public FunctionPass {
545 // PassClass - The type of passes tracked by this PassManager
546 typedef FunctionPass PassClass;
548 // SubPassClass - The types of classes that should be collated together
549 typedef BasicBlockPass SubPassClass;
551 // BatcherClass - The type to use for collation of subtypes...
552 typedef PassManagerT<BasicBlock> BatcherClass;
554 // ParentClass - The type of the parent PassManager...
555 typedef PassManagerT<Module> ParentClass;
557 // PMType - The type of the passmanager that subclasses this class
558 typedef PassManagerT<Function> PMType;
560 // runPass - Specify how the pass should be run on the UnitType
561 static bool runPass(PassClass *P, Function *F) {
562 return P->runOnFunction(*F);
565 // Dummy implementation of PassStarted/PassEnded
566 static void PassStarted(Pass *P) {}
567 static void PassEnded(Pass *P) {}
569 // getPMName() - Return the name of the unit the PassManager operates on for
571 const char *getPMName() const { return "Function"; }
572 virtual const char *getPassName() const { return "Function Pass Manager"; }
574 // Implement the FunctionPass interface...
575 virtual bool doInitialization(Module &M);
576 virtual bool runOnFunction(Function &F);
577 virtual bool doFinalization(Module &M);
579 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
580 AU.setPreservesAll();
586 //===----------------------------------------------------------------------===//
587 // PassManagerTraits<Module> Specialization
589 // This is the top level PassManager implementation that holds generic passes.
591 template<> struct PassManagerTraits<Module> : public Pass {
592 // PassClass - The type of passes tracked by this PassManager
593 typedef Pass PassClass;
595 // SubPassClass - The types of classes that should be collated together
596 typedef FunctionPass SubPassClass;
598 // BatcherClass - The type to use for collation of subtypes...
599 typedef PassManagerT<Function> BatcherClass;
601 // ParentClass - The type of the parent PassManager...
602 typedef AnalysisResolver ParentClass;
604 // runPass - Specify how the pass should be run on the UnitType
605 static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
607 // getPMName() - Return the name of the unit the PassManager operates on for
609 const char *getPMName() const { return "Module"; }
610 virtual const char *getPassName() const { return "Module Pass Manager"; }
612 // TimingInformation - This data member maintains timing information for each
613 // of the passes that is executed.
615 TimingInfo *TimeInfo;
617 // PassStarted/Ended - This callback is notified any time a pass is started
618 // or stops. This is used to collect timing information about the different
619 // passes being executed.
621 void PassStarted(Pass *P) {
622 if (TimeInfo) TimeInfo->passStarted(P);
624 void PassEnded(Pass *P) {
625 if (TimeInfo) TimeInfo->passEnded(P);
628 // run - Implement the PassManager interface...
629 bool run(Module &M) {
630 TimeInfo = TimingInfo::create();
631 bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
639 // PassManagerTraits constructor - Create a timing info object if the user
640 // specified timing info should be collected on the command line.
642 PassManagerTraits() : TimeInfo(0) {}
647 //===----------------------------------------------------------------------===//
648 // PassManagerTraits Method Implementations
651 // PassManagerTraits<BasicBlock> Implementations
653 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
654 bool Changed = false;
655 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
656 ((PMType*)this)->Passes[i]->doInitialization(M);
660 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
661 return ((PMType*)this)->runOnUnit(&BB);
664 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
665 bool Changed = false;
666 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
667 ((PMType*)this)->Passes[i]->doFinalization(M);
672 // PassManagerTraits<Function> Implementations
674 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
675 bool Changed = false;
676 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
677 ((PMType*)this)->Passes[i]->doInitialization(M);
681 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
682 return ((PMType*)this)->runOnUnit(&F);
685 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
686 bool Changed = false;
687 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
688 ((PMType*)this)->Passes[i]->doFinalization(M);