3c108fbeb7eaf51c2184ef2f2a6903e7d2318409
[oota-llvm.git] / lib / VMCore / Pass.cpp
1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVM Pass infrastructure.  It is primarily
11 // responsible with ensuring that passes are executed and batched together
12 // optimally.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/PassManager.h"
17 #include "PassManagerT.h"         // PassManagerT implementation
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/TypeInfo.h"
22 #include <iostream>
23 #include <set>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //   AnalysisResolver Class Implementation
28 //
29
30 AnalysisResolver::~AnalysisResolver() {
31 }
32 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
33   assert(P->Resolver == 0 && "Pass already in a PassManager!");
34   P->Resolver = AR;
35 }
36
37 //===----------------------------------------------------------------------===//
38 // PassManager implementation - The PassManager class is a simple Pimpl class
39 // that wraps the PassManagerT template.
40 //
41 PassManager::PassManager() : PM(new ModulePassManager()) {}
42 PassManager::~PassManager() { delete PM; }
43 void PassManager::add(Pass *P) {
44   ModulePass *MP = dynamic_cast<ModulePass*>(P);
45   assert(MP && "Not a modulepass?");
46   PM->add(MP);
47 }
48 bool PassManager::run(Module &M) { return PM->runOnModule(M); }
49
50 //===----------------------------------------------------------------------===//
51 // FunctionPassManager implementation - The FunctionPassManager class
52 // is a simple Pimpl class that wraps the PassManagerT template. It
53 // is like PassManager, but only deals in FunctionPasses.
54 //
55 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
56   PM(new FunctionPassManagerT()), MP(P) {}
57 FunctionPassManager::~FunctionPassManager() { delete PM; }
58 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
59 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
60
61 /// doInitialization - Run all of the initializers for the function passes.
62 ///
63 bool FunctionPassManager::doInitialization() {
64   return PM->doInitialization(*MP->getModule());
65 }
66
67 bool FunctionPassManager::run(Function &F) {
68   std::string errstr;
69   if (MP->materializeFunction(&F, &errstr)) {
70     std::cerr << "Error reading bytecode file: " << errstr << "\n";
71     abort();
72   }
73   return PM->runOnFunction(F);
74 }
75
76 /// doFinalization - Run all of the initializers for the function passes.
77 ///
78 bool FunctionPassManager::doFinalization() {
79   return PM->doFinalization(*MP->getModule());
80 }
81
82
83 //===----------------------------------------------------------------------===//
84 // TimingInfo Class - This class is used to calculate information about the
85 // amount of time each pass takes to execute.  This only happens with
86 // -time-passes is enabled on the command line.
87 //
88 bool llvm::TimePassesIsEnabled = false;
89 static cl::opt<bool,true>
90 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
91             cl::desc("Time each pass, printing elapsed time for each on exit"));
92
93 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
94 // a non null value (if the -time-passes option is enabled) or it leaves it
95 // null.  It may be called multiple times.
96 void TimingInfo::createTheTimeInfo() {
97   if (!TimePassesIsEnabled || TheTimeInfo) return;
98
99   // Constructed the first time this is called, iff -time-passes is enabled.
100   // This guarantees that the object will be constructed before static globals,
101   // thus it will be destroyed before them.
102   static TimingInfo TTI;
103   TheTimeInfo = &TTI;
104 }
105
106 void PMDebug::PrintArgumentInformation(const Pass *P) {
107   // Print out passes in pass manager...
108   if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
109     for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
110       PrintArgumentInformation(PM->getContainedPass(i));
111
112   } else {  // Normal pass.  Print argument information...
113     // Print out arguments for registered passes that are _optimizations_
114     if (const PassInfo *PI = P->getPassInfo())
115       if (!PI->isAnalysisGroup())
116         std::cerr << " -" << PI->getPassArgument();
117   }
118 }
119
120 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
121                                    Pass *P, Module *M) {
122   if (PassDebugging >= Executions) {
123     std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
124               << P->getPassName();
125     if (M) std::cerr << "' on Module '" << M->getModuleIdentifier() << "'\n";
126     std::cerr << "'...\n";
127   }
128 }
129
130 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
131                                    Pass *P, Function *F) {
132   if (PassDebugging >= Executions) {
133     std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
134               << P->getPassName();
135     if (F) std::cerr << "' on Function '" << F->getName();
136     std::cerr << "'...\n";
137   }
138 }
139
140 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
141                                    Pass *P, BasicBlock *BB) {
142   if (PassDebugging >= Executions) {
143     std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
144               << P->getPassName();
145     if (BB) std::cerr << "' on BasicBlock '" << BB->getName();
146     std::cerr << "'...\n";
147   }
148 }
149
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();
157     }
158     std::cerr << "\n";
159   }
160 }
161
162 //===----------------------------------------------------------------------===//
163 // Pass Implementation
164 //
165
166 void ModulePass::addToPassManager(ModulePassManager *PM, AnalysisUsage &AU) {
167   PM->addPass(this, AU);
168 }
169
170 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
171   return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
172 }
173
174 // dumpPassStructure - Implement the -debug-passes=Structure option
175 void Pass::dumpPassStructure(unsigned Offset) {
176   std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
177 }
178
179 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.
180 //
181 const char *Pass::getPassName() const {
182   if (const PassInfo *PI = getPassInfo())
183     return PI->getPassName();
184   return typeid(*this).name();
185 }
186
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.
190 //
191 void Pass::print(std::ostream &O,const Module*) const {
192   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
193 }
194
195 // dump - call print(std::cerr);
196 void Pass::dump() const {
197   print(std::cerr, 0);
198 }
199
200 //===----------------------------------------------------------------------===//
201 // ImmutablePass Implementation
202 //
203 void ImmutablePass::addToPassManager(ModulePassManager *PM, 
204                                      AnalysisUsage &AU) {
205   PM->addPass(this, AU);
206 }
207
208
209 //===----------------------------------------------------------------------===//
210 // FunctionPass Implementation
211 //
212
213 // run - On a module, we run this pass by initializing, runOnFunction'ing once
214 // for every function in the module, then by finalizing.
215 //
216 bool FunctionPass::runOnModule(Module &M) {
217   bool Changed = doInitialization(M);
218
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);
222
223   return Changed | doFinalization(M);
224 }
225
226 // run - On a function, we simply initialize, run the function, then finalize.
227 //
228 bool FunctionPass::run(Function &F) {
229   if (F.isExternal()) return false;// Passes are not run on external functions!
230
231   bool Changed = doInitialization(*F.getParent());
232   Changed |= runOnFunction(F);
233   return Changed | doFinalization(*F.getParent());
234 }
235
236 void FunctionPass::addToPassManager(ModulePassManager *PM,
237                                     AnalysisUsage &AU) {
238   PM->addPass(this, AU);
239 }
240
241 void FunctionPass::addToPassManager(FunctionPassManagerT *PM,
242                                     AnalysisUsage &AU) {
243   PM->addPass(this, AU);
244 }
245
246 //===----------------------------------------------------------------------===//
247 // BasicBlockPass Implementation
248 //
249
250 // To run this pass on a function, we simply call runOnBasicBlock once for each
251 // function.
252 //
253 bool BasicBlockPass::runOnFunction(Function &F) {
254   bool Changed = doInitialization(F);
255   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
256     Changed |= runOnBasicBlock(*I);
257   return Changed | doFinalization(F);
258 }
259
260 // To run directly on the basic block, we initialize, runOnBasicBlock, then
261 // finalize.
262 //
263 bool BasicBlockPass::runPass(BasicBlock &BB) {
264   Function &F = *BB.getParent();
265   Module &M = *F.getParent();
266   bool Changed = doInitialization(M);
267   Changed |= doInitialization(F);
268   Changed |= runOnBasicBlock(BB);
269   Changed |= doFinalization(F);
270   Changed |= doFinalization(M);
271   return Changed;
272 }
273
274 void BasicBlockPass::addToPassManager(FunctionPassManagerT *PM,
275                                       AnalysisUsage &AU) {
276   PM->addPass(this, AU);
277 }
278
279 void BasicBlockPass::addToPassManager(BasicBlockPassManager *PM,
280                                       AnalysisUsage &AU) {
281   PM->addPass(this, AU);
282 }
283
284
285 //===----------------------------------------------------------------------===//
286 // Pass Registration mechanism
287 //
288 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
289 static std::vector<PassRegistrationListener*> *Listeners = 0;
290
291 // getPassInfo - Return the PassInfo data structure that corresponds to this
292 // pass...
293 const PassInfo *Pass::getPassInfo() const {
294   if (PassInfoCache) return PassInfoCache;
295   return lookupPassInfo(typeid(*this));
296 }
297
298 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
299   if (PassInfoMap == 0) return 0;
300   std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
301   return (I != PassInfoMap->end()) ? I->second : 0;
302 }
303
304 void RegisterPassBase::registerPass() {
305   if (PassInfoMap == 0)
306     PassInfoMap = new std::map<TypeInfo, PassInfo*>();
307
308   assert(PassInfoMap->find(PIObj.getTypeInfo()) == PassInfoMap->end() &&
309          "Pass already registered!");
310   PassInfoMap->insert(std::make_pair(TypeInfo(PIObj.getTypeInfo()), &PIObj));
311
312   // Notify any listeners...
313   if (Listeners)
314     for (std::vector<PassRegistrationListener*>::iterator
315            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
316       (*I)->passRegistered(&PIObj);
317 }
318
319 void RegisterPassBase::unregisterPass() {
320   assert(PassInfoMap && "Pass registered but not in map!");
321   std::map<TypeInfo, PassInfo*>::iterator I =
322     PassInfoMap->find(PIObj.getTypeInfo());
323   assert(I != PassInfoMap->end() && "Pass registered but not in map!");
324
325   // Remove pass from the map...
326   PassInfoMap->erase(I);
327   if (PassInfoMap->empty()) {
328     delete PassInfoMap;
329     PassInfoMap = 0;
330   }
331
332   // Notify any listeners...
333   if (Listeners)
334     for (std::vector<PassRegistrationListener*>::iterator
335            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
336       (*I)->passUnregistered(&PIObj);
337 }
338
339 //===----------------------------------------------------------------------===//
340 //                  Analysis Group Implementation Code
341 //===----------------------------------------------------------------------===//
342
343 struct AnalysisGroupInfo {
344   const PassInfo *DefaultImpl;
345   std::set<const PassInfo *> Implementations;
346   AnalysisGroupInfo() : DefaultImpl(0) {}
347 };
348
349 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
350
351 // RegisterAGBase implementation
352 //
353 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
354                                const std::type_info *Pass, bool isDefault)
355   : RegisterPassBase(Interface),
356     ImplementationInfo(0), isDefaultImplementation(isDefault) {
357
358   InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
359   if (InterfaceInfo == 0) {
360     // First reference to Interface, register it now.
361     registerPass();
362     InterfaceInfo = &PIObj;
363   }
364   assert(PIObj.isAnalysisGroup() &&
365          "Trying to join an analysis group that is a normal pass!");
366
367   if (Pass) {
368     ImplementationInfo = Pass::lookupPassInfo(*Pass);
369     assert(ImplementationInfo &&
370            "Must register pass before adding to AnalysisGroup!");
371
372     // Make sure we keep track of the fact that the implementation implements
373     // the interface.
374     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
375     IIPI->addInterfaceImplemented(InterfaceInfo);
376
377     // Lazily allocate to avoid nasty initialization order dependencies
378     if (AnalysisGroupInfoMap == 0)
379       AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
380
381     AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
382     assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
383            "Cannot add a pass to the same analysis group more than once!");
384     AGI.Implementations.insert(ImplementationInfo);
385     if (isDefault) {
386       assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
387              "Default implementation for analysis group already specified!");
388       assert(ImplementationInfo->getNormalCtor() &&
389            "Cannot specify pass as default if it does not have a default ctor");
390       AGI.DefaultImpl = ImplementationInfo;
391       InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
392     }
393   }
394 }
395
396 void RegisterAGBase::setGroupName(const char *Name) {
397   assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
398   InterfaceInfo->setPassName(Name);
399 }
400
401 RegisterAGBase::~RegisterAGBase() {
402   if (ImplementationInfo) {
403     assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
404     AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
405
406     assert(AGI.Implementations.count(ImplementationInfo) &&
407            "Pass not a member of analysis group?");
408
409     if (AGI.DefaultImpl == ImplementationInfo)
410       AGI.DefaultImpl = 0;
411
412     AGI.Implementations.erase(ImplementationInfo);
413
414     // Last member of this analysis group? Unregister PassInfo, delete map entry
415     if (AGI.Implementations.empty()) {
416       assert(AGI.DefaultImpl == 0 &&
417              "Default implementation didn't unregister?");
418       AnalysisGroupInfoMap->erase(InterfaceInfo);
419       if (AnalysisGroupInfoMap->empty()) {  // Delete map if empty
420         delete AnalysisGroupInfoMap;
421         AnalysisGroupInfoMap = 0;
422       }
423     }
424   }
425   
426   if (InterfaceInfo == &PIObj)
427     unregisterPass();
428 }
429
430
431 //===----------------------------------------------------------------------===//
432 // PassRegistrationListener implementation
433 //
434
435 // PassRegistrationListener ctor - Add the current object to the list of
436 // PassRegistrationListeners...
437 PassRegistrationListener::PassRegistrationListener() {
438   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
439   Listeners->push_back(this);
440 }
441
442 // dtor - Remove object from list of listeners...
443 PassRegistrationListener::~PassRegistrationListener() {
444   std::vector<PassRegistrationListener*>::iterator I =
445     std::find(Listeners->begin(), Listeners->end(), this);
446   assert(Listeners && I != Listeners->end() &&
447          "PassRegistrationListener not registered!");
448   Listeners->erase(I);
449
450   if (Listeners->empty()) {
451     delete Listeners;
452     Listeners = 0;
453   }
454 }
455
456 // enumeratePasses - Iterate over the registered passes, calling the
457 // passEnumerate callback on each PassInfo object.
458 //
459 void PassRegistrationListener::enumeratePasses() {
460   if (PassInfoMap)
461     for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
462            E = PassInfoMap->end(); I != E; ++I)
463       passEnumerate(I->second);
464 }
465
466 //===----------------------------------------------------------------------===//
467 //   AnalysisUsage Class Implementation
468 //
469
470 // setPreservesCFG - This function should be called to by the pass, iff they do
471 // not:
472 //
473 //  1. Add or remove basic blocks from the function
474 //  2. Modify terminator instructions in any way.
475 //
476 // This function annotates the AnalysisUsage info object to say that analyses
477 // that only depend on the CFG are preserved by this pass.
478 //
479 void AnalysisUsage::setPreservesCFG() {
480   // Since this transformation doesn't modify the CFG, it preserves all analyses
481   // that only depend on the CFG (like dominators, loop info, etc...)
482   //
483   if (PassInfoMap) {
484     for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
485              E = PassInfoMap->end(); I != E; ++I)
486       if (I->second->isCFGOnlyPass())
487         Preserved.push_back(I->second);
488   }
489 }
490
491