ddee390e50938fc894cae897859c46c49044ab81
[oota-llvm.git] / lib / VMCore / Pass.cpp
1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
2 //
3 // This file implements the LLVM Pass infrastructure.  It is primarily
4 // responsible with ensuring that passes are executed and batched together
5 // optimally.
6 //
7 //===----------------------------------------------------------------------===//
8
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"
15 #include <set>
16
17 // IncludeFile - Stub function used to help linking out.
18 IncludeFile::IncludeFile(void*) {}
19
20 //===----------------------------------------------------------------------===//
21 //   AnalysisID Class Implementation
22 //
23
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;
29 }
30
31 void RegisterPassBase::setOnlyUsesCFG() {
32   getCFGOnlyAnalyses().push_back(PIObj);
33 }
34
35 //===----------------------------------------------------------------------===//
36 //   AnalysisResolver Class Implementation
37 //
38
39 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
40   assert(P->Resolver == 0 && "Pass already in a PassManager!");
41   P->Resolver = AR;
42 }
43
44 //===----------------------------------------------------------------------===//
45 //   AnalysisUsage Class Implementation
46 //
47
48 // setPreservesCFG - This function should be called to by the pass, iff they do
49 // not:
50 //
51 //  1. Add or remove basic blocks from the function
52 //  2. Modify terminator instructions in any way.
53 //
54 // This function annotates the AnalysisUsage info object to say that analyses
55 // that only depend on the CFG are preserved by this pass.
56 //
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...)
60   //
61   Preserved.insert(Preserved.end(),
62                    getCFGOnlyAnalyses().begin(), getCFGOnlyAnalyses().end());
63 }
64
65
66 //===----------------------------------------------------------------------===//
67 // PassManager implementation - The PassManager class is a simple Pimpl class
68 // that wraps the PassManagerT template.
69 //
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); }
74
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.
79 //
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);
89   return PM->run(F); 
90 }
91
92
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.
97 //
98 static cl::opt<bool>
99 EnableTiming("time-passes",
100             cl::desc("Time each pass, printing elapsed time for each on exit"));
101
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;
107
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;
112   TheTimeInfo = &TTI;
113 }
114
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));
120
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();
126   }
127 }
128
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 << " '" 
133               << P->getPassName();
134     if (V) {
135       std::cerr << "' on ";
136
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();
145     }
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 Pass::addToPassManager(PassManagerT<Module> *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 intelligable 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 {
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(PassManagerT<Module> *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::run(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   return doInitialization(*F.getParent()) | runOnFunction(F)
232        | doFinalization(*F.getParent());
233 }
234
235 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
236                                     AnalysisUsage &AU) {
237   PM->addPass(this, AU);
238 }
239
240 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
241                                     AnalysisUsage &AU) {
242   PM->addPass(this, AU);
243 }
244
245 //===----------------------------------------------------------------------===//
246 // BasicBlockPass Implementation
247 //
248
249 // To run this pass on a function, we simply call runOnBasicBlock once for each
250 // function.
251 //
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);
257 }
258
259 // To run directly on the basic block, we initialize, runOnBasicBlock, then
260 // finalize.
261 //
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);
267 }
268
269 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
270                                       AnalysisUsage &AU) {
271   PM->addPass(this, AU);
272 }
273
274 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
275                                       AnalysisUsage &AU) {
276   PM->addPass(this, AU);
277 }
278
279
280 //===----------------------------------------------------------------------===//
281 // Pass Registration mechanism
282 //
283 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
284 static std::vector<PassRegistrationListener*> *Listeners = 0;
285
286 // getPassInfo - Return the PassInfo data structure that corresponds to this
287 // pass...
288 const PassInfo *Pass::getPassInfo() const {
289   if (PassInfoCache) return PassInfoCache;
290   return lookupPassInfo(typeid(*this));
291 }
292
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;
297 }
298
299 void RegisterPassBase::registerPass(PassInfo *PI) {
300   if (PassInfoMap == 0)
301     PassInfoMap = new std::map<TypeInfo, PassInfo*>();
302
303   assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
304          "Pass already registered!");
305   PIObj = PI;
306   PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
307
308   // Notify any listeners...
309   if (Listeners)
310     for (std::vector<PassRegistrationListener*>::iterator
311            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
312       (*I)->passRegistered(PI);
313 }
314
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!");
320
321   // Remove pass from the map...
322   PassInfoMap->erase(I);
323   if (PassInfoMap->empty()) {
324     delete PassInfoMap;
325     PassInfoMap = 0;
326   }
327
328   // Notify any listeners...
329   if (Listeners)
330     for (std::vector<PassRegistrationListener*>::iterator
331            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
332       (*I)->passUnregistered(PI);
333
334   // Delete the PassInfo object itself...
335   delete PI;
336 }
337
338 //===----------------------------------------------------------------------===//
339 //                  Analysis Group Implementation Code
340 //===----------------------------------------------------------------------===//
341
342 struct AnalysisGroupInfo {
343   const PassInfo *DefaultImpl;
344   std::set<const PassInfo *> Implementations;
345   AnalysisGroupInfo() : DefaultImpl(0) {}
346 };
347
348 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
349
350 // RegisterAGBase implementation
351 //
352 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
353                                const std::type_info *Pass, bool isDefault)
354   : ImplementationInfo(0), isDefaultImplementation(isDefault) {
355
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);
361     PIObj = 0;
362   }
363   assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
364          "Trying to join an analysis group that is a normal pass!");
365
366   if (Pass) {
367     ImplementationInfo = Pass::lookupPassInfo(*Pass);
368     assert(ImplementationInfo &&
369            "Must register pass before adding to AnalysisGroup!");
370
371     // Make sure we keep track of the fact that the implementation implements
372     // the interface.
373     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
374     IIPI->addInterfaceImplemented(InterfaceInfo);
375
376     // Lazily allocate to avoid nasty initialization order dependencies
377     if (AnalysisGroupInfoMap == 0)
378       AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
379
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);
384     if (isDefault) {
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());
391     }
392   }
393 }
394
395 void RegisterAGBase::setGroupName(const char *Name) {
396   assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
397   InterfaceInfo->setPassName(Name);
398 }
399
400 RegisterAGBase::~RegisterAGBase() {
401   if (ImplementationInfo) {
402     assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
403     AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
404
405     assert(AGI.Implementations.count(ImplementationInfo) &&
406            "Pass not a member of analysis group?");
407
408     if (AGI.DefaultImpl == ImplementationInfo)
409       AGI.DefaultImpl = 0;
410     
411     AGI.Implementations.erase(ImplementationInfo);
412
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;
421       }
422
423       unregisterPass(InterfaceInfo);
424     }
425   }
426 }
427
428
429 //===----------------------------------------------------------------------===//
430 // PassRegistrationListener implementation
431 //
432
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);
438 }
439
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!");
446   Listeners->erase(I);
447
448   if (Listeners->empty()) {
449     delete Listeners;
450     Listeners = 0;
451   }
452 }
453
454 // enumeratePasses - Iterate over the registered passes, calling the
455 // passEnumerate callback on each PassInfo object.
456 //
457 void PassRegistrationListener::enumeratePasses() {
458   if (PassInfoMap)
459     for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
460            E = PassInfoMap->end(); I != E; ++I)
461       passEnumerate(I->second);
462 }