1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
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 "llvm/ModuleProvider.h"
13 #include "Support/STLExtras.h"
14 #include "Support/TypeInfo.h"
17 // IncludeFile - Stub function used to help linking out.
18 IncludeFile::IncludeFile(void*) {}
20 //===----------------------------------------------------------------------===//
21 // AnalysisID Class Implementation
24 // getCFGOnlyAnalyses - A wrapper around the CFGOnlyAnalyses which make it
25 // initializer order independent.
26 static std::vector<const PassInfo*> &getCFGOnlyAnalyses() {
27 static std::vector<const PassInfo*> CFGOnlyAnalyses;
28 return CFGOnlyAnalyses;
31 void RegisterPassBase::setOnlyUsesCFG() {
32 getCFGOnlyAnalyses().push_back(PIObj);
35 //===----------------------------------------------------------------------===//
36 // AnalysisResolver Class Implementation
39 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
40 assert(P->Resolver == 0 && "Pass already in a PassManager!");
44 //===----------------------------------------------------------------------===//
45 // AnalysisUsage Class Implementation
48 // setPreservesCFG - This function should be called to by the pass, iff they do
51 // 1. Add or remove basic blocks from the function
52 // 2. Modify terminator instructions in any way.
54 // This function annotates the AnalysisUsage info object to say that analyses
55 // that only depend on the CFG are preserved by this pass.
57 void AnalysisUsage::setPreservesCFG() {
58 // Since this transformation doesn't modify the CFG, it preserves all analyses
59 // that only depend on the CFG (like dominators, loop info, etc...)
61 Preserved.insert(Preserved.end(),
62 getCFGOnlyAnalyses().begin(), getCFGOnlyAnalyses().end());
66 //===----------------------------------------------------------------------===//
67 // PassManager implementation - The PassManager class is a simple Pimpl class
68 // that wraps the PassManagerT template.
70 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
71 PassManager::~PassManager() { delete PM; }
72 void PassManager::add(Pass *P) { PM->add(P); }
73 bool PassManager::run(Module &M) { return PM->run(M); }
75 //===----------------------------------------------------------------------===//
76 // FunctionPassManager implementation - The FunctionPassManager class
77 // is a simple Pimpl class that wraps the PassManagerT template. It
78 // is like PassManager, but only deals in FunctionPasses.
80 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
81 PM(new PassManagerT<Function>()), MP(P) {}
82 FunctionPassManager::~FunctionPassManager() { delete PM; }
83 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
84 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
85 bool FunctionPassManager::run(Function &F) {
86 Function *mF = MP->getModule()->getNamedFunction(F.getName());
87 assert((&F == mF) && "ModuleProvider does not contain this function!");
88 MP->materializeFunction(&F);
93 //===----------------------------------------------------------------------===//
94 // TimingInfo Class - This class is used to calculate information about the
95 // amount of time each pass takes to execute. This only happens with
96 // -time-passes is enabled on the command line.
99 EnableTiming("time-passes",
100 cl::desc("Time each pass, printing elapsed time for each on exit"));
102 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
103 // a non null value (if the -time-passes option is enabled) or it leaves it
104 // null. It may be called multiple times.
105 void TimingInfo::createTheTimeInfo() {
106 if (!EnableTiming || TheTimeInfo) return;
108 // Constructed the first time this is called, iff -time-passes is enabled.
109 // This guarantees that the object will be constructed before static globals,
110 // thus it will be destroyed before them.
111 static TimingInfo TTI;
115 void PMDebug::PrintArgumentInformation(const Pass *P) {
116 // Print out passes in pass manager...
117 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
118 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
119 PrintArgumentInformation(PM->getContainedPass(i));
121 } else { // Normal pass. Print argument information...
122 // Print out arguments for registered passes that are _optimizations_
123 if (const PassInfo *PI = P->getPassInfo())
124 if (PI->getPassType() & PassInfo::Optimization)
125 std::cerr << " -" << PI->getPassArgument();
129 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
130 Pass *P, Annotable *V) {
131 if (PassDebugging >= Executions) {
132 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
135 std::cerr << "' on ";
137 if (dynamic_cast<Module*>(V)) {
138 std::cerr << "Module\n"; return;
139 } else if (Function *F = dynamic_cast<Function*>(V))
140 std::cerr << "Function '" << F->getName();
141 else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
142 std::cerr << "BasicBlock '" << BB->getName();
143 else if (Value *Val = dynamic_cast<Value*>(V))
144 std::cerr << typeid(*Val).name() << " '" << Val->getName();
146 std::cerr << "'...\n";
150 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
151 Pass *P, const std::vector<AnalysisID> &Set){
152 if (PassDebugging >= Details && !Set.empty()) {
153 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
154 for (unsigned i = 0; i != Set.size(); ++i) {
155 if (i) std::cerr << ",";
156 std::cerr << " " << Set[i]->getPassName();
162 //===----------------------------------------------------------------------===//
163 // Pass Implementation
166 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
167 PM->addPass(this, AU);
170 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
171 return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
174 // dumpPassStructure - Implement the -debug-passes=Structure option
175 void Pass::dumpPassStructure(unsigned Offset) {
176 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
179 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
181 const char *Pass::getPassName() const {
182 if (const PassInfo *PI = getPassInfo())
183 return PI->getPassName();
184 return typeid(*this).name();
187 // print - Print out the internal state of the pass. This is called by Analyze
188 // to print out the contents of an analysis. Otherwise it is not necessary to
189 // implement this method.
191 void Pass::print(std::ostream &O) const {
192 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
195 // dump - call print(std::cerr);
196 void Pass::dump() const {
200 //===----------------------------------------------------------------------===//
201 // ImmutablePass Implementation
203 void ImmutablePass::addToPassManager(PassManagerT<Module> *PM,
205 PM->addPass(this, AU);
209 //===----------------------------------------------------------------------===//
210 // FunctionPass Implementation
213 // run - On a module, we run this pass by initializing, runOnFunction'ing once
214 // for every function in the module, then by finalizing.
216 bool FunctionPass::run(Module &M) {
217 bool Changed = doInitialization(M);
219 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
220 if (!I->isExternal()) // Passes are not run on external functions!
221 Changed |= runOnFunction(*I);
223 return Changed | doFinalization(M);
226 // run - On a function, we simply initialize, run the function, then finalize.
228 bool FunctionPass::run(Function &F) {
229 if (F.isExternal()) return false;// Passes are not run on external functions!
231 return doInitialization(*F.getParent()) | runOnFunction(F)
232 | doFinalization(*F.getParent());
235 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
237 PM->addPass(this, AU);
240 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
242 PM->addPass(this, AU);
245 //===----------------------------------------------------------------------===//
246 // BasicBlockPass Implementation
249 // To run this pass on a function, we simply call runOnBasicBlock once for each
252 bool BasicBlockPass::runOnFunction(Function &F) {
253 bool Changed = doInitialization(F);
254 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
255 Changed |= runOnBasicBlock(*I);
256 return Changed | doFinalization(F);
259 // To run directly on the basic block, we initialize, runOnBasicBlock, then
262 bool BasicBlockPass::run(BasicBlock &BB) {
263 Function &F = *BB.getParent();
264 Module &M = *F.getParent();
265 return doInitialization(M) | doInitialization(F) | runOnBasicBlock(BB) |
266 doFinalization(F) | doFinalization(M);
269 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
271 PM->addPass(this, AU);
274 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
276 PM->addPass(this, AU);
280 //===----------------------------------------------------------------------===//
281 // Pass Registration mechanism
283 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
284 static std::vector<PassRegistrationListener*> *Listeners = 0;
286 // getPassInfo - Return the PassInfo data structure that corresponds to this
288 const PassInfo *Pass::getPassInfo() const {
289 if (PassInfoCache) return PassInfoCache;
290 return lookupPassInfo(typeid(*this));
293 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
294 if (PassInfoMap == 0) return 0;
295 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
296 return (I != PassInfoMap->end()) ? I->second : 0;
299 void RegisterPassBase::registerPass(PassInfo *PI) {
300 if (PassInfoMap == 0)
301 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
303 assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
304 "Pass already registered!");
306 PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
308 // Notify any listeners...
310 for (std::vector<PassRegistrationListener*>::iterator
311 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
312 (*I)->passRegistered(PI);
315 void RegisterPassBase::unregisterPass(PassInfo *PI) {
316 assert(PassInfoMap && "Pass registered but not in map!");
317 std::map<TypeInfo, PassInfo*>::iterator I =
318 PassInfoMap->find(PI->getTypeInfo());
319 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
321 // Remove pass from the map...
322 PassInfoMap->erase(I);
323 if (PassInfoMap->empty()) {
328 // Notify any listeners...
330 for (std::vector<PassRegistrationListener*>::iterator
331 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
332 (*I)->passUnregistered(PI);
334 // Delete the PassInfo object itself...
338 //===----------------------------------------------------------------------===//
339 // Analysis Group Implementation Code
340 //===----------------------------------------------------------------------===//
342 struct AnalysisGroupInfo {
343 const PassInfo *DefaultImpl;
344 std::set<const PassInfo *> Implementations;
345 AnalysisGroupInfo() : DefaultImpl(0) {}
348 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
350 // RegisterAGBase implementation
352 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
353 const std::type_info *Pass, bool isDefault)
354 : ImplementationInfo(0), isDefaultImplementation(isDefault) {
356 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
357 if (InterfaceInfo == 0) { // First reference to Interface, add it now.
358 InterfaceInfo = // Create the new PassInfo for the interface...
359 new PassInfo("", "", Interface, PassInfo::AnalysisGroup, 0, 0);
360 registerPass(InterfaceInfo);
363 assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
364 "Trying to join an analysis group that is a normal pass!");
367 ImplementationInfo = Pass::lookupPassInfo(*Pass);
368 assert(ImplementationInfo &&
369 "Must register pass before adding to AnalysisGroup!");
371 // Make sure we keep track of the fact that the implementation implements
373 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
374 IIPI->addInterfaceImplemented(InterfaceInfo);
376 // Lazily allocate to avoid nasty initialization order dependencies
377 if (AnalysisGroupInfoMap == 0)
378 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
380 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
381 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
382 "Cannot add a pass to the same analysis group more than once!");
383 AGI.Implementations.insert(ImplementationInfo);
385 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
386 "Default implementation for analysis group already specified!");
387 assert(ImplementationInfo->getNormalCtor() &&
388 "Cannot specify pass as default if it does not have a default ctor");
389 AGI.DefaultImpl = ImplementationInfo;
390 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
395 void RegisterAGBase::setGroupName(const char *Name) {
396 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
397 InterfaceInfo->setPassName(Name);
400 RegisterAGBase::~RegisterAGBase() {
401 if (ImplementationInfo) {
402 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
403 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
405 assert(AGI.Implementations.count(ImplementationInfo) &&
406 "Pass not a member of analysis group?");
408 if (AGI.DefaultImpl == ImplementationInfo)
411 AGI.Implementations.erase(ImplementationInfo);
413 // Last member of this analysis group? Unregister PassInfo, delete map entry
414 if (AGI.Implementations.empty()) {
415 assert(AGI.DefaultImpl == 0 &&
416 "Default implementation didn't unregister?");
417 AnalysisGroupInfoMap->erase(InterfaceInfo);
418 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
419 delete AnalysisGroupInfoMap;
420 AnalysisGroupInfoMap = 0;
423 unregisterPass(InterfaceInfo);
429 //===----------------------------------------------------------------------===//
430 // PassRegistrationListener implementation
433 // PassRegistrationListener ctor - Add the current object to the list of
434 // PassRegistrationListeners...
435 PassRegistrationListener::PassRegistrationListener() {
436 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
437 Listeners->push_back(this);
440 // dtor - Remove object from list of listeners...
441 PassRegistrationListener::~PassRegistrationListener() {
442 std::vector<PassRegistrationListener*>::iterator I =
443 std::find(Listeners->begin(), Listeners->end(), this);
444 assert(Listeners && I != Listeners->end() &&
445 "PassRegistrationListener not registered!");
448 if (Listeners->empty()) {
454 // enumeratePasses - Iterate over the registered passes, calling the
455 // passEnumerate callback on each PassInfo object.
457 void PassRegistrationListener::enumeratePasses() {
459 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
460 E = PassInfoMap->end(); I != E; ++I)
461 passEnumerate(I->second);