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