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