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 {
89 return UserTime+SystemTime < TR.UserTime+TR.SystemTime;
92 void print(const char *PassName, const TimeRecord &TotalTime) const;
96 std::map<Pass*, TimeRecord> TimingData;
97 TimingInfo() {} // Private ctor, must use create member
99 // Create method. If Timing is enabled, this creates and returns a new timing
100 // object, otherwise it returns null.
102 static TimingInfo *create();
104 // TimingDtor - Print out information about timing information
107 void passStarted(Pass *P);
108 void passEnded(Pass *P);
113 //===----------------------------------------------------------------------===//
114 // Declare the PassManagerTraits which will be specialized...
116 template<class UnitType> class PassManagerTraits; // Do not define.
119 //===----------------------------------------------------------------------===//
120 // PassManagerT - Container object for passes. The PassManagerT destructor
121 // deletes all passes contained inside of the PassManagerT, so you shouldn't
122 // delete passes manually, and all passes should be dynamically allocated.
124 template<typename UnitType>
125 class PassManagerT : public PassManagerTraits<UnitType>,public AnalysisResolver{
126 typedef PassManagerTraits<UnitType> Traits;
127 typedef typename Traits::PassClass PassClass;
128 typedef typename Traits::SubPassClass SubPassClass;
129 typedef typename Traits::BatcherClass BatcherClass;
130 typedef typename Traits::ParentClass ParentClass;
132 friend typename Traits::PassClass;
133 friend typename Traits::SubPassClass;
136 std::vector<PassClass*> Passes; // List of passes to run
138 // The parent of this pass manager...
139 ParentClass * const Parent;
141 // The current batcher if one is in use, or null
142 BatcherClass *Batcher;
144 // CurrentAnalyses - As the passes are being run, this map contains the
145 // analyses that are available to the current pass for use. This is accessed
146 // through the getAnalysis() function in this class and in Pass.
148 std::map<AnalysisID, Pass*> CurrentAnalyses;
150 // LastUseOf - This map keeps track of the last usage in our pipeline of a
151 // particular pass. When executing passes, the memory for .first is free'd
152 // after .second is run.
154 std::map<Pass*, Pass*> LastUseOf;
157 PassManagerT(ParentClass *Par = 0) : Parent(Par), Batcher(0) {}
159 // Delete all of the contained passes...
160 for (typename std::vector<PassClass*>::iterator
161 I = Passes.begin(), E = Passes.end(); I != E; ++I)
165 // run - Run all of the queued passes on the specified module in an optimal
167 virtual bool runOnUnit(UnitType *M) {
168 bool MadeChanges = false;
170 CurrentAnalyses.clear();
172 // LastUserOf - This contains the inverted LastUseOfMap...
173 std::map<Pass *, std::vector<Pass*> > LastUserOf;
174 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
175 E = LastUseOf.end(); I != E; ++I)
176 LastUserOf[I->second].push_back(I->first);
179 // Output debug information...
180 if (Parent == 0) PMDebug::PerformPassStartupStuff(this);
182 // Run all of the passes
183 for (unsigned i = 0, e = Passes.size(); i < e; ++i) {
184 PassClass *P = Passes[i];
186 PMDebug::PrintPassInformation(getDepth(), "Executing Pass", P,
189 // Get information about what analyses the pass uses...
190 AnalysisUsage AnUsage;
191 P->getAnalysisUsage(AnUsage);
192 PMDebug::PrintAnalysisSetInfo(getDepth(), "Required", P,
193 AnUsage.getRequiredSet());
196 // All Required analyses should be available to the pass as it runs!
197 for (std::vector<AnalysisID>::const_iterator
198 I = AnUsage.getRequiredSet().begin(),
199 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
200 assert(getAnalysisOrNullUp(*I) && "Analysis used but not available!");
206 bool Changed = runPass(P, M);
208 MadeChanges |= Changed;
211 PMDebug::PrintPassInformation(getDepth()+1, "Made Modification", P,
213 PMDebug::PrintAnalysisSetInfo(getDepth(), "Preserved", P,
214 AnUsage.getPreservedSet());
217 // Erase all analyses not in the preserved set...
218 if (!AnUsage.preservesAll()) {
219 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
220 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
221 E = CurrentAnalyses.end(); I != E; )
222 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
224 ++I; // This analysis is preserved, leave it in the available set...
226 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
227 I = CurrentAnalyses.erase(I); // Analysis not preserved!
229 // GCC 2.95.3 STL doesn't have correct erase member!
230 CurrentAnalyses.erase(I);
231 I = CurrentAnalyses.begin();
236 // Add the current pass to the set of passes that have been run, and are
237 // thus available to users.
239 if (const PassInfo *PI = P->getPassInfo())
240 CurrentAnalyses[PI] = P;
242 // Free memory for any passes that we are the last use of...
243 std::vector<Pass*> &DeadPass = LastUserOf[P];
244 for (std::vector<Pass*>::iterator I = DeadPass.begin(),E = DeadPass.end();
246 PMDebug::PrintPassInformation(getDepth()+1, "Freeing Pass", *I,
248 (*I)->releaseMemory();
254 // dumpPassStructure - Implement the -debug-passes=PassStructure option
255 virtual void dumpPassStructure(unsigned Offset = 0) {
256 std::cerr << std::string(Offset*2, ' ') << Traits::getPMName()
257 << " Pass Manager\n";
258 for (typename std::vector<PassClass*>::iterator
259 I = Passes.begin(), E = Passes.end(); I != E; ++I) {
261 P->dumpPassStructure(Offset+1);
263 // Loop through and see which classes are destroyed after this one...
264 for (std::map<Pass*, Pass*>::iterator I = LastUseOf.begin(),
265 E = LastUseOf.end(); I != E; ++I) {
266 if (P == I->second) {
267 std::cerr << "--" << std::string(Offset*2, ' ');
268 I->first->dumpPassStructure(0);
274 Pass *getAnalysisOrNullDown(AnalysisID ID) const {
275 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
276 if (I == CurrentAnalyses.end()) {
278 return ((AnalysisResolver*)Batcher)->getAnalysisOrNullDown(ID);
284 Pass *getAnalysisOrNullUp(AnalysisID ID) const {
285 std::map<AnalysisID, Pass*>::const_iterator I = CurrentAnalyses.find(ID);
286 if (I == CurrentAnalyses.end()) {
288 return Parent->getAnalysisOrNullUp(ID);
294 // {start/end}Pass - Called when a pass is started, it just propogates
295 // information up to the top level PassManagerT object to tell it that a pass
296 // has started or ended. This is used to gather timing information about
299 void startPass(Pass *P) {
300 if (Parent) Parent->startPass(P);
303 void endPass(Pass *P) {
304 if (Parent) Parent->endPass(P);
308 // markPassUsed - Inform higher level pass managers (and ourselves)
309 // that these analyses are being used by this pass. This is used to
310 // make sure that analyses are not free'd before we have to use
313 void markPassUsed(AnalysisID P, Pass *User) {
314 std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.find(P);
315 if (I != CurrentAnalyses.end()) {
316 LastUseOf[I->second] = User; // Local pass, extend the lifetime
318 // Pass not in current available set, must be a higher level pass
319 // available to us, propogate to parent pass manager... We tell the
320 // parent that we (the passmanager) are using the analysis so that it
321 // frees the analysis AFTER this pass manager runs.
323 assert(Parent != 0 && "Pass available but not found! "
324 "Did your analysis pass 'Provide' itself?");
325 Parent->markPassUsed(P, this);
329 // Return the number of parent PassManagers that exist
330 virtual unsigned getDepth() const {
331 if (Parent == 0) return 0;
332 return 1 + Parent->getDepth();
335 virtual unsigned getNumContainedPasses() const { return Passes.size(); }
336 virtual const Pass *getContainedPass(unsigned N) const {
337 assert(N < Passes.size() && "Pass number out of range!");
341 // add - Add a pass to the queue of passes to run. This passes ownership of
342 // the Pass to the PassManager. When the PassManager is destroyed, the pass
343 // will be destroyed as well, so there is no need to delete the pass. This
344 // implies that all passes MUST be new'd.
346 void add(PassClass *P) {
347 // Get information about what analyses the pass uses...
348 AnalysisUsage AnUsage;
349 P->getAnalysisUsage(AnUsage);
350 const std::vector<AnalysisID> &Required = AnUsage.getRequiredSet();
352 // Loop over all of the analyses used by this pass,
353 for (std::vector<AnalysisID>::const_iterator I = Required.begin(),
354 E = Required.end(); I != E; ++I) {
355 if (getAnalysisOrNullDown(*I) == 0)
356 add((PassClass*)(*I)->createPass());
359 // Tell the pass to add itself to this PassManager... the way it does so
360 // depends on the class of the pass, and is critical to laying out passes in
361 // an optimal order..
363 P->addToPassManager(this, AnUsage);
368 // addPass - These functions are used to implement the subclass specific
369 // behaviors present in PassManager. Basically the add(Pass*) method ends up
370 // reflecting its behavior into a Pass::addToPassManager call. Subclasses of
371 // Pass override it specifically so that they can reflect the type
372 // information inherent in "this" back to the PassManager.
374 // For generic Pass subclasses (which are interprocedural passes), we simply
375 // add the pass to the end of the pass list and terminate any accumulation of
376 // FunctionPass's that are present.
378 void addPass(PassClass *P, AnalysisUsage &AnUsage) {
379 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
381 // FIXME: If this pass being added isn't killed by any of the passes in the
382 // batcher class then we can reorder to pass to execute before the batcher
383 // does, which will potentially allow us to batch more passes!
385 //const std::vector<AnalysisID> &ProvidedSet = AnUsage.getProvidedSet();
386 if (Batcher /*&& ProvidedSet.empty()*/)
387 closeBatcher(); // This pass cannot be batched!
389 // Set the Resolver instance variable in the Pass so that it knows where to
390 // find this object...
392 setAnalysisResolver(P, this);
395 // Inform higher level pass managers (and ourselves) that these analyses are
396 // being used by this pass. This is used to make sure that analyses are not
397 // free'd before we have to use them...
399 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
400 E = RequiredSet.end(); I != E; ++I)
401 markPassUsed(*I, P); // Mark *I as used by P
403 // Erase all analyses not in the preserved set...
404 if (!AnUsage.preservesAll()) {
405 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
406 for (std::map<AnalysisID, Pass*>::iterator I = CurrentAnalyses.begin(),
407 E = CurrentAnalyses.end(); I != E; )
408 if (std::find(PreservedSet.begin(), PreservedSet.end(), I->first) !=
410 ++I; // This analysis is preserved, leave it in the available set...
412 #if MAP_DOESNT_HAVE_BROKEN_ERASE_MEMBER
413 I = CurrentAnalyses.erase(I); // Analysis not preserved!
415 CurrentAnalyses.erase(I);// GCC 2.95.3 STL doesn't have correct erase!
416 I = CurrentAnalyses.begin();
421 // Add this pass to the currently available set...
422 if (const PassInfo *PI = P->getPassInfo())
423 CurrentAnalyses[PI] = P;
425 // For now assume that our results are never used...
429 // For FunctionPass subclasses, we must be sure to batch the FunctionPass's
430 // together in a BatcherClass object so that all of the analyses are run
431 // together a function at a time.
433 void addPass(SubPassClass *MP, AnalysisUsage &AnUsage) {
434 if (Batcher == 0) // If we don't have a batcher yet, make one now.
435 Batcher = new BatcherClass(this);
436 // The Batcher will queue the passes up
437 MP->addToPassManager(Batcher, AnUsage);
440 // closeBatcher - Terminate the batcher that is being worked on.
441 void closeBatcher() {
443 Passes.push_back(Batcher);
451 //===----------------------------------------------------------------------===//
452 // PassManagerTraits<BasicBlock> Specialization
454 // This pass manager is used to group together all of the BasicBlockPass's
455 // into a single unit.
457 template<> struct PassManagerTraits<BasicBlock> : public BasicBlockPass {
458 // PassClass - The type of passes tracked by this PassManager
459 typedef BasicBlockPass PassClass;
461 // SubPassClass - The types of classes that should be collated together
462 // This is impossible to match, so BasicBlock instantiations of PassManagerT
465 typedef PassManagerT<Module> SubPassClass;
467 // BatcherClass - The type to use for collation of subtypes... This class is
468 // never instantiated for the PassManager<BasicBlock>, but it must be an
469 // instance of PassClass to typecheck.
471 typedef PassClass BatcherClass;
473 // ParentClass - The type of the parent PassManager...
474 typedef PassManagerT<Function> ParentClass;
476 // PMType - The type of the passmanager that subclasses this class
477 typedef PassManagerT<BasicBlock> PMType;
479 // runPass - Specify how the pass should be run on the UnitType
480 static bool runPass(PassClass *P, BasicBlock *M) {
481 // todo, init and finalize
482 return P->runOnBasicBlock(*M);
485 // Dummy implementation of PassStarted/PassEnded
486 static void PassStarted(Pass *P) {}
487 static void PassEnded(Pass *P) {}
489 // getPMName() - Return the name of the unit the PassManager operates on for
491 const char *getPMName() const { return "BasicBlock"; }
492 virtual const char *getPassName() const { return "BasicBlock Pass Manager"; }
494 // Implement the BasicBlockPass interface...
495 virtual bool doInitialization(Module &M);
496 virtual bool runOnBasicBlock(BasicBlock &BB);
497 virtual bool doFinalization(Module &M);
499 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
500 AU.setPreservesAll();
506 //===----------------------------------------------------------------------===//
507 // PassManagerTraits<Function> Specialization
509 // This pass manager is used to group together all of the FunctionPass's
510 // into a single unit.
512 template<> struct PassManagerTraits<Function> : public FunctionPass {
513 // PassClass - The type of passes tracked by this PassManager
514 typedef FunctionPass PassClass;
516 // SubPassClass - The types of classes that should be collated together
517 typedef BasicBlockPass SubPassClass;
519 // BatcherClass - The type to use for collation of subtypes...
520 typedef PassManagerT<BasicBlock> BatcherClass;
522 // ParentClass - The type of the parent PassManager...
523 typedef PassManagerT<Module> ParentClass;
525 // PMType - The type of the passmanager that subclasses this class
526 typedef PassManagerT<Function> PMType;
528 // runPass - Specify how the pass should be run on the UnitType
529 static bool runPass(PassClass *P, Function *F) {
530 return P->runOnFunction(*F);
533 // Dummy implementation of PassStarted/PassEnded
534 static void PassStarted(Pass *P) {}
535 static void PassEnded(Pass *P) {}
537 // getPMName() - Return the name of the unit the PassManager operates on for
539 const char *getPMName() const { return "Function"; }
540 virtual const char *getPassName() const { return "Function Pass Manager"; }
542 // Implement the FunctionPass interface...
543 virtual bool doInitialization(Module &M);
544 virtual bool runOnFunction(Function &F);
545 virtual bool doFinalization(Module &M);
547 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
548 AU.setPreservesAll();
554 //===----------------------------------------------------------------------===//
555 // PassManagerTraits<Module> Specialization
557 // This is the top level PassManager implementation that holds generic passes.
559 template<> struct PassManagerTraits<Module> : public Pass {
560 // PassClass - The type of passes tracked by this PassManager
561 typedef Pass PassClass;
563 // SubPassClass - The types of classes that should be collated together
564 typedef FunctionPass SubPassClass;
566 // BatcherClass - The type to use for collation of subtypes...
567 typedef PassManagerT<Function> BatcherClass;
569 // ParentClass - The type of the parent PassManager...
570 typedef AnalysisResolver ParentClass;
572 // runPass - Specify how the pass should be run on the UnitType
573 static bool runPass(PassClass *P, Module *M) { return P->run(*M); }
575 // getPMName() - Return the name of the unit the PassManager operates on for
577 const char *getPMName() const { return "Module"; }
578 virtual const char *getPassName() const { return "Module Pass Manager"; }
580 // TimingInformation - This data member maintains timing information for each
581 // of the passes that is executed.
583 TimingInfo *TimeInfo;
585 // PassStarted/Ended - This callback is notified any time a pass is started
586 // or stops. This is used to collect timing information about the different
587 // passes being executed.
589 void PassStarted(Pass *P) {
590 if (TimeInfo) TimeInfo->passStarted(P);
592 void PassEnded(Pass *P) {
593 if (TimeInfo) TimeInfo->passEnded(P);
596 // run - Implement the PassManager interface...
597 bool run(Module &M) {
598 TimeInfo = TimingInfo::create();
599 bool Result = ((PassManagerT<Module>*)this)->runOnUnit(&M);
607 // PassManagerTraits constructor - Create a timing info object if the user
608 // specified timing info should be collected on the command line.
610 PassManagerTraits() : TimeInfo(0) {}
615 //===----------------------------------------------------------------------===//
616 // PassManagerTraits Method Implementations
619 // PassManagerTraits<BasicBlock> Implementations
621 inline bool PassManagerTraits<BasicBlock>::doInitialization(Module &M) {
622 bool Changed = false;
623 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
624 ((PMType*)this)->Passes[i]->doInitialization(M);
628 inline bool PassManagerTraits<BasicBlock>::runOnBasicBlock(BasicBlock &BB) {
629 return ((PMType*)this)->runOnUnit(&BB);
632 inline bool PassManagerTraits<BasicBlock>::doFinalization(Module &M) {
633 bool Changed = false;
634 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
635 ((PMType*)this)->Passes[i]->doFinalization(M);
640 // PassManagerTraits<Function> Implementations
642 inline bool PassManagerTraits<Function>::doInitialization(Module &M) {
643 bool Changed = false;
644 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
645 ((PMType*)this)->Passes[i]->doInitialization(M);
649 inline bool PassManagerTraits<Function>::runOnFunction(Function &F) {
650 return ((PMType*)this)->runOnUnit(&F);
653 inline bool PassManagerTraits<Function>::doFinalization(Module &M) {
654 bool Changed = false;
655 for (unsigned i = 0, e = ((PMType*)this)->Passes.size(); i != e; ++i)
656 ((PMType*)this)->Passes[i]->doFinalization(M);