45000f2bef54682be3602583796c276b289b7b9f
[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/ADT/StringMap.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/System/Atomic.h"
27 #include "llvm/System/Mutex.h"
28 #include "llvm/System/Threading.h"
29 #include <algorithm>
30 #include <map>
31 #include <set>
32 using namespace llvm;
33
34 //===----------------------------------------------------------------------===//
35 // Pass Implementation
36 //
37
38 // Force out-of-line virtual method.
39 Pass::~Pass() { 
40   delete Resolver; 
41 }
42
43 // Force out-of-line virtual method.
44 ModulePass::~ModulePass() { }
45
46 PassManagerType ModulePass::getPotentialPassManagerType() const {
47   return PMT_ModulePassManager;
48 }
49
50 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
51   return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0;
52 }
53
54 // dumpPassStructure - Implement the -debug-passes=Structure option
55 void Pass::dumpPassStructure(unsigned Offset) {
56   dbgs().indent(Offset*2) << getPassName() << "\n";
57 }
58
59 /// getPassName - Return a nice clean name for a pass.  This usually
60 /// implemented in terms of the name that is registered by one of the
61 /// Registration templates, but can be overloaded directly.
62 ///
63 const char *Pass::getPassName() const {
64   if (const PassInfo *PI = getPassInfo())
65     return PI->getPassName();
66   return "Unnamed pass: implement Pass::getPassName()";
67 }
68
69 void Pass::preparePassManager(PMStack &) {
70   // By default, don't do anything.
71 }
72
73 PassManagerType Pass::getPotentialPassManagerType() const {
74   // Default implementation.
75   return PMT_Unknown; 
76 }
77
78 void Pass::getAnalysisUsage(AnalysisUsage &) const {
79   // By default, no analysis results are used, all are invalidated.
80 }
81
82 void Pass::releaseMemory() {
83   // By default, don't do anything.
84 }
85
86 void Pass::verifyAnalysis() const {
87   // By default, don't do anything.
88 }
89
90 // print - Print out the internal state of the pass.  This is called by Analyze
91 // to print out the contents of an analysis.  Otherwise it is not necessary to
92 // implement this method.
93 //
94 void Pass::print(raw_ostream &O,const Module*) const {
95   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
96 }
97
98 // dump - call print(cerr);
99 void Pass::dump() const {
100   print(dbgs(), 0);
101 }
102
103 //===----------------------------------------------------------------------===//
104 // ImmutablePass Implementation
105 //
106 // Force out-of-line virtual method.
107 ImmutablePass::~ImmutablePass() { }
108
109 void ImmutablePass::initializePass() {
110   // By default, don't do anything.
111 }
112
113 //===----------------------------------------------------------------------===//
114 // FunctionPass Implementation
115 //
116
117 // run - On a module, we run this pass by initializing, runOnFunction'ing once
118 // for every function in the module, then by finalizing.
119 //
120 bool FunctionPass::runOnModule(Module &M) {
121   bool Changed = doInitialization(M);
122
123   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
124     if (!I->isDeclaration())      // Passes are not run on external functions!
125     Changed |= runOnFunction(*I);
126
127   return Changed | doFinalization(M);
128 }
129
130 // run - On a function, we simply initialize, run the function, then finalize.
131 //
132 bool FunctionPass::run(Function &F) {
133   // Passes are not run on external functions!
134   if (F.isDeclaration()) return false;
135
136   bool Changed = doInitialization(*F.getParent());
137   Changed |= runOnFunction(F);
138   return Changed | doFinalization(*F.getParent());
139 }
140
141 bool FunctionPass::doInitialization(Module &) {
142   // By default, don't do anything.
143   return false;
144 }
145
146 bool FunctionPass::doFinalization(Module &) {
147   // By default, don't do anything.
148   return false;
149 }
150
151 PassManagerType FunctionPass::getPotentialPassManagerType() const {
152   return PMT_FunctionPassManager;
153 }
154
155 //===----------------------------------------------------------------------===//
156 // BasicBlockPass Implementation
157 //
158
159 // To run this pass on a function, we simply call runOnBasicBlock once for each
160 // function.
161 //
162 bool BasicBlockPass::runOnFunction(Function &F) {
163   bool Changed = doInitialization(F);
164   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
165     Changed |= runOnBasicBlock(*I);
166   return Changed | doFinalization(F);
167 }
168
169 bool BasicBlockPass::doInitialization(Module &) {
170   // By default, don't do anything.
171   return false;
172 }
173
174 bool BasicBlockPass::doInitialization(Function &) {
175   // By default, don't do anything.
176   return false;
177 }
178
179 bool BasicBlockPass::doFinalization(Function &) {
180   // By default, don't do anything.
181   return false;
182 }
183
184 bool BasicBlockPass::doFinalization(Module &) {
185   // By default, don't do anything.
186   return false;
187 }
188
189 PassManagerType BasicBlockPass::getPotentialPassManagerType() const {
190   return PMT_BasicBlockPassManager; 
191 }
192
193 //===----------------------------------------------------------------------===//
194 // Pass Registration mechanism
195 //
196 namespace {
197 class PassRegistrar {
198   /// PassInfoMap - Keep track of the passinfo object for each registered llvm
199   /// pass.
200   typedef std::map<intptr_t, const PassInfo*> MapType;
201   MapType PassInfoMap;
202
203   typedef StringMap<const PassInfo*> StringMapType;
204   StringMapType PassInfoStringMap;
205   
206   /// AnalysisGroupInfo - Keep track of information for each analysis group.
207   struct AnalysisGroupInfo {
208     std::set<const PassInfo *> Implementations;
209   };
210   
211   /// AnalysisGroupInfoMap - Information for each analysis group.
212   std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
213
214 public:
215   
216   const PassInfo *GetPassInfo(intptr_t TI) const {
217     MapType::const_iterator I = PassInfoMap.find(TI);
218     return I != PassInfoMap.end() ? I->second : 0;
219   }
220   
221   const PassInfo *GetPassInfo(StringRef Arg) const {
222     StringMapType::const_iterator I = PassInfoStringMap.find(Arg);
223     return I != PassInfoStringMap.end() ? I->second : 0;
224   }
225   
226   void RegisterPass(const PassInfo &PI) {
227     bool Inserted =
228       PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
229     assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted;
230     PassInfoStringMap[PI.getPassArgument()] = &PI;
231   }
232   
233   void UnregisterPass(const PassInfo &PI) {
234     MapType::iterator I = PassInfoMap.find(PI.getTypeInfo());
235     assert(I != PassInfoMap.end() && "Pass registered but not in map!");
236     
237     // Remove pass from the map.
238     PassInfoMap.erase(I);
239     PassInfoStringMap.erase(PI.getPassArgument());
240   }
241   
242   void EnumerateWith(PassRegistrationListener *L) {
243     for (MapType::const_iterator I = PassInfoMap.begin(),
244          E = PassInfoMap.end(); I != E; ++I)
245       L->passEnumerate(I->second);
246   }
247   
248   
249   /// Analysis Group Mechanisms.
250   void RegisterAnalysisGroup(PassInfo *InterfaceInfo,
251                              const PassInfo *ImplementationInfo,
252                              bool isDefault) {
253     AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
254     assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
255            "Cannot add a pass to the same analysis group more than once!");
256     AGI.Implementations.insert(ImplementationInfo);
257     if (isDefault) {
258       assert(InterfaceInfo->getNormalCtor() == 0 &&
259              "Default implementation for analysis group already specified!");
260       assert(ImplementationInfo->getNormalCtor() &&
261            "Cannot specify pass as default if it does not have a default ctor");
262       InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
263     }
264   }
265 };
266 }
267
268 static std::vector<PassRegistrationListener*> *Listeners = 0;
269 static sys::SmartMutex<true> ListenersLock;
270
271 // FIXME: This should use ManagedStatic to manage the pass registrar.
272 // Unfortunately, we can't do this, because passes are registered with static
273 // ctors, and having llvm_shutdown clear this map prevents successful
274 // ressurection after llvm_shutdown is run.
275 static PassRegistrar *getPassRegistrar() {
276   static PassRegistrar *PassRegistrarObj = 0;
277   
278   // Use double-checked locking to safely initialize the registrar when
279   // we're running in multithreaded mode.
280   PassRegistrar* tmp = PassRegistrarObj;
281   if (llvm_is_multithreaded()) {
282     sys::MemoryFence();
283     if (!tmp) {
284       llvm_acquire_global_lock();
285       tmp = PassRegistrarObj;
286       if (!tmp) {
287         tmp = new PassRegistrar();
288         sys::MemoryFence();
289         PassRegistrarObj = tmp;
290       }
291       llvm_release_global_lock();
292     }
293   } else if (!tmp) {
294     PassRegistrarObj = new PassRegistrar();
295   }
296   
297   return PassRegistrarObj;
298 }
299
300 // getPassInfo - Return the PassInfo data structure that corresponds to this
301 // pass...
302 const PassInfo *Pass::getPassInfo() const {
303   return lookupPassInfo(PassID);
304 }
305
306 const PassInfo *Pass::lookupPassInfo(intptr_t TI) {
307   return getPassRegistrar()->GetPassInfo(TI);
308 }
309
310 const PassInfo *Pass::lookupPassInfo(StringRef Arg) {
311   return getPassRegistrar()->GetPassInfo(Arg);
312 }
313
314 void PassInfo::registerPass() {
315   getPassRegistrar()->RegisterPass(*this);
316
317   // Notify any listeners.
318   sys::SmartScopedLock<true> Lock(ListenersLock);
319   if (Listeners)
320     for (std::vector<PassRegistrationListener*>::iterator
321            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
322       (*I)->passRegistered(this);
323 }
324
325 void PassInfo::unregisterPass() {
326   getPassRegistrar()->UnregisterPass(*this);
327 }
328
329 //===----------------------------------------------------------------------===//
330 //                  Analysis Group Implementation Code
331 //===----------------------------------------------------------------------===//
332
333 // RegisterAGBase implementation
334 //
335 RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID,
336                                intptr_t PassID, bool isDefault)
337   : PassInfo(Name, InterfaceID) {
338
339   PassInfo *InterfaceInfo =
340     const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID));
341   if (InterfaceInfo == 0) {
342     // First reference to Interface, register it now.
343     registerPass();
344     InterfaceInfo = this;
345   }
346   assert(isAnalysisGroup() &&
347          "Trying to join an analysis group that is a normal pass!");
348
349   if (PassID) {
350     const PassInfo *ImplementationInfo = Pass::lookupPassInfo(PassID);
351     assert(ImplementationInfo &&
352            "Must register pass before adding to AnalysisGroup!");
353
354     // Make sure we keep track of the fact that the implementation implements
355     // the interface.
356     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
357     IIPI->addInterfaceImplemented(InterfaceInfo);
358     
359     getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
360   }
361 }
362
363
364 //===----------------------------------------------------------------------===//
365 // PassRegistrationListener implementation
366 //
367
368 // PassRegistrationListener ctor - Add the current object to the list of
369 // PassRegistrationListeners...
370 PassRegistrationListener::PassRegistrationListener() {
371   sys::SmartScopedLock<true> Lock(ListenersLock);
372   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
373   Listeners->push_back(this);
374 }
375
376 // dtor - Remove object from list of listeners...
377 PassRegistrationListener::~PassRegistrationListener() {
378   sys::SmartScopedLock<true> Lock(ListenersLock);
379   std::vector<PassRegistrationListener*>::iterator I =
380     std::find(Listeners->begin(), Listeners->end(), this);
381   assert(Listeners && I != Listeners->end() &&
382          "PassRegistrationListener not registered!");
383   Listeners->erase(I);
384
385   if (Listeners->empty()) {
386     delete Listeners;
387     Listeners = 0;
388   }
389 }
390
391 // enumeratePasses - Iterate over the registered passes, calling the
392 // passEnumerate callback on each PassInfo object.
393 //
394 void PassRegistrationListener::enumeratePasses() {
395   getPassRegistrar()->EnumerateWith(this);
396 }
397
398 PassNameParser::~PassNameParser() {}
399
400 //===----------------------------------------------------------------------===//
401 //   AnalysisUsage Class Implementation
402 //
403
404 namespace {
405   struct GetCFGOnlyPasses : public PassRegistrationListener {
406     typedef AnalysisUsage::VectorType VectorType;
407     VectorType &CFGOnlyList;
408     GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {}
409     
410     void passEnumerate(const PassInfo *P) {
411       if (P->isCFGOnlyPass())
412         CFGOnlyList.push_back(P);
413     }
414   };
415 }
416
417 // setPreservesCFG - This function should be called to by the pass, iff they do
418 // not:
419 //
420 //  1. Add or remove basic blocks from the function
421 //  2. Modify terminator instructions in any way.
422 //
423 // This function annotates the AnalysisUsage info object to say that analyses
424 // that only depend on the CFG are preserved by this pass.
425 //
426 void AnalysisUsage::setPreservesCFG() {
427   // Since this transformation doesn't modify the CFG, it preserves all analyses
428   // that only depend on the CFG (like dominators, loop info, etc...)
429   GetCFGOnlyPasses(Preserved).enumeratePasses();
430 }
431
432