1 //===- Pass.cpp - LLVM Pass Infrastructure Impementation ------------------===//
3 // This file implements the LLVM Pass infrastructure. It is primarily
4 // responsible with ensuring that passes are executed and batched together
7 //===----------------------------------------------------------------------===//
9 #include "llvm/PassManager.h"
10 #include "PassManagerT.h" // PassManagerT implementation
11 #include "llvm/Module.h"
12 #include "Support/STLExtras.h"
13 #include "Support/TypeInfo.h"
15 #include <sys/resource.h>
16 #include <sys/unistd.h>
19 //===----------------------------------------------------------------------===//
20 // AnalysisID Class Implementation
23 static std::vector<const PassInfo*> CFGOnlyAnalyses;
25 void RegisterPassBase::setPreservesCFG() {
26 CFGOnlyAnalyses.push_back(PIObj);
29 //===----------------------------------------------------------------------===//
30 // AnalysisResolver Class Implementation
33 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
34 assert(P->Resolver == 0 && "Pass already in a PassManager!");
38 //===----------------------------------------------------------------------===//
39 // AnalysisUsage Class Implementation
42 // preservesCFG - This function should be called to by the pass, iff they do
45 // 1. Add or remove basic blocks from the function
46 // 2. Modify terminator instructions in any way.
48 // This function annotates the AnalysisUsage info object to say that analyses
49 // that only depend on the CFG are preserved by this pass.
51 void AnalysisUsage::preservesCFG() {
52 // Since this transformation doesn't modify the CFG, it preserves all analyses
53 // that only depend on the CFG (like dominators, loop info, etc...)
55 Preserved.insert(Preserved.end(),
56 CFGOnlyAnalyses.begin(), CFGOnlyAnalyses.end());
60 //===----------------------------------------------------------------------===//
61 // PassManager implementation - The PassManager class is a simple Pimpl class
62 // that wraps the PassManagerT template.
64 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
65 PassManager::~PassManager() { delete PM; }
66 void PassManager::add(Pass *P) { PM->add(P); }
67 bool PassManager::run(Module &M) { return PM->run(M); }
70 //===----------------------------------------------------------------------===//
71 // TimingInfo Class - This class is used to calculate information about the
72 // amount of time each pass takes to execute. This only happens with
73 // -time-passes is enabled on the command line.
76 EnableTiming("time-passes",
77 cl::desc("Time each pass, printing elapsed time for each on exit"));
79 static TimeRecord getTimeRecord() {
80 static unsigned long PageSize = 0;
84 PageSize = sysconf(_SC_PAGE_SIZE);
87 PageSize = sysconf(_SC_PAGESIZE);
89 PageSize = getpagesize();
97 if (getrusage(RUSAGE_SELF, &RU)) {
98 perror("getrusage call failed: -time-passes info incorrect!");
102 Result.Elapsed = T.tv_sec + T.tv_usec/1000000.0;
103 Result.UserTime = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
104 Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/1000000.0;
105 Result.MaxRSS = RU.ru_maxrss*PageSize;
110 bool TimeRecord::operator<(const TimeRecord &TR) const {
111 // Primary sort key is User+System time
112 if (UserTime+SystemTime < TR.UserTime+TR.SystemTime)
114 if (UserTime+SystemTime > TR.UserTime+TR.SystemTime)
117 // Secondary sort key is Wall Time
118 return Elapsed < TR.Elapsed;
121 void TimeRecord::passStart(const TimeRecord &T) {
122 Elapsed -= T.Elapsed;
123 UserTime -= T.UserTime;
124 SystemTime -= T.SystemTime;
128 void TimeRecord::passEnd(const TimeRecord &T) {
129 Elapsed += T.Elapsed;
130 UserTime += T.UserTime;
131 SystemTime += T.SystemTime;
132 RSSTemp = T.MaxRSS - RSSTemp;
133 MaxRSS = std::max(MaxRSS, RSSTemp);
136 static void printVal(double Val, double Total) {
137 if (Total < 1e-7) // Avoid dividing by zero...
138 fprintf(stderr, " ----- ");
140 fprintf(stderr, " %7.4f (%5.1f%%)", Val, Val*100/Total);
143 void TimeRecord::print(const char *PassName, const TimeRecord &Total) const {
144 printVal(UserTime, Total.UserTime);
145 printVal(SystemTime, Total.SystemTime);
146 printVal(UserTime+SystemTime, Total.UserTime+Total.SystemTime);
147 printVal(Elapsed, Total.Elapsed);
149 fprintf(stderr, " ");
152 std::cerr << MaxRSS << "\t";
153 std::cerr << PassName << "\n";
157 // Create method. If Timing is enabled, this creates and returns a new timing
158 // object, otherwise it returns null.
160 TimingInfo *TimingInfo::create() {
161 return EnableTiming ? new TimingInfo() : 0;
164 void TimingInfo::passStarted(Pass *P) {
165 TimingData[P].passStart(getTimeRecord());
167 void TimingInfo::passEnded(Pass *P) {
168 TimingData[P].passEnd(getTimeRecord());
170 void TimeRecord::sum(const TimeRecord &TR) {
171 Elapsed += TR.Elapsed;
172 UserTime += TR.UserTime;
173 SystemTime += TR.SystemTime;
177 // TimingDtor - Print out information about timing information
178 TimingInfo::~TimingInfo() {
179 // Iterate over all of the data, converting it into the dual of the data map,
180 // so that the data is sorted by amount of time taken, instead of pointer.
182 std::vector<std::pair<TimeRecord, Pass*> > Data;
184 for (std::map<Pass*, TimeRecord>::iterator I = TimingData.begin(),
185 E = TimingData.end(); I != E; ++I)
186 // Throw out results for "grouping" pass managers...
187 if (!dynamic_cast<AnalysisResolver*>(I->first)) {
188 Data.push_back(std::make_pair(I->second, I->first));
189 Total.sum(I->second);
192 // Sort the data by time as the primary key, in reverse order...
193 std::sort(Data.begin(), Data.end(),
194 std::greater<std::pair<TimeRecord, Pass*> >());
196 // Print out timing header...
197 std::cerr << std::string(79, '=') << "\n"
198 << " ... Pass execution timing report ...\n"
199 << std::string(79, '=') << "\n Total Execution Time: "
200 << (Total.UserTime+Total.SystemTime) << " seconds ("
201 << Total.Elapsed << " wall clock)\n\n ---User Time--- "
202 << "--System Time-- --User+System-- ---Wall Time---";
205 std::cerr << " ---Mem---";
206 std::cerr << " --- Pass Name ---\n";
208 // Loop through all of the timing data, printing it out...
209 for (unsigned i = 0, e = Data.size(); i != e; ++i)
210 Data[i].first.print(Data[i].second->getPassName(), Total);
212 Total.print("TOTAL", Total);
216 void PMDebug::PrintArgumentInformation(const Pass *P) {
217 // Print out passes in pass manager...
218 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
219 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
220 PrintArgumentInformation(PM->getContainedPass(i));
222 } else { // Normal pass. Print argument information...
223 // Print out arguments for registered passes that are _optimizations_
224 if (const PassInfo *PI = P->getPassInfo())
225 if (PI->getPassType() & PassInfo::Optimization)
226 std::cerr << " -" << PI->getPassArgument();
230 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
231 Pass *P, Annotable *V) {
232 if (PassDebugging >= Executions) {
233 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
236 std::cerr << "' on ";
238 if (dynamic_cast<Module*>(V)) {
239 std::cerr << "Module\n"; return;
240 } else if (Function *F = dynamic_cast<Function*>(V))
241 std::cerr << "Function '" << F->getName();
242 else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
243 std::cerr << "BasicBlock '" << BB->getName();
244 else if (Value *Val = dynamic_cast<Value*>(V))
245 std::cerr << typeid(*Val).name() << " '" << Val->getName();
247 std::cerr << "'...\n";
251 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
252 Pass *P, const std::vector<AnalysisID> &Set){
253 if (PassDebugging >= Details && !Set.empty()) {
254 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
255 for (unsigned i = 0; i != Set.size(); ++i)
256 std::cerr << " " << Set[i]->getPassName();
261 //===----------------------------------------------------------------------===//
262 // Pass Implementation
265 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
266 PM->addPass(this, AU);
269 // dumpPassStructure - Implement the -debug-passes=Structure option
270 void Pass::dumpPassStructure(unsigned Offset) {
271 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
274 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
276 const char *Pass::getPassName() const {
277 if (const PassInfo *PI = getPassInfo())
278 return PI->getPassName();
279 return typeid(*this).name();
282 // print - Print out the internal state of the pass. This is called by Analyse
283 // to print out the contents of an analysis. Otherwise it is not neccesary to
284 // implement this method.
286 void Pass::print(std::ostream &O) const {
287 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
290 // dump - call print(std::cerr);
291 void Pass::dump() const {
295 //===----------------------------------------------------------------------===//
296 // FunctionPass Implementation
299 // run - On a module, we run this pass by initializing, runOnFunction'ing once
300 // for every function in the module, then by finalizing.
302 bool FunctionPass::run(Module &M) {
303 bool Changed = doInitialization(M);
305 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
306 if (!I->isExternal()) // Passes are not run on external functions!
307 Changed |= runOnFunction(*I);
309 return Changed | doFinalization(M);
312 // run - On a function, we simply initialize, run the function, then finalize.
314 bool FunctionPass::run(Function &F) {
315 if (F.isExternal()) return false;// Passes are not run on external functions!
317 return doInitialization(*F.getParent()) | runOnFunction(F)
318 | doFinalization(*F.getParent());
321 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
323 PM->addPass(this, AU);
326 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
328 PM->addPass(this, AU);
331 //===----------------------------------------------------------------------===//
332 // BasicBlockPass Implementation
335 // To run this pass on a function, we simply call runOnBasicBlock once for each
338 bool BasicBlockPass::runOnFunction(Function &F) {
339 bool Changed = false;
340 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
341 Changed |= runOnBasicBlock(*I);
345 // To run directly on the basic block, we initialize, runOnBasicBlock, then
348 bool BasicBlockPass::run(BasicBlock &BB) {
349 Module &M = *BB.getParent()->getParent();
350 return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
353 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
355 PM->addPass(this, AU);
358 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
360 PM->addPass(this, AU);
364 //===----------------------------------------------------------------------===//
365 // Pass Registration mechanism
367 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
368 static std::vector<PassRegistrationListener*> *Listeners = 0;
370 // getPassInfo - Return the PassInfo data structure that corresponds to this
372 const PassInfo *Pass::getPassInfo() const {
373 if (PassInfoCache) return PassInfoCache;
374 return lookupPassInfo(typeid(*this));
377 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
378 if (PassInfoMap == 0) return 0;
379 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
380 return (I != PassInfoMap->end()) ? I->second : 0;
383 void RegisterPassBase::registerPass(PassInfo *PI) {
384 if (PassInfoMap == 0)
385 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
387 assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
388 "Pass already registered!");
390 PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
392 // Notify any listeners...
394 for (std::vector<PassRegistrationListener*>::iterator
395 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
396 (*I)->passRegistered(PI);
399 void RegisterPassBase::unregisterPass(PassInfo *PI) {
400 assert(PassInfoMap && "Pass registered but not in map!");
401 std::map<TypeInfo, PassInfo*>::iterator I =
402 PassInfoMap->find(PI->getTypeInfo());
403 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
405 // Remove pass from the map...
406 PassInfoMap->erase(I);
407 if (PassInfoMap->empty()) {
412 // Notify any listeners...
414 for (std::vector<PassRegistrationListener*>::iterator
415 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
416 (*I)->passUnregistered(PI);
418 // Delete the PassInfo object itself...
422 //===----------------------------------------------------------------------===//
423 // Analysis Group Implementation Code
424 //===----------------------------------------------------------------------===//
426 struct AnalysisGroupInfo {
427 const PassInfo *DefaultImpl;
428 std::set<const PassInfo *> Implementations;
429 AnalysisGroupInfo() : DefaultImpl(0) {}
432 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
434 // RegisterAGBase implementation
436 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
437 const std::type_info *Pass, bool isDefault)
438 : ImplementationInfo(0), isDefaultImplementation(isDefault) {
440 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
441 if (InterfaceInfo == 0) { // First reference to Interface, add it now.
442 InterfaceInfo = // Create the new PassInfo for the interface...
443 new PassInfo("", "", Interface, PassInfo::AnalysisGroup, 0, 0);
444 registerPass(InterfaceInfo);
447 assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
448 "Trying to join an analysis group that is a normal pass!");
451 ImplementationInfo = Pass::lookupPassInfo(*Pass);
452 assert(ImplementationInfo &&
453 "Must register pass before adding to AnalysisGroup!");
455 // Lazily allocate to avoid nasty initialization order dependencies
456 if (AnalysisGroupInfoMap == 0)
457 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
459 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
460 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
461 "Cannot add a pass to the same analysis group more than once!");
462 AGI.Implementations.insert(ImplementationInfo);
464 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
465 "Default implementation for analysis group already specified!");
466 assert(ImplementationInfo->getNormalCtor() &&
467 "Cannot specify pass as default if it does not have a default ctor");
468 AGI.DefaultImpl = ImplementationInfo;
469 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
474 void RegisterAGBase::setGroupName(const char *Name) {
475 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
476 InterfaceInfo->setPassName(Name);
479 RegisterAGBase::~RegisterAGBase() {
480 if (ImplementationInfo) {
481 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
482 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
484 assert(AGI.Implementations.count(ImplementationInfo) &&
485 "Pass not a member of analysis group?");
487 if (AGI.DefaultImpl == ImplementationInfo)
490 AGI.Implementations.erase(ImplementationInfo);
492 // Last member of this analysis group? Unregister PassInfo, delete map entry
493 if (AGI.Implementations.empty()) {
494 assert(AGI.DefaultImpl == 0 &&
495 "Default implementation didn't unregister?");
496 AnalysisGroupInfoMap->erase(InterfaceInfo);
497 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
498 delete AnalysisGroupInfoMap;
499 AnalysisGroupInfoMap = 0;
502 unregisterPass(InterfaceInfo);
508 // findAnalysisGroupMember - Return an iterator pointing to one of the elements
509 // of Map if there is a pass in Map that is a member of the analysis group for
510 // the specified AnalysisGroupID.
512 static std::map<const PassInfo*, Pass*>::const_iterator
513 findAnalysisGroupMember(const PassInfo *AnalysisGroupID,
514 const std::map<const PassInfo*, Pass*> &Map) {
515 assert(AnalysisGroupID->getPassType() == PassInfo::AnalysisGroup &&
516 "AnalysisGroupID is not an analysis group!");
517 assert(AnalysisGroupInfoMap && AnalysisGroupInfoMap->count(AnalysisGroupID) &&
518 "Analysis Group does not have any registered members!");
520 // Get the set of all known implementations of this analysis group...
521 std::set<const PassInfo *> &Impls =
522 (*AnalysisGroupInfoMap)[AnalysisGroupID].Implementations;
524 // Scan over available passes, checking to see if any is a valid analysis
525 for (std::map<const PassInfo*, Pass*>::const_iterator I = Map.begin(),
526 E = Map.end(); I != E; ++I)
527 if (Impls.count(I->first)) // This is a valid analysis, return it.
530 return Map.end(); // Nothing of use found.
536 //===----------------------------------------------------------------------===//
537 // PassRegistrationListener implementation
540 // PassRegistrationListener ctor - Add the current object to the list of
541 // PassRegistrationListeners...
542 PassRegistrationListener::PassRegistrationListener() {
543 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
544 Listeners->push_back(this);
547 // dtor - Remove object from list of listeners...
548 PassRegistrationListener::~PassRegistrationListener() {
549 std::vector<PassRegistrationListener*>::iterator I =
550 std::find(Listeners->begin(), Listeners->end(), this);
551 assert(Listeners && I != Listeners->end() &&
552 "PassRegistrationListener not registered!");
555 if (Listeners->empty()) {
561 // enumeratePasses - Iterate over the registered passes, calling the
562 // passEnumerate callback on each PassInfo object.
564 void PassRegistrationListener::enumeratePasses() {
566 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
567 E = PassInfoMap->end(); I != E; ++I)
568 passEnumerate(I->second);