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