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"
24 //===----------------------------------------------------------------------===//
25 // Pass debugging information. Often it is useful to find out what pass is
26 // running when a crash occurs in a utility. When this library is compiled with
27 // debugging on, a command line option (--debug-pass) is enabled that causes the
28 // pass name to be printed before it executes.
31 // Different debug levels that can be enabled...
33 None, Arguments, Structure, Executions, Details
36 static cl::opt<enum PassDebugLevel>
37 PassDebugging("debug-pass", cl::Hidden,
38 cl::desc("Print PassManager debugging information"),
40 clEnumVal(None , "disable debug output"),
41 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
42 clEnumVal(Structure , "print pass structure before run()"),
43 clEnumVal(Executions, "print pass name before it is executed"),
44 clEnumVal(Details , "print pass details when it is executed"),
47 //===----------------------------------------------------------------------===//
48 // PMDebug class - a set of debugging functions, that are not to be
49 // instantiated by the template.
52 static void PerformPassStartupStuff(Pass *P) {
53 // If debugging is enabled, print out argument information...
54 if (PassDebugging >= Arguments) {
55 std::cerr << "Pass Arguments: ";
56 PrintArgumentInformation(P);
59 // Print the pass execution structure
60 if (PassDebugging >= Structure)
61 P->dumpPassStructure();
65 static void PrintArgumentInformation(const Pass *P);
66 static void PrintPassInformation(unsigned,const char*,Pass *, Annotable *);
67 static void PrintAnalysisSetInfo(unsigned,const char*,Pass *P,
68 const std::vector<AnalysisID> &);
72 //===----------------------------------------------------------------------===//
73 // TimingInfo Class - This class is used to calculate information about the
74 // amount of time each pass takes to execute. This only happens when
75 // -time-passes is enabled on the command line.
77 struct TimeRecord { // TimeRecord - Data we collect and print for each pass
78 double Elapsed; // Wall clock time elapsed in seconds
79 double UserTime; // User time elapsed
80 double SystemTime; // System time elapsed
81 unsigned long MaxRSS; // Maximum resident set size (in bytes)
82 unsigned long RSSTemp; // Temp for calculating maxrss
84 TimeRecord() : Elapsed(0), UserTime(0), SystemTime(0), MaxRSS(0) {}
85 void passStart(const TimeRecord &T);
86 void passEnd(const TimeRecord &T);
87 void sum(const TimeRecord &TR);
88 bool operator<(const TimeRecord &TR) const;
90 void print(const char *PassName, const TimeRecord &TotalTime) const;
94 std::map<Pass*, TimeRecord> TimingData;
95 TimingInfo() {} // Private ctor, must use create member
97 // Create method. If Timing is enabled, this creates and returns a new timing
98 // object, otherwise it returns null.
100 static TimingInfo *create();
102 // TimingDtor - Print out information about timing information
105 void passStarted(Pass *P);
106 void passEnded(Pass *P);
109 //===----------------------------------------------------------------------===//
110 // Declare the PassManagerTraits which will be specialized...
112 template<class UnitType> class PassManagerTraits; // Do not define.
115 //===----------------------------------------------------------------------===//
116 // PassManagerT - Container object for passes. The PassManagerT destructor
117 // deletes all passes contained inside of the PassManagerT, so you shouldn't
118 // delete passes manually, and all passes should be dynamically allocated.
120 template<typename UnitType>
121 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
122 typedef PassManagerTraits<UnitType> Traits;
123 typedef typename Traits::PassClass PassClass;
124 typedef typename Traits::SubPassClass SubPassClass;
125 typedef typename Traits::BatcherClass BatcherClass;
126 typedef typename Traits::ParentClass ParentClass;
128 friend typename Traits::PassClass;
129 friend typename Traits::SubPassClass;
132 std::vector<PassClass*> Passes; // List of passes to run
134 // The parent of this pass manager...
135 ParentClass * const Parent;
137 // The current batcher if one is in use, or null
138 BatcherClass *Batcher;
140 // CurrentAnalyses - As the passes are being run, this map contains the
141 // analyses that are available to the current pass for use. This is accessed
142 // through the getAnalysis() function in this class and in Pass.
144 std::map<AnalysisID, Pass*> CurrentAnalyses;
146 // LastUseOf - This map keeps track of the last usage in our pipeline of a
147 // particular pass. When executing passes, the memory for .first is free'd
148 // after .second is run.
150 std::map<Pass*, Pass*> LastUseOf;
153 PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
155 // Delete all of the contained passes...
156 for (typename std::vector<PassClass*>::iterator
157 I = Passes.begin(), E = Passes.end(); I != E; ++I)
161 // run - Run all of the queued passes on the specified module in an optimal
163 virtual bool runOnUnit(UnitType *M) {
164 bool MadeChanges = false;
166 CurrentAnalyses.clear();
168 // LastUserOf - This contains the inverted LastUseOfMap...
169 std::map<Pass *, std::vector<Pass*> > LastUserOf;
170 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
171 E = LastUseOf.end(); I != E; ++I)
172 LastUserOf[I->second].push_back(I->first);
175 // Output debug information...
176 if (Parent == 0) PMDebug::PerformPassStartupStuff(this);
178 // Run all of the passes
179 for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
180 PassClass *P = Passes[i];
182 PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
185 // Get information about what analyses the pass uses...
186 AnalysisUsage AnUsage;
187 P->getAnalysisUsage(AnUsage);
188 PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
189 AnUsage.getRequiredSet());
191 // All Required analyses should be available to the pass as it runs! Here
192 // we fill in the AnalysisImpls member of the pass so that it can
193 // successfully use the getAnalysis() method to retrieve the
194 // implementations it needs.
196 P->AnalysisImpls.clear();
197 P->AnalysisImpls.reserve(AnUsage.getRequiredSet().size());
198 for (std::vector<const PassInfo *>::const_iterator
199 I = AnUsage.getRequiredSet().begin(),
200 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
201 Pass *Impl = getAnalysisOrNullUp(*I);
203 std::cerr << "Analysis '" << (*I)->getPassName()
204 << "' used but not available!";
205 assert(0 && "Analysis used but not available!");
206 } else if (PassDebugging == Details) {
207 if ((*I)->getPassName() != std::string(Impl->getPassName()))
208 std::cerr << " Interface '" << (*I)->getPassName()
209 << "' implemented by '" << Impl->getPassName() << "'\n";
211 P->AnalysisImpls.push_back(std::make_pair(*I, Impl));
216 bool Changed = runPass(P, M);
218 MadeChanges |= Changed;
221 PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
223 PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
224 AnUsage.getPreservedSet());
227 // Erase all analyses not in the preserved set...
228 if (!AnUsage.preservesAll()) {
229 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
230 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
231 E = CurrentAnalyses.end(); I != E; )
232 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
234 ++I; // This analysis is preserved, leave it in the available set...
236 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
237 I = CurrentAnalyses.erase(I); // Analysis not preserved!
239 // GCC 2.95.3 STL doesn't have correct erase member!
240 CurrentAnalyses.erase(I);
241 I = CurrentAnalyses.begin();
246 // Add the current pass to the set of passes that have been run, and are
247 // thus available to users.
249 if (const PassInfo *PI = P->getPassInfo()) {
250 CurrentAnalyses[PI] = P;
252 // This pass is the current implementation of all of the interfaces it
253 // implements as well.
255 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
256 for (unsigned i = 0, e = II.size(); i != e; ++i)
257 CurrentAnalyses[II[i]] = P;
260 // Free memory for any passes that we are the last use of...
261 std::vector<Pass*> &DeadPass = LastUserOf[P];
262 for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
264 PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
266 (*I)->releaseMemory();
272 // dumpPassStructure - Implement the -debug-passes=PassStructure option
273 virtual void dumpPassStructure(unsigned Offset = 0) {
274 std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
275 << " Pass Manager\n";
276 for (typename std::vector<PassClass*>::iterator
277 I = Passes.begin(), E = Passes.end(); I != E; ++I) {
279 P->dumpPassStructure(Offset+1);
281 // Loop through and see which classes are destroyed after this one...
282 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
283 E = LastUseOf.end(); I != E; ++I) {
284 if (P == I->second) {
285 std::cerr << "--" << std::string(Offset*2, ' ');
286 I->first->dumpPassStructure(0);
292 Pass *getAnalysisOrNullDown(const PassInfo *ID) const {
293 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
295 if (I != CurrentAnalyses.end())
296 return I->second; // Found it.
299 return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
303 Pass *getAnalysisOrNullUp(const PassInfo *ID) const {
304 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
305 if (I != CurrentAnalyses.end())
306 return I->second; // Found it.
308 if (Parent) // Try scanning...
309 return Parent->getAnalysisOrNullUp(ID);
313 // {start/end}Pass - Called when a pass is started, it just propogates
314 // information up to the top level PassManagerT object to tell it that a pass
315 // has started or ended. This is used to gather timing information about
318 void startPass(Pass *P) {
319 if (Parent) Parent->startPass(P);
322 void endPass(Pass *P) {
323 if (Parent) Parent->endPass(P);
327 // markPassUsed - Inform higher level pass managers (and ourselves)
328 // that these analyses are being used by this pass. This is used to
329 // make sure that analyses are not free'd before we have to use
332 void markPassUsed(const PassInfo *P, Pass *User) {
333 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(P);
335 if (I != CurrentAnalyses.end()) {
336 LastUseOf[I->second] = User; // Local pass, extend the lifetime
338 // Pass not in current available set, must be a higher level pass
339 // available to us, propogate to parent pass manager... We tell the
340 // parent that we (the passmanager) are using the analysis so that it
341 // frees the analysis AFTER this pass manager runs.
343 assert(Parent != 0 && "Pass available but not found!");
344 Parent->markPassUsed(P, this);
348 // Return the number of parent PassManagers that exist
349 virtual unsigned getDepth() const {
350 if (Parent == 0) return 0;
351 return 1 + Parent->getDepth();
354 virtual unsigned getNumContainedPasses() const { return Passes.size(); }
355 virtual const Pass *getContainedPass(unsigned N) const {
356 assert(N < Passes.size() && "Pass number out of range!");
360 // add - Add a pass to the queue of passes to run. This gives ownership of
361 // the Pass to the PassManager. When the PassManager is destroyed, the pass
362 // will be destroyed as well, so there is no need to delete the pass. This
363 // implies that all passes MUST be new'd.
365 void add(PassClass *P) {
366 // Get information about what analyses the pass uses...
367 AnalysisUsage AnUsage;
368 P->getAnalysisUsage(AnUsage);
369 const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
371 // Loop over all of the analyses used by this pass,
372 for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
373 E = Required.end(); I != E; ++I) {
374 if (getAnalysisOrNullDown(*I) == 0)
375 add((PassClass*)(*I)->createPass());
378 // Tell the pass to add itself to this PassManager... the way it does so
379 // depends on the class of the pass, and is critical to laying out passes in
380 // an optimal order..
382 P->addToPassManager(this, AnUsage);
387 // addPass - These functions are used to implement the subclass specific
388 // behaviors present in PassManager. Basically the add(Pass*) method ends up
389 // reflecting its behavior into a Pass::addToPassManager call. Subclasses of
390 // Pass override it specifically so that they can reflect the type
391 // information inherent in "this" back to the PassManager.
393 // For generic Pass subclasses (which are interprocedural passes), we simply
394 // add the pass to the end of the pass list and terminate any accumulation of
395 // FunctionPass's that are present.
397 void addPass(PassClass *P, AnalysisUsage &AnUsage) {
398 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
400 // FIXME: If this pass being added isn't killed by any of the passes in the
401 // batcher class then we can reorder to pass to execute before the batcher
402 // does, which will potentially allow us to batch more passes!
404 //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
405 if (Batcher /*&& ProvidedSet.empty()*/)
406 closeBatcher(); // This pass cannot be batched!
408 // Set the Resolver instance variable in the Pass so that it knows where to
409 // find this object...
411 setAnalysisResolver(P, this);
414 // Inform higher level pass managers (and ourselves) that these analyses are
415 // being used by this pass. This is used to make sure that analyses are not
416 // free'd before we have to use them...
418 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
419 E = RequiredSet.end(); I != E; ++I)
420 markPassUsed(*I, P); // Mark *I as used by P
422 // Erase all analyses not in the preserved set...
423 if (!AnUsage.preservesAll()) {
424 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
425 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
426 E = CurrentAnalyses.end(); I != E; )
427 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
429 ++I; // This analysis is preserved, leave it in the available set...
431 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
432 I = CurrentAnalyses.erase(I); // Analysis not preserved!
434 CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
435 I = CurrentAnalyses.begin();
440 // Add this pass to the currently available set...
441 if (const PassInfo *PI = P->getPassInfo()) {
442 CurrentAnalyses[PI] = P;
444 // This pass is the current implementation of all of the interfaces it
445 // implements as well.
447 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
448 for (unsigned i = 0, e = II.size(); i != e; ++i)
449 CurrentAnalyses[II[i]] = P;
452 // For now assume that our results are never used...
456 // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
457 // together in a BatcherClass object so that all of the analyses are run
458 // together a function at a time.
460 void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
461 if (Batcher == 0) // If we don't have a batcher yet, make one now.
462 Batcher = new BatcherClass(this);
463 // The Batcher will queue the passes up
464 MP->addToPassManager(Batcher, AnUsage);
467 // closeBatcher - Terminate the batcher that is being worked on.
468 void closeBatcher() {
470 Passes.push_back(Batcher);
478 //===----------------------------------------------------------------------===//
479 // PassManagerTraits<BasicBlock> Specialization
481 // This pass manager is used to group together all of the BasicBlockPass's
482 // into a single unit.
484 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
485 // PassClass - The type of passes tracked by this PassManager
486 typedef BasicBlockPass PassClass;
488 // SubPassClass - The types of classes that should be collated together
489 // This is impossible to match, so BasicBlock instantiations of PassManagerT
492 typedef PassManagerT<Module> SubPassClass;
494 // BatcherClass - The type to use for collation of subtypes... This class is
495 // never instantiated for the PassManager<BasicBlock>, but it must be an
496 // instance of PassClass to typecheck.
498 typedef PassClass BatcherClass;
500 // ParentClass - The type of the parent PassManager...
501 typedef PassManagerT<Function> ParentClass;
503 // PMType - The type of the passmanager that subclasses this class
504 typedef PassManagerT<BasicBlock> PMType;
506 // runPass - Specify how the pass should be run on the UnitType
507 static bool runPass(PassClass *P, BasicBlock *M) {
508 // todo, init and finalize
509 return P->runOnBasicBlock(*M);
512 // Dummy implementation of PassStarted/PassEnded
513 static void PassStarted(Pass *P) {}
514 static void PassEnded(Pass *P) {}
516 // getPMName() - Return the name of the unit the PassManager operates on for
518 const char *getPMName() const { return "BasicBlock"; }
519 virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
521 // Implement the BasicBlockPass interface...
522 virtual bool doInitialization(Module &M);
523 virtual bool runOnBasicBlock(BasicBlock &BB);
524 virtual bool doFinalization(Module &M);
526 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
527 AU.setPreservesAll();
533 //===----------------------------------------------------------------------===//
534 // PassManagerTraits<Function> Specialization
536 // This pass manager is used to group together all of the FunctionPass's
537 // into a single unit.
539 template<> struct PassManagerTraits<Function> : public FunctionPass {
540 // PassClass - The type of passes tracked by this PassManager
541 typedef FunctionPass PassClass;
543 // SubPassClass - The types of classes that should be collated together
544 typedef BasicBlockPass SubPassClass;
546 // BatcherClass - The type to use for collation of subtypes...
547 typedef PassManagerT<BasicBlock> BatcherClass;
549 // ParentClass - The type of the parent PassManager...
550 typedef PassManagerT<Module> ParentClass;
552 // PMType - The type of the passmanager that subclasses this class
553 typedef PassManagerT<Function> PMType;
555 // runPass - Specify how the pass should be run on the UnitType
556 static bool runPass(PassClass *P, Function *F) {
557 return P->runOnFunction(*F);
560 // Dummy implementation of PassStarted/PassEnded
561 static void PassStarted(Pass *P) {}
562 static void PassEnded(Pass *P) {}
564 // getPMName() - Return the name of the unit the PassManager operates on for
566 const char *getPMName() const { return "Function"; }
567 virtual const char *getPassName() const { return "Function Pass Manager"; }
569 // Implement the FunctionPass interface...
570 virtual bool doInitialization(Module &M);
571 virtual bool runOnFunction(Function &F);
572 virtual bool doFinalization(Module &M);
574 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
575 AU.setPreservesAll();
581 //===----------------------------------------------------------------------===//
582 // PassManagerTraits<Module> Specialization
584 // This is the top level PassManager implementation that holds generic passes.
586 template<> struct PassManagerTraits<Module> : public Pass {
587 // PassClass - The type of passes tracked by this PassManager
588 typedef Pass PassClass;
590 // SubPassClass - The types of classes that should be collated together
591 typedef FunctionPass SubPassClass;
593 // BatcherClass - The type to use for collation of subtypes...
594 typedef PassManagerT<Function> BatcherClass;
596 // ParentClass - The type of the parent PassManager...
597 typedef AnalysisResolver ParentClass;
599 // runPass - Specify how the pass should be run on the UnitType
600 static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
602 // getPMName() - Return the name of the unit the PassManager operates on for
604 const char *getPMName() const { return "Module"; }
605 virtual const char *getPassName() const { return "Module Pass Manager"; }
607 // TimingInformation - This data member maintains timing information for each
608 // of the passes that is executed.
610 TimingInfo *TimeInfo;
612 // PassStarted/Ended - This callback is notified any time a pass is started
613 // or stops. This is used to collect timing information about the different
614 // passes being executed.
616 void PassStarted(Pass *P) {
617 if (TimeInfo) TimeInfo->passStarted(P);
619 void PassEnded(Pass *P) {
620 if (TimeInfo) TimeInfo->passEnded(P);
623 // run - Implement the PassManager interface...
624 bool run(Module &M) {
625 TimeInfo = TimingInfo::create();
626 bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
634 // PassManagerTraits constructor - Create a timing info object if the user
635 // specified timing info should be collected on the command line.
637 PassManagerTraits() : TimeInfo(0) {}
642 //===----------------------------------------------------------------------===//
643 // PassManagerTraits Method Implementations
646 // PassManagerTraits<BasicBlock> Implementations
648 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
649 bool Changed = false;
650 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
651 ((PMType*)this)->Passes[i]->doInitialization(M);
655 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
656 return ((PMType*)this)->runOnUnit(&BB);
659 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
660 bool Changed = false;
661 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
662 ((PMType*)this)->Passes[i]->doFinalization(M);
667 // PassManagerTraits<Function> Implementations
669 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
670 bool Changed = false;
671 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
672 ((PMType*)this)->Passes[i]->doInitialization(M);
676 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
677 return ((PMType*)this)->runOnUnit(&F);
680 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
681 bool Changed = false;
682 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
683 ((PMType*)this)->Passes[i]->doFinalization(M);