Move the memory fences out of the path for single-threaded mode.
[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/System/Atomic.h"
23 #include "llvm/System/Threading.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   PassRegistrar* tmp = PassRegistrarObj;
201   if (llvm_is_multithreaded()) {
202     sys::MemoryFence();
203     if (!tmp) {
204       llvm_acquire_global_lock();
205       tmp = PassRegistrarObj;
206       if (!tmp) {
207         tmp = new PassRegistrar();
208         sys::MemoryFence();
209         PassRegistrarObj = tmp;
210       }
211       llvm_release_global_lock();
212     }
213   } else if (!tmp) {
214     PassRegistrarObj = new PassRegistrar();
215   }
216   
217   return PassRegistrarObj;
218 }
219
220 // getPassInfo - Return the PassInfo data structure that corresponds to this
221 // pass...
222 const PassInfo *Pass::getPassInfo() const {
223   return lookupPassInfo(PassID);
224 }
225
226 const PassInfo *Pass::lookupPassInfo(intptr_t TI) {
227   return getPassRegistrar()->GetPassInfo(TI);
228 }
229
230 void PassInfo::registerPass() {
231   getPassRegistrar()->RegisterPass(*this);
232
233   // Notify any listeners.
234   if (Listeners)
235     for (std::vector<PassRegistrationListener*>::iterator
236            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
237       (*I)->passRegistered(this);
238 }
239
240 void PassInfo::unregisterPass() {
241   getPassRegistrar()->UnregisterPass(*this);
242 }
243
244 //===----------------------------------------------------------------------===//
245 //                  Analysis Group Implementation Code
246 //===----------------------------------------------------------------------===//
247
248 // RegisterAGBase implementation
249 //
250 RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID,
251                                intptr_t PassID, bool isDefault)
252   : PassInfo(Name, InterfaceID),
253     ImplementationInfo(0), isDefaultImplementation(isDefault) {
254
255   InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID));
256   if (InterfaceInfo == 0) {
257     // First reference to Interface, register it now.
258     registerPass();
259     InterfaceInfo = this;
260   }
261   assert(isAnalysisGroup() &&
262          "Trying to join an analysis group that is a normal pass!");
263
264   if (PassID) {
265     ImplementationInfo = Pass::lookupPassInfo(PassID);
266     assert(ImplementationInfo &&
267            "Must register pass before adding to AnalysisGroup!");
268
269     // Make sure we keep track of the fact that the implementation implements
270     // the interface.
271     PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
272     IIPI->addInterfaceImplemented(InterfaceInfo);
273     
274     getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
275   }
276 }
277
278
279 //===----------------------------------------------------------------------===//
280 // PassRegistrationListener implementation
281 //
282
283 // PassRegistrationListener ctor - Add the current object to the list of
284 // PassRegistrationListeners...
285 PassRegistrationListener::PassRegistrationListener() {
286   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
287   Listeners->push_back(this);
288 }
289
290 // dtor - Remove object from list of listeners...
291 PassRegistrationListener::~PassRegistrationListener() {
292   std::vector<PassRegistrationListener*>::iterator I =
293     std::find(Listeners->begin(), Listeners->end(), this);
294   assert(Listeners && I != Listeners->end() &&
295          "PassRegistrationListener not registered!");
296   Listeners->erase(I);
297
298   if (Listeners->empty()) {
299     delete Listeners;
300     Listeners = 0;
301   }
302 }
303
304 // enumeratePasses - Iterate over the registered passes, calling the
305 // passEnumerate callback on each PassInfo object.
306 //
307 void PassRegistrationListener::enumeratePasses() {
308   getPassRegistrar()->EnumerateWith(this);
309 }
310
311 //===----------------------------------------------------------------------===//
312 //   AnalysisUsage Class Implementation
313 //
314
315 namespace {
316   struct GetCFGOnlyPasses : public PassRegistrationListener {
317     typedef AnalysisUsage::VectorType VectorType;
318     VectorType &CFGOnlyList;
319     GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {}
320     
321     void passEnumerate(const PassInfo *P) {
322       if (P->isCFGOnlyPass())
323         CFGOnlyList.push_back(P);
324     }
325   };
326 }
327
328 // setPreservesCFG - This function should be called to by the pass, iff they do
329 // not:
330 //
331 //  1. Add or remove basic blocks from the function
332 //  2. Modify terminator instructions in any way.
333 //
334 // This function annotates the AnalysisUsage info object to say that analyses
335 // that only depend on the CFG are preserved by this pass.
336 //
337 void AnalysisUsage::setPreservesCFG() {
338   // Since this transformation doesn't modify the CFG, it preserves all analyses
339   // that only depend on the CFG (like dominators, loop info, etc...)
340   GetCFGOnlyPasses(Preserved).enumeratePasses();
341 }
342
343