Add braces to clarify if/else structure and remove warning.
[oota-llvm.git] / lib / VMCore / Pass.cpp
1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Pass.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/Threading.h"
23 #include "llvm/System/Atomic.h"
24 #include <algorithm>
25 #include <map>
26 #include <set>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Pass Implementation
31 //
32
33 // Force out-of-line virtual method.
34 Pass::~Pass() { 
35   delete Resolver; 
36 }
37
38 // Force out-of-line virtual method.
39 ModulePass::~ModulePass() { }
40
41 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
42   return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0;
43 }
44
45 // dumpPassStructure - Implement the -debug-passes=Structure option
46 void Pass::dumpPassStructure(unsigned Offset) {
47   cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
48 }
49
50 /// getPassName - Return a nice clean name for a pass.  This usually
51 /// implemented in terms of the name that is registered by one of the
52 /// Registration templates, but can be overloaded directly.
53 ///
54 const char *Pass::getPassName() const {
55   if (const PassInfo *PI = getPassInfo())
56     return PI->getPassName();
57   return "Unnamed pass: implement Pass::getPassName()";
58 }
59
60 // print - Print out the internal state of the pass.  This is called by Analyze
61 // to print out the contents of an analysis.  Otherwise it is not necessary to
62 // implement this method.
63 //
64 void Pass::print(std::ostream &O,const Module*) const {
65   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
66 }
67
68 // dump - call print(cerr);
69 void Pass::dump() const {
70   print(*cerr.stream(), 0);
71 }
72
73 //===----------------------------------------------------------------------===//
74 // ImmutablePass Implementation
75 //
76 // Force out-of-line virtual method.
77 ImmutablePass::~ImmutablePass() { }
78
79 //===----------------------------------------------------------------------===//
80 // FunctionPass Implementation
81 //
82
83 // run - On a module, we run this pass by initializing, runOnFunction'ing once
84 // for every function in the module, then by finalizing.
85 //
86 bool FunctionPass::runOnModule(Module &M) {
87   bool Changed = doInitialization(M);
88
89   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
90     if (!I->isDeclaration())      // Passes are not run on external functions!
91     Changed |= runOnFunction(*I);
92
93   return Changed | doFinalization(M);
94 }
95
96 // run - On a function, we simply initialize, run the function, then finalize.
97 //
98 bool FunctionPass::run(Function &F) {
99   // Passes are not run on external functions!
100   if (F.isDeclaration()) return false;
101
102   bool Changed = doInitialization(*F.getParent());
103   Changed |= runOnFunction(F);
104   return Changed | doFinalization(*F.getParent());
105 }
106
107 //===----------------------------------------------------------------------===//
108 // BasicBlockPass Implementation
109 //
110
111 // To run this pass on a function, we simply call runOnBasicBlock once for each
112 // function.
113 //
114 bool BasicBlockPass::runOnFunction(Function &F) {
115   bool Changed = doInitialization(F);
116   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
117     Changed |= runOnBasicBlock(*I);
118   return Changed | doFinalization(F);
119 }
120
121 //===----------------------------------------------------------------------===//
122 // Pass Registration mechanism
123 //
124 namespace {
125 class PassRegistrar {
126   /// PassInfoMap - Keep track of the passinfo object for each registered llvm
127   /// pass.
128   typedef std::map<intptr_t, const PassInfo*> MapType;
129   MapType PassInfoMap;
130   
131   /// AnalysisGroupInfo - Keep track of information for each analysis group.
132   struct AnalysisGroupInfo {
133     const PassInfo *DefaultImpl;
134     std::set<const PassInfo *> Implementations;
135     AnalysisGroupInfo() : DefaultImpl(0) {}
136   };
137   
138   /// AnalysisGroupInfoMap - Information for each analysis group.
139   std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
140
141 public:
142   
143   const PassInfo *GetPassInfo(intptr_t TI) const {
144     MapType::const_iterator I = PassInfoMap.find(TI);
145     return I != PassInfoMap.end() ? I->second : 0;
146   }
147   
148   void RegisterPass(const PassInfo &PI) {
149     bool Inserted =
150       PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
151     assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted;
152   }
153   
154   void UnregisterPass(const PassInfo &PI) {
155     MapType::iterator I = PassInfoMap.find(PI.getTypeInfo());
156     assert(I != PassInfoMap.end() && "Pass registered but not in map!");
157     
158     // Remove pass from the map.
159     PassInfoMap.erase(I);
160   }
161   
162   void EnumerateWith(PassRegistrationListener *L) {
163     for (MapType::const_iterator I = PassInfoMap.begin(),
164          E = PassInfoMap.end(); I != E; ++I)
165       L->passEnumerate(I->second);
166   }
167   
168   
169   /// Analysis Group Mechanisms.
170   void RegisterAnalysisGroup(PassInfo *InterfaceInfo,
171                              const PassInfo *ImplementationInfo,
172                              bool isDefault) {
173     AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
174     assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
175            "Cannot add a pass to the same analysis group more than once!");
176     AGI.Implementations.insert(ImplementationInfo);
177     if (isDefault) {
178       assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
179              "Default implementation for analysis group already specified!");
180       assert(ImplementationInfo->getNormalCtor() &&
181            "Cannot specify pass as default if it does not have a default ctor");
182       AGI.DefaultImpl = ImplementationInfo;
183       InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
184     }
185   }
186 };
187 }
188
189 static std::vector<PassRegistrationListener*> *Listeners = 0;
190
191 // FIXME: This should use ManagedStatic to manage the pass registrar.
192 // Unfortunately, we can't do this, because passes are registered with static
193 // ctors, and having llvm_shutdown clear this map prevents successful
194 // ressurection after llvm_shutdown is run.
195 static PassRegistrar *getPassRegistrar() {
196   static PassRegistrar *PassRegistrarObj = 0;
197   
198   // Use double-checked locking to safely initialize the registrar when
199   // we're running in multithreaded mode.
200   if (!PassRegistrarObj) {
201     if (llvm_is_multithreaded()) {
202       llvm_acquire_global_lock();
203       if (!PassRegistrarObj) {
204         PassRegistrar* tmp = new PassRegistrar();
205         sys::MemoryFence();
206         PassRegistrarObj = tmp;
207       }
208       llvm_release_global_lock();
209     } else
210       PassRegistrarObj = new PassRegistrar();
211   }
212   return PassRegistrarObj;
213 }
214
215 // getPassInfo - Return the PassInfo data structure that corresponds to this
216 // pass...
217 const PassInfo *Pass::getPassInfo() const {
218   return lookupPassInfo(PassID);
219 }
220
221 const PassInfo *Pass::lookupPassInfo(intptr_t TI) {
222   return getPassRegistrar()->GetPassInfo(TI);
223 }
224
225 void PassInfo::registerPass() {
226   getPassRegistrar()->RegisterPass(*this);
227
228   // Notify any listeners.
229   if (Listeners)
230     for (std::vector<PassRegistrationListener*>::iterator
231            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
232       (*I)->passRegistered(this);
233 }
234
235 void PassInfo::unregisterPass() {
236   getPassRegistrar()->UnregisterPass(*this);
237 }
238
239 //===----------------------------------------------------------------------===//
240 //                  Analysis Group Implementation Code
241 //===----------------------------------------------------------------------===//
242
243 // RegisterAGBase implementation
244 //
245 RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID,
246                                intptr_t PassID, bool isDefault)
247   : PassInfo(Name, InterfaceID),
248     ImplementationInfo(0), isDefaultImplementation(isDefault) {
249
250   InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID));
251   if (InterfaceInfo == 0) {
252     // First reference to Interface, register it now.
253     registerPass();
254     InterfaceInfo = this;
255   }
256   assert(isAnalysisGroup() &&
257          "Trying to join an analysis group that is a normal pass!");
258
259   if (PassID) {
260     ImplementationInfo = Pass::lookupPassInfo(PassID);
261     assert(ImplementationInfo &&
262            "Must register pass before adding to AnalysisGroup!");
263
264     // Make sure we keep track of the fact that the implementation implements
265     // the interface.
266     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
267     IIPI->addInterfaceImplemented(InterfaceInfo);
268     
269     getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
270   }
271 }
272
273
274 //===----------------------------------------------------------------------===//
275 // PassRegistrationListener implementation
276 //
277
278 // PassRegistrationListener ctor - Add the current object to the list of
279 // PassRegistrationListeners...
280 PassRegistrationListener::PassRegistrationListener() {
281   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
282   Listeners->push_back(this);
283 }
284
285 // dtor - Remove object from list of listeners...
286 PassRegistrationListener::~PassRegistrationListener() {
287   std::vector<PassRegistrationListener*>::iterator I =
288     std::find(Listeners->begin(), Listeners->end(), this);
289   assert(Listeners && I != Listeners->end() &&
290          "PassRegistrationListener not registered!");
291   Listeners->erase(I);
292
293   if (Listeners->empty()) {
294     delete Listeners;
295     Listeners = 0;
296   }
297 }
298
299 // enumeratePasses - Iterate over the registered passes, calling the
300 // passEnumerate callback on each PassInfo object.
301 //
302 void PassRegistrationListener::enumeratePasses() {
303   getPassRegistrar()->EnumerateWith(this);
304 }
305
306 //===----------------------------------------------------------------------===//
307 //   AnalysisUsage Class Implementation
308 //
309
310 namespace {
311   struct GetCFGOnlyPasses : public PassRegistrationListener {
312     typedef AnalysisUsage::VectorType VectorType;
313     VectorType &CFGOnlyList;
314     GetCFGOnlyPasses(VectorType &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