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