1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM Pass infrastructure. It is primarily
11 // responsible with ensuring that passes are executed and batched together
14 //===----------------------------------------------------------------------===//
16 #include "llvm/PassManager.h"
17 #include "PassManagerT.h" // PassManagerT implementation
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "Support/STLExtras.h"
21 #include "Support/TypeInfo.h"
25 // IncludeFile - Stub function used to help linking out.
26 IncludeFile::IncludeFile(void*) {}
28 //===----------------------------------------------------------------------===//
29 // AnalysisID Class Implementation
32 // getCFGOnlyAnalyses - A wrapper around the CFGOnlyAnalyses which make it
33 // initializer order independent.
34 static std::vector<const PassInfo*> &getCFGOnlyAnalyses() {
35 static std::vector<const PassInfo*> CFGOnlyAnalyses;
36 return CFGOnlyAnalyses;
39 void RegisterPassBase::setOnlyUsesCFG() {
40 getCFGOnlyAnalyses().push_back(PIObj);
43 //===----------------------------------------------------------------------===//
44 // AnalysisResolver Class Implementation
47 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
48 assert(P->Resolver == 0 && "Pass already in a PassManager!");
52 //===----------------------------------------------------------------------===//
53 // AnalysisUsage Class Implementation
56 // setPreservesCFG - This function should be called to by the pass, iff they do
59 // 1. Add or remove basic blocks from the function
60 // 2. Modify terminator instructions in any way.
62 // This function annotates the AnalysisUsage info object to say that analyses
63 // that only depend on the CFG are preserved by this pass.
65 void AnalysisUsage::setPreservesCFG() {
66 // Since this transformation doesn't modify the CFG, it preserves all analyses
67 // that only depend on the CFG (like dominators, loop info, etc...)
69 Preserved.insert(Preserved.end(),
70 getCFGOnlyAnalyses().begin(), getCFGOnlyAnalyses().end());
74 //===----------------------------------------------------------------------===//
75 // PassManager implementation - The PassManager class is a simple Pimpl class
76 // that wraps the PassManagerT template.
78 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
79 PassManager::~PassManager() { delete PM; }
80 void PassManager::add(Pass *P) { PM->add(P); }
81 bool PassManager::run(Module &M) { return PM->run(M); }
83 //===----------------------------------------------------------------------===//
84 // FunctionPassManager implementation - The FunctionPassManager class
85 // is a simple Pimpl class that wraps the PassManagerT template. It
86 // is like PassManager, but only deals in FunctionPasses.
88 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
89 PM(new PassManagerT<Function>()), MP(P) {}
90 FunctionPassManager::~FunctionPassManager() { delete PM; }
91 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
92 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
93 bool FunctionPassManager::run(Function &F) {
94 MP->materializeFunction(&F);
99 //===----------------------------------------------------------------------===//
100 // TimingInfo Class - This class is used to calculate information about the
101 // amount of time each pass takes to execute. This only happens with
102 // -time-passes is enabled on the command line.
105 EnableTiming("time-passes",
106 cl::desc("Time each pass, printing elapsed time for each on exit"));
108 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
109 // a non null value (if the -time-passes option is enabled) or it leaves it
110 // null. It may be called multiple times.
111 void TimingInfo::createTheTimeInfo() {
112 if (!EnableTiming || TheTimeInfo) return;
114 // Constructed the first time this is called, iff -time-passes is enabled.
115 // This guarantees that the object will be constructed before static globals,
116 // thus it will be destroyed before them.
117 static TimingInfo TTI;
121 void PMDebug::PrintArgumentInformation(const Pass *P) {
122 // Print out passes in pass manager...
123 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
124 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
125 PrintArgumentInformation(PM->getContainedPass(i));
127 } else { // Normal pass. Print argument information...
128 // Print out arguments for registered passes that are _optimizations_
129 if (const PassInfo *PI = P->getPassInfo())
130 if (PI->getPassType() & PassInfo::Optimization)
131 std::cerr << " -" << PI->getPassArgument();
135 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
136 Pass *P, Annotable *V) {
137 if (PassDebugging >= Executions) {
138 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
141 std::cerr << "' on ";
143 if (dynamic_cast<Module*>(V)) {
144 std::cerr << "Module\n"; return;
145 } else if (Function *F = dynamic_cast<Function*>(V))
146 std::cerr << "Function '" << F->getName();
147 else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
148 std::cerr << "BasicBlock '" << BB->getName();
149 else if (Value *Val = dynamic_cast<Value*>(V))
150 std::cerr << typeid(*Val).name() << " '" << Val->getName();
152 std::cerr << "'...\n";
156 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
157 Pass *P, const std::vector<AnalysisID> &Set){
158 if (PassDebugging >= Details && !Set.empty()) {
159 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
160 for (unsigned i = 0; i != Set.size(); ++i) {
161 if (i) std::cerr << ",";
162 std::cerr << " " << Set[i]->getPassName();
168 //===----------------------------------------------------------------------===//
169 // Pass Implementation
172 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
173 PM->addPass(this, AU);
176 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
177 return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
180 // dumpPassStructure - Implement the -debug-passes=Structure option
181 void Pass::dumpPassStructure(unsigned Offset) {
182 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
185 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
187 const char *Pass::getPassName() const {
188 if (const PassInfo *PI = getPassInfo())
189 return PI->getPassName();
190 return typeid(*this).name();
193 // print - Print out the internal state of the pass. This is called by Analyze
194 // to print out the contents of an analysis. Otherwise it is not necessary to
195 // implement this method.
197 void Pass::print(std::ostream &O) const {
198 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
201 // dump - call print(std::cerr);
202 void Pass::dump() const {
206 //===----------------------------------------------------------------------===//
207 // ImmutablePass Implementation
209 void ImmutablePass::addToPassManager(PassManagerT<Module> *PM,
211 PM->addPass(this, AU);
215 //===----------------------------------------------------------------------===//
216 // FunctionPass Implementation
219 // run - On a module, we run this pass by initializing, runOnFunction'ing once
220 // for every function in the module, then by finalizing.
222 bool FunctionPass::run(Module &M) {
223 bool Changed = doInitialization(M);
225 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
226 if (!I->isExternal()) // Passes are not run on external functions!
227 Changed |= runOnFunction(*I);
229 return Changed | doFinalization(M);
232 // run - On a function, we simply initialize, run the function, then finalize.
234 bool FunctionPass::run(Function &F) {
235 if (F.isExternal()) return false;// Passes are not run on external functions!
237 return doInitialization(*F.getParent()) | runOnFunction(F)
238 | doFinalization(*F.getParent());
241 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
243 PM->addPass(this, AU);
246 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
248 PM->addPass(this, AU);
251 //===----------------------------------------------------------------------===//
252 // BasicBlockPass Implementation
255 // To run this pass on a function, we simply call runOnBasicBlock once for each
258 bool BasicBlockPass::runOnFunction(Function &F) {
259 bool Changed = doInitialization(F);
260 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
261 Changed |= runOnBasicBlock(*I);
262 return Changed | doFinalization(F);
265 // To run directly on the basic block, we initialize, runOnBasicBlock, then
268 bool BasicBlockPass::run(BasicBlock &BB) {
269 Function &F = *BB.getParent();
270 Module &M = *F.getParent();
271 return doInitialization(M) | doInitialization(F) | runOnBasicBlock(BB) |
272 doFinalization(F) | doFinalization(M);
275 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
277 PM->addPass(this, AU);
280 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
282 PM->addPass(this, AU);
286 //===----------------------------------------------------------------------===//
287 // Pass Registration mechanism
289 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
290 static std::vector<PassRegistrationListener*> *Listeners = 0;
292 // getPassInfo - Return the PassInfo data structure that corresponds to this
294 const PassInfo *Pass::getPassInfo() const {
295 if (PassInfoCache) return PassInfoCache;
296 return lookupPassInfo(typeid(*this));
299 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
300 if (PassInfoMap == 0) return 0;
301 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
302 return (I != PassInfoMap->end()) ? I->second : 0;
305 void RegisterPassBase::registerPass(PassInfo *PI) {
306 if (PassInfoMap == 0)
307 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
309 assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
310 "Pass already registered!");
312 PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
314 // Notify any listeners...
316 for (std::vector<PassRegistrationListener*>::iterator
317 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
318 (*I)->passRegistered(PI);
321 void RegisterPassBase::unregisterPass(PassInfo *PI) {
322 assert(PassInfoMap && "Pass registered but not in map!");
323 std::map<TypeInfo, PassInfo*>::iterator I =
324 PassInfoMap->find(PI->getTypeInfo());
325 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
327 // Remove pass from the map...
328 PassInfoMap->erase(I);
329 if (PassInfoMap->empty()) {
334 // Notify any listeners...
336 for (std::vector<PassRegistrationListener*>::iterator
337 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
338 (*I)->passUnregistered(PI);
340 // Delete the PassInfo object itself...
344 //===----------------------------------------------------------------------===//
345 // Analysis Group Implementation Code
346 //===----------------------------------------------------------------------===//
348 struct AnalysisGroupInfo {
349 const PassInfo *DefaultImpl;
350 std::set<const PassInfo *> Implementations;
351 AnalysisGroupInfo() : DefaultImpl(0) {}
354 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
356 // RegisterAGBase implementation
358 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
359 const std::type_info *Pass, bool isDefault)
360 : ImplementationInfo(0), isDefaultImplementation(isDefault) {
362 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
363 if (InterfaceInfo == 0) { // First reference to Interface, add it now.
364 InterfaceInfo = // Create the new PassInfo for the interface...
365 new PassInfo("", "", Interface, PassInfo::AnalysisGroup, 0, 0);
366 registerPass(InterfaceInfo);
369 assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
370 "Trying to join an analysis group that is a normal pass!");
373 ImplementationInfo = Pass::lookupPassInfo(*Pass);
374 assert(ImplementationInfo &&
375 "Must register pass before adding to AnalysisGroup!");
377 // Make sure we keep track of the fact that the implementation implements
379 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
380 IIPI->addInterfaceImplemented(InterfaceInfo);
382 // Lazily allocate to avoid nasty initialization order dependencies
383 if (AnalysisGroupInfoMap == 0)
384 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
386 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
387 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
388 "Cannot add a pass to the same analysis group more than once!");
389 AGI.Implementations.insert(ImplementationInfo);
391 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
392 "Default implementation for analysis group already specified!");
393 assert(ImplementationInfo->getNormalCtor() &&
394 "Cannot specify pass as default if it does not have a default ctor");
395 AGI.DefaultImpl = ImplementationInfo;
396 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
401 void RegisterAGBase::setGroupName(const char *Name) {
402 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
403 InterfaceInfo->setPassName(Name);
406 RegisterAGBase::~RegisterAGBase() {
407 if (ImplementationInfo) {
408 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
409 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
411 assert(AGI.Implementations.count(ImplementationInfo) &&
412 "Pass not a member of analysis group?");
414 if (AGI.DefaultImpl == ImplementationInfo)
417 AGI.Implementations.erase(ImplementationInfo);
419 // Last member of this analysis group? Unregister PassInfo, delete map entry
420 if (AGI.Implementations.empty()) {
421 assert(AGI.DefaultImpl == 0 &&
422 "Default implementation didn't unregister?");
423 AnalysisGroupInfoMap->erase(InterfaceInfo);
424 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
425 delete AnalysisGroupInfoMap;
426 AnalysisGroupInfoMap = 0;
429 unregisterPass(InterfaceInfo);
435 //===----------------------------------------------------------------------===//
436 // PassRegistrationListener implementation
439 // PassRegistrationListener ctor - Add the current object to the list of
440 // PassRegistrationListeners...
441 PassRegistrationListener::PassRegistrationListener() {
442 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
443 Listeners->push_back(this);
446 // dtor - Remove object from list of listeners...
447 PassRegistrationListener::~PassRegistrationListener() {
448 std::vector<PassRegistrationListener*>::iterator I =
449 std::find(Listeners->begin(), Listeners->end(), this);
450 assert(Listeners && I != Listeners->end() &&
451 "PassRegistrationListener not registered!");
454 if (Listeners->empty()) {
460 // enumeratePasses - Iterate over the registered passes, calling the
461 // passEnumerate callback on each PassInfo object.
463 void PassRegistrationListener::enumeratePasses() {
465 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
466 E = PassInfoMap->end(); I != E; ++I)
467 passEnumerate(I->second);