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