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