56e3acb99e671b0a69102fcf0d95e1feb4c449ba
[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 "llvm/Module.h"
18 #include "llvm/ModuleProvider.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/TypeInfo.h"
22 #include <set>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 //   AnalysisResolver Class Implementation
27 //
28
29 AnalysisResolver::~AnalysisResolver() {
30 }
31
32 //===----------------------------------------------------------------------===//
33 // Pass Implementation
34 //
35
36 // Force out-of-line virtual method.
37 ModulePass::~ModulePass() { }
38
39 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
40   return Resolver_New->getAnalysisToUpdate(AnalysisID, true) != 0;
41 }
42
43 // dumpPassStructure - Implement the -debug-passes=Structure option
44 void Pass::dumpPassStructure(unsigned Offset) {
45   cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
46 }
47
48 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.
49 //
50 const char *Pass::getPassName() const {
51   if (const PassInfo *PI = getPassInfo())
52     return PI->getPassName();
53   return typeid(*this).name();
54 }
55
56 // print - Print out the internal state of the pass.  This is called by Analyze
57 // to print out the contents of an analysis.  Otherwise it is not necessary to
58 // implement this method.
59 //
60 void Pass::print(std::ostream &O,const Module*) const {
61   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
62 }
63
64 // dump - call print(cerr);
65 void Pass::dump() const {
66   print(*cerr.stream(), 0);
67 }
68
69 //===----------------------------------------------------------------------===//
70 // ImmutablePass Implementation
71 //
72 // Force out-of-line virtual method.
73 ImmutablePass::~ImmutablePass() { }
74
75 //===----------------------------------------------------------------------===//
76 // FunctionPass Implementation
77 //
78
79 // run - On a module, we run this pass by initializing, runOnFunction'ing once
80 // for every function in the module, then by finalizing.
81 //
82 bool FunctionPass::runOnModule(Module &M) {
83   bool Changed = doInitialization(M);
84
85   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
86     if (!I->isExternal())      // Passes are not run on external functions!
87     Changed |= runOnFunction(*I);
88
89   return Changed | doFinalization(M);
90 }
91
92 // run - On a function, we simply initialize, run the function, then finalize.
93 //
94 bool FunctionPass::run(Function &F) {
95   if (F.isExternal()) return false;// Passes are not run on external functions!
96
97   bool Changed = doInitialization(*F.getParent());
98   Changed |= runOnFunction(F);
99   return Changed | doFinalization(*F.getParent());
100 }
101
102 //===----------------------------------------------------------------------===//
103 // BasicBlockPass Implementation
104 //
105
106 // To run this pass on a function, we simply call runOnBasicBlock once for each
107 // function.
108 //
109 bool BasicBlockPass::runOnFunction(Function &F) {
110   bool Changed = doInitialization(F);
111   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
112     Changed |= runOnBasicBlock(*I);
113   return Changed | doFinalization(F);
114 }
115
116 // To run directly on the basic block, we initialize, runOnBasicBlock, then
117 // finalize.
118 //
119 bool BasicBlockPass::runPass(BasicBlock &BB) {
120   Function &F = *BB.getParent();
121   Module &M = *F.getParent();
122   bool Changed = doInitialization(M);
123   Changed |= doInitialization(F);
124   Changed |= runOnBasicBlock(BB);
125   Changed |= doFinalization(F);
126   Changed |= doFinalization(M);
127   return Changed;
128 }
129
130 //===----------------------------------------------------------------------===//
131 // Pass Registration mechanism
132 //
133 namespace {
134 class PassRegistrar {
135   /// PassInfoMap - Keep track of the passinfo object for each registered llvm
136   /// pass.
137   std::map<TypeInfo, PassInfo*> PassInfoMap;
138   
139   /// AnalysisGroupInfo - Keep track of information for each analysis group.
140   struct AnalysisGroupInfo {
141     const PassInfo *DefaultImpl;
142     std::set<const PassInfo *> Implementations;
143     AnalysisGroupInfo() : DefaultImpl(0) {}
144   };
145   
146   /// AnalysisGroupInfoMap - Information for each analysis group.
147   std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
148
149 public:
150   
151   const PassInfo *GetPassInfo(const std::type_info &TI) const {
152     std::map<TypeInfo, PassInfo*>::const_iterator I = PassInfoMap.find(TI);
153     return I != PassInfoMap.end() ? I->second : 0;
154   }
155   
156   void RegisterPass(PassInfo &PI) {
157     bool Inserted =
158       PassInfoMap.insert(std::make_pair(TypeInfo(PI.getTypeInfo()),&PI)).second;
159     assert(Inserted && "Pass registered multiple times!");
160   }
161   
162   void UnregisterPass(PassInfo &PI) {
163     std::map<TypeInfo, PassInfo*>::iterator I =
164       PassInfoMap.find(PI.getTypeInfo());
165     assert(I != PassInfoMap.end() && "Pass registered but not in map!");
166     
167     // Remove pass from the map.
168     PassInfoMap.erase(I);
169   }
170   
171   void EnumerateWith(PassRegistrationListener *L) {
172     for (std::map<TypeInfo, PassInfo*>::const_iterator I = PassInfoMap.begin(),
173          E = PassInfoMap.end(); I != E; ++I)
174       L->passEnumerate(I->second);
175   }
176   
177   
178   /// Analysis Group Mechanisms.
179   void RegisterAnalysisGroup(PassInfo *InterfaceInfo,
180                              const PassInfo *ImplementationInfo,
181                              bool isDefault) {
182     AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
183     assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
184            "Cannot add a pass to the same analysis group more than once!");
185     AGI.Implementations.insert(ImplementationInfo);
186     if (isDefault) {
187       assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
188              "Default implementation for analysis group already specified!");
189       assert(ImplementationInfo->getNormalCtor() &&
190            "Cannot specify pass as default if it does not have a default ctor");
191       AGI.DefaultImpl = ImplementationInfo;
192       InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
193     }
194   }
195 };
196 }
197
198 static ManagedStatic<PassRegistrar> PassRegistrarObj;
199 static std::vector<PassRegistrationListener*> *Listeners = 0;
200
201 // getPassInfo - Return the PassInfo data structure that corresponds to this
202 // pass...
203 const PassInfo *Pass::getPassInfo() const {
204   if (PassInfoCache) return PassInfoCache;
205   return lookupPassInfo(typeid(*this));
206 }
207
208 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
209   return PassRegistrarObj->GetPassInfo(TI);
210 }
211
212 void RegisterPassBase::registerPass() {
213   PassRegistrarObj->RegisterPass(PIObj);
214
215   // Notify any listeners.
216   if (Listeners)
217     for (std::vector<PassRegistrationListener*>::iterator
218            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
219       (*I)->passRegistered(&PIObj);
220 }
221
222 void RegisterPassBase::unregisterPass() {
223   PassRegistrarObj->UnregisterPass(PIObj);
224 }
225
226 //===----------------------------------------------------------------------===//
227 //                  Analysis Group Implementation Code
228 //===----------------------------------------------------------------------===//
229
230 // RegisterAGBase implementation
231 //
232 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
233                                const std::type_info *Pass, bool isDefault)
234   : RegisterPassBase(Interface),
235     ImplementationInfo(0), isDefaultImplementation(isDefault) {
236
237   InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
238   if (InterfaceInfo == 0) {
239     // First reference to Interface, register it now.
240     registerPass();
241     InterfaceInfo = &PIObj;
242   }
243   assert(PIObj.isAnalysisGroup() &&
244          "Trying to join an analysis group that is a normal pass!");
245
246   if (Pass) {
247     ImplementationInfo = Pass::lookupPassInfo(*Pass);
248     assert(ImplementationInfo &&
249            "Must register pass before adding to AnalysisGroup!");
250
251     // Make sure we keep track of the fact that the implementation implements
252     // the interface.
253     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
254     IIPI->addInterfaceImplemented(InterfaceInfo);
255     
256     PassRegistrarObj->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
257   }
258 }
259
260 void RegisterAGBase::setGroupName(const char *Name) {
261   assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
262   InterfaceInfo->setPassName(Name);
263 }
264
265
266 //===----------------------------------------------------------------------===//
267 // PassRegistrationListener implementation
268 //
269
270 // PassRegistrationListener ctor - Add the current object to the list of
271 // PassRegistrationListeners...
272 PassRegistrationListener::PassRegistrationListener() {
273   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
274   Listeners->push_back(this);
275 }
276
277 // dtor - Remove object from list of listeners...
278 PassRegistrationListener::~PassRegistrationListener() {
279   std::vector<PassRegistrationListener*>::iterator I =
280     std::find(Listeners->begin(), Listeners->end(), this);
281   assert(Listeners && I != Listeners->end() &&
282          "PassRegistrationListener not registered!");
283   Listeners->erase(I);
284
285   if (Listeners->empty()) {
286     delete Listeners;
287     Listeners = 0;
288   }
289 }
290
291 // enumeratePasses - Iterate over the registered passes, calling the
292 // passEnumerate callback on each PassInfo object.
293 //
294 void PassRegistrationListener::enumeratePasses() {
295   PassRegistrarObj->EnumerateWith(this);
296 }
297
298 //===----------------------------------------------------------------------===//
299 //   AnalysisUsage Class Implementation
300 //
301
302 namespace {
303   struct GetCFGOnlyPasses : public PassRegistrationListener {
304     std::vector<AnalysisID> &CFGOnlyList;
305     GetCFGOnlyPasses(std::vector<AnalysisID> &L) : CFGOnlyList(L) {}
306     
307     void passEnumerate(const PassInfo *P) {
308       if (P->isCFGOnlyPass())
309         CFGOnlyList.push_back(P);
310     }
311   };
312 }
313
314 // setPreservesCFG - This function should be called to by the pass, iff they do
315 // not:
316 //
317 //  1. Add or remove basic blocks from the function
318 //  2. Modify terminator instructions in any way.
319 //
320 // This function annotates the AnalysisUsage info object to say that analyses
321 // that only depend on the CFG are preserved by this pass.
322 //
323 void AnalysisUsage::setPreservesCFG() {
324   // Since this transformation doesn't modify the CFG, it preserves all analyses
325   // that only depend on the CFG (like dominators, loop info, etc...)
326   GetCFGOnlyPasses(Preserved).enumeratePasses();
327 }
328
329