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"
26 // IncludeFile - Stub function used to help linking out.
27 IncludeFile::IncludeFile(void*) {}
29 //===----------------------------------------------------------------------===//
30 // AnalysisID Class Implementation
33 // getCFGOnlyAnalyses - A wrapper around the CFGOnlyAnalyses which make it
34 // initializer order independent.
35 static std::vector<const PassInfo*> &getCFGOnlyAnalyses() {
36 static std::vector<const PassInfo*> CFGOnlyAnalyses;
37 return CFGOnlyAnalyses;
40 void RegisterPassBase::setOnlyUsesCFG() {
41 getCFGOnlyAnalyses().push_back(PIObj);
44 //===----------------------------------------------------------------------===//
45 // AnalysisResolver Class Implementation
48 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
49 assert(P->Resolver == 0 && "Pass already in a PassManager!");
53 //===----------------------------------------------------------------------===//
54 // AnalysisUsage Class Implementation
57 // setPreservesCFG - This function should be called to by the pass, iff they do
60 // 1. Add or remove basic blocks from the function
61 // 2. Modify terminator instructions in any way.
63 // This function annotates the AnalysisUsage info object to say that analyses
64 // that only depend on the CFG are preserved by this pass.
66 void AnalysisUsage::setPreservesCFG() {
67 // Since this transformation doesn't modify the CFG, it preserves all analyses
68 // that only depend on the CFG (like dominators, loop info, etc...)
70 Preserved.insert(Preserved.end(),
71 getCFGOnlyAnalyses().begin(), getCFGOnlyAnalyses().end());
75 //===----------------------------------------------------------------------===//
76 // PassManager implementation - The PassManager class is a simple Pimpl class
77 // that wraps the PassManagerT template.
79 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
80 PassManager::~PassManager() { delete PM; }
81 void PassManager::add(Pass *P) { PM->add(P); }
82 bool PassManager::run(Module &M) { return PM->run(M); }
84 //===----------------------------------------------------------------------===//
85 // FunctionPassManager implementation - The FunctionPassManager class
86 // is a simple Pimpl class that wraps the PassManagerT template. It
87 // is like PassManager, but only deals in FunctionPasses.
89 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
90 PM(new PassManagerT<Function>()), MP(P) {}
91 FunctionPassManager::~FunctionPassManager() { delete PM; }
92 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
93 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
94 bool FunctionPassManager::run(Function &F) {
95 Function *mF = MP->getModule()->getNamedFunction(F.getName());
96 assert((&F == mF) && "ModuleProvider does not contain this function!");
97 MP->materializeFunction(&F);
102 //===----------------------------------------------------------------------===//
103 // TimingInfo Class - This class is used to calculate information about the
104 // amount of time each pass takes to execute. This only happens with
105 // -time-passes is enabled on the command line.
108 EnableTiming("time-passes",
109 cl::desc("Time each pass, printing elapsed time for each on exit"));
111 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
112 // a non null value (if the -time-passes option is enabled) or it leaves it
113 // null. It may be called multiple times.
114 void TimingInfo::createTheTimeInfo() {
115 if (!EnableTiming || TheTimeInfo) return;
117 // Constructed the first time this is called, iff -time-passes is enabled.
118 // This guarantees that the object will be constructed before static globals,
119 // thus it will be destroyed before them.
120 static TimingInfo TTI;
124 void PMDebug::PrintArgumentInformation(const Pass *P) {
125 // Print out passes in pass manager...
126 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
127 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
128 PrintArgumentInformation(PM->getContainedPass(i));
130 } else { // Normal pass. Print argument information...
131 // Print out arguments for registered passes that are _optimizations_
132 if (const PassInfo *PI = P->getPassInfo())
133 if (PI->getPassType() & PassInfo::Optimization)
134 std::cerr << " -" << PI->getPassArgument();
138 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
139 Pass *P, Annotable *V) {
140 if (PassDebugging >= Executions) {
141 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
144 std::cerr << "' on ";
146 if (dynamic_cast<Module*>(V)) {
147 std::cerr << "Module\n"; return;
148 } else if (Function *F = dynamic_cast<Function*>(V))
149 std::cerr << "Function '" << F->getName();
150 else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
151 std::cerr << "BasicBlock '" << BB->getName();
152 else if (Value *Val = dynamic_cast<Value*>(V))
153 std::cerr << typeid(*Val).name() << " '" << Val->getName();
155 std::cerr << "'...\n";
159 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
160 Pass *P, const std::vector<AnalysisID> &Set){
161 if (PassDebugging >= Details && !Set.empty()) {
162 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
163 for (unsigned i = 0; i != Set.size(); ++i) {
164 if (i) std::cerr << ",";
165 std::cerr << " " << Set[i]->getPassName();
171 //===----------------------------------------------------------------------===//
172 // Pass Implementation
175 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
176 PM->addPass(this, AU);
179 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
180 return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
183 // dumpPassStructure - Implement the -debug-passes=Structure option
184 void Pass::dumpPassStructure(unsigned Offset) {
185 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
188 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
190 const char *Pass::getPassName() const {
191 if (const PassInfo *PI = getPassInfo())
192 return PI->getPassName();
193 return typeid(*this).name();
196 // print - Print out the internal state of the pass. This is called by Analyze
197 // to print out the contents of an analysis. Otherwise it is not necessary to
198 // implement this method.
200 void Pass::print(std::ostream &O) const {
201 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
204 // dump - call print(std::cerr);
205 void Pass::dump() const {
209 //===----------------------------------------------------------------------===//
210 // ImmutablePass Implementation
212 void ImmutablePass::addToPassManager(PassManagerT<Module> *PM,
214 PM->addPass(this, AU);
218 //===----------------------------------------------------------------------===//
219 // FunctionPass Implementation
222 // run - On a module, we run this pass by initializing, runOnFunction'ing once
223 // for every function in the module, then by finalizing.
225 bool FunctionPass::run(Module &M) {
226 bool Changed = doInitialization(M);
228 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
229 if (!I->isExternal()) // Passes are not run on external functions!
230 Changed |= runOnFunction(*I);
232 return Changed | doFinalization(M);
235 // run - On a function, we simply initialize, run the function, then finalize.
237 bool FunctionPass::run(Function &F) {
238 if (F.isExternal()) return false;// Passes are not run on external functions!
240 return doInitialization(*F.getParent()) | runOnFunction(F)
241 | doFinalization(*F.getParent());
244 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
246 PM->addPass(this, AU);
249 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
251 PM->addPass(this, AU);
254 //===----------------------------------------------------------------------===//
255 // BasicBlockPass Implementation
258 // To run this pass on a function, we simply call runOnBasicBlock once for each
261 bool BasicBlockPass::runOnFunction(Function &F) {
262 bool Changed = doInitialization(F);
263 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
264 Changed |= runOnBasicBlock(*I);
265 return Changed | doFinalization(F);
268 // To run directly on the basic block, we initialize, runOnBasicBlock, then
271 bool BasicBlockPass::run(BasicBlock &BB) {
272 Function &F = *BB.getParent();
273 Module &M = *F.getParent();
274 return doInitialization(M) | doInitialization(F) | runOnBasicBlock(BB) |
275 doFinalization(F) | doFinalization(M);
278 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
280 PM->addPass(this, AU);
283 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
285 PM->addPass(this, AU);
289 //===----------------------------------------------------------------------===//
290 // Pass Registration mechanism
292 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
293 static std::vector<PassRegistrationListener*> *Listeners = 0;
295 // getPassInfo - Return the PassInfo data structure that corresponds to this
297 const PassInfo *Pass::getPassInfo() const {
298 if (PassInfoCache) return PassInfoCache;
299 return lookupPassInfo(typeid(*this));
302 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
303 if (PassInfoMap == 0) return 0;
304 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
305 return (I != PassInfoMap->end()) ? I->second : 0;
308 void RegisterPassBase::registerPass(PassInfo *PI) {
309 if (PassInfoMap == 0)
310 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
312 assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
313 "Pass already registered!");
315 PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
317 // Notify any listeners...
319 for (std::vector<PassRegistrationListener*>::iterator
320 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
321 (*I)->passRegistered(PI);
324 void RegisterPassBase::unregisterPass(PassInfo *PI) {
325 assert(PassInfoMap && "Pass registered but not in map!");
326 std::map<TypeInfo, PassInfo*>::iterator I =
327 PassInfoMap->find(PI->getTypeInfo());
328 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
330 // Remove pass from the map...
331 PassInfoMap->erase(I);
332 if (PassInfoMap->empty()) {
337 // Notify any listeners...
339 for (std::vector<PassRegistrationListener*>::iterator
340 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
341 (*I)->passUnregistered(PI);
343 // Delete the PassInfo object itself...
347 //===----------------------------------------------------------------------===//
348 // Analysis Group Implementation Code
349 //===----------------------------------------------------------------------===//
351 struct AnalysisGroupInfo {
352 const PassInfo *DefaultImpl;
353 std::set<const PassInfo *> Implementations;
354 AnalysisGroupInfo() : DefaultImpl(0) {}
357 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
359 // RegisterAGBase implementation
361 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
362 const std::type_info *Pass, bool isDefault)
363 : ImplementationInfo(0), isDefaultImplementation(isDefault) {
365 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
366 if (InterfaceInfo == 0) { // First reference to Interface, add it now.
367 InterfaceInfo = // Create the new PassInfo for the interface...
368 new PassInfo("", "", Interface, PassInfo::AnalysisGroup, 0, 0);
369 registerPass(InterfaceInfo);
372 assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
373 "Trying to join an analysis group that is a normal pass!");
376 ImplementationInfo = Pass::lookupPassInfo(*Pass);
377 assert(ImplementationInfo &&
378 "Must register pass before adding to AnalysisGroup!");
380 // Make sure we keep track of the fact that the implementation implements
382 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
383 IIPI->addInterfaceImplemented(InterfaceInfo);
385 // Lazily allocate to avoid nasty initialization order dependencies
386 if (AnalysisGroupInfoMap == 0)
387 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
389 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
390 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
391 "Cannot add a pass to the same analysis group more than once!");
392 AGI.Implementations.insert(ImplementationInfo);
394 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
395 "Default implementation for analysis group already specified!");
396 assert(ImplementationInfo->getNormalCtor() &&
397 "Cannot specify pass as default if it does not have a default ctor");
398 AGI.DefaultImpl = ImplementationInfo;
399 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
404 void RegisterAGBase::setGroupName(const char *Name) {
405 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
406 InterfaceInfo->setPassName(Name);
409 RegisterAGBase::~RegisterAGBase() {
410 if (ImplementationInfo) {
411 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
412 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
414 assert(AGI.Implementations.count(ImplementationInfo) &&
415 "Pass not a member of analysis group?");
417 if (AGI.DefaultImpl == ImplementationInfo)
420 AGI.Implementations.erase(ImplementationInfo);
422 // Last member of this analysis group? Unregister PassInfo, delete map entry
423 if (AGI.Implementations.empty()) {
424 assert(AGI.DefaultImpl == 0 &&
425 "Default implementation didn't unregister?");
426 AnalysisGroupInfoMap->erase(InterfaceInfo);
427 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
428 delete AnalysisGroupInfoMap;
429 AnalysisGroupInfoMap = 0;
432 unregisterPass(InterfaceInfo);
438 //===----------------------------------------------------------------------===//
439 // PassRegistrationListener implementation
442 // PassRegistrationListener ctor - Add the current object to the list of
443 // PassRegistrationListeners...
444 PassRegistrationListener::PassRegistrationListener() {
445 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
446 Listeners->push_back(this);
449 // dtor - Remove object from list of listeners...
450 PassRegistrationListener::~PassRegistrationListener() {
451 std::vector<PassRegistrationListener*>::iterator I =
452 std::find(Listeners->begin(), Listeners->end(), this);
453 assert(Listeners && I != Listeners->end() &&
454 "PassRegistrationListener not registered!");
457 if (Listeners->empty()) {
463 // enumeratePasses - Iterate over the registered passes, calling the
464 // passEnumerate callback on each PassInfo object.
466 void PassRegistrationListener::enumeratePasses() {
468 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
469 E = PassInfoMap->end(); I != E; ++I)
470 passEnumerate(I->second);
473 } // End llvm namespace