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