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