* PassInfo is allowed to be missing now (ie, not all passes need be registered)
[oota-llvm.git] / lib / VMCore / Pass.cpp
1 //===- Pass.cpp - LLVM Pass Infrastructure Impementation ------------------===//
2 //
3 // This file implements the LLVM Pass infrastructure.  It is primarily
4 // responsible with ensuring that passes are executed and batched together
5 // optimally.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/PassManager.h"
10 #include "PassManagerT.h"         // PassManagerT implementation
11 #include "llvm/Module.h"
12 #include "Support/STLExtras.h"
13 #include "Support/CommandLine.h"
14 #include "Support/TypeInfo.h"
15 #include <typeinfo>
16 #include <iostream>
17 #include <sys/time.h>
18 #include <stdio.h>
19
20 //===----------------------------------------------------------------------===//
21 //   AnalysisID Class Implementation
22 //
23
24 static std::vector<AnalysisID> CFGOnlyAnalyses;
25 #if 0
26 // Source of unique analysis ID #'s.
27 unsigned AnalysisID::NextID = 0;
28
29 AnalysisID::AnalysisID(const AnalysisID &AID, bool DependsOnlyOnCFG) {
30   ID = AID.ID;                    // Implement the copy ctor part...
31   Constructor = AID.Constructor;
32   
33   // If this analysis only depends on the CFG of the function, add it to the CFG
34   // only list...
35   if (DependsOnlyOnCFG)
36     CFGOnlyAnalyses.push_back(AID);
37 }
38 #endif
39
40 //===----------------------------------------------------------------------===//
41 //   AnalysisResolver Class Implementation
42 //
43
44 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
45   assert(P->Resolver == 0 && "Pass already in a PassManager!");
46   P->Resolver = AR;
47 }
48
49 //===----------------------------------------------------------------------===//
50 //   AnalysisUsage Class Implementation
51 //
52
53 // preservesCFG - This function should be called to by the pass, iff they do
54 // not:
55 //
56 //  1. Add or remove basic blocks from the function
57 //  2. Modify terminator instructions in any way.
58 //
59 // This function annotates the AnalysisUsage info object to say that analyses
60 // that only depend on the CFG are preserved by this pass.
61 //
62 void AnalysisUsage::preservesCFG() {
63   // Since this transformation doesn't modify the CFG, it preserves all analyses
64   // that only depend on the CFG (like dominators, loop info, etc...)
65   //
66   Preserved.insert(Preserved.end(),
67                    CFGOnlyAnalyses.begin(), CFGOnlyAnalyses.end());
68 }
69
70
71 //===----------------------------------------------------------------------===//
72 // PassManager implementation - The PassManager class is a simple Pimpl class
73 // that wraps the PassManagerT template.
74 //
75 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
76 PassManager::~PassManager() { delete PM; }
77 void PassManager::add(Pass *P) { PM->add(P); }
78 bool PassManager::run(Module &M) { return PM->run(M); }
79
80
81 //===----------------------------------------------------------------------===//
82 // TimingInfo Class - This class is used to calculate information about the
83 // amount of time each pass takes to execute.  This only happens with
84 // -time-passes is enabled on the command line.
85 //
86 static cl::opt<bool>
87 EnableTiming("time-passes",
88             cl::desc("Time each pass, printing elapsed time for each on exit"));
89
90 static double getTime() {
91   struct timeval T;
92   gettimeofday(&T, 0);
93   return T.tv_sec + T.tv_usec/1000000.0;
94 }
95
96 // Create method.  If Timing is enabled, this creates and returns a new timing
97 // object, otherwise it returns null.
98 //
99 TimingInfo *TimingInfo::create() {
100   return EnableTiming ? new TimingInfo() : 0;
101 }
102
103 void TimingInfo::passStarted(Pass *P) { TimingData[P] -= getTime(); }
104 void TimingInfo::passEnded(Pass *P) { TimingData[P] += getTime(); }
105
106 // TimingDtor - Print out information about timing information
107 TimingInfo::~TimingInfo() {
108   // Iterate over all of the data, converting it into the dual of the data map,
109   // so that the data is sorted by amount of time taken, instead of pointer.
110   //
111   std::vector<std::pair<double, Pass*> > Data;
112   double TotalTime = 0;
113   for (std::map<Pass*, double>::iterator I = TimingData.begin(),
114          E = TimingData.end(); I != E; ++I)
115     // Throw out results for "grouping" pass managers...
116     if (!dynamic_cast<AnalysisResolver*>(I->first)) {
117       Data.push_back(std::make_pair(I->second, I->first));
118       TotalTime += I->second;
119     }
120   
121   // Sort the data by time as the primary key, in reverse order...
122   std::sort(Data.begin(), Data.end(), std::greater<std::pair<double, Pass*> >());
123
124   // Print out timing header...
125   std::cerr << std::string(79, '=') << "\n"
126        << "                      ... Pass execution timing report ...\n"
127        << std::string(79, '=') << "\n  Total Execution Time: " << TotalTime
128        << " seconds\n\n  % Time: Seconds:\tPass Name:\n";
129
130   // Loop through all of the timing data, printing it out...
131   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
132     fprintf(stderr, "  %6.2f%% %fs\t%s\n", Data[i].first*100 / TotalTime,
133             Data[i].first, Data[i].second->getPassName());
134   }
135   std::cerr << "  100.00% " << TotalTime << "s\tTOTAL\n"
136        << std::string(79, '=') << "\n";
137 }
138
139
140 //===----------------------------------------------------------------------===//
141 // Pass debugging information.  Often it is useful to find out what pass is
142 // running when a crash occurs in a utility.  When this library is compiled with
143 // debugging on, a command line option (--debug-pass) is enabled that causes the
144 // pass name to be printed before it executes.
145 //
146
147 // Different debug levels that can be enabled...
148 enum PassDebugLevel {
149   None, Structure, Executions, Details
150 };
151
152 static cl::opt<enum PassDebugLevel>
153 PassDebugging("debug-pass", cl::Hidden,
154               cl::desc("Print PassManager debugging information"),
155               cl::values(
156   clEnumVal(None      , "disable debug output"),
157   // TODO: add option to print out pass names "PassOptions"
158   clEnumVal(Structure , "print pass structure before run()"),
159   clEnumVal(Executions, "print pass name before it is executed"),
160   clEnumVal(Details   , "print pass details when it is executed"),
161                          0));
162
163 void PMDebug::PrintPassStructure(Pass *P) {
164   if (PassDebugging >= Structure)
165     P->dumpPassStructure();
166 }
167
168 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
169                                    Pass *P, Annotable *V) {
170   if (PassDebugging >= Executions) {
171     std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '" 
172               << P->getPassName();
173     if (V) {
174       std::cerr << "' on ";
175
176       if (dynamic_cast<Module*>(V)) {
177         std::cerr << "Module\n"; return;
178       } else if (Function *F = dynamic_cast<Function*>(V))
179         std::cerr << "Function '" << F->getName();
180       else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
181         std::cerr << "BasicBlock '" << BB->getName();
182       else if (Value *Val = dynamic_cast<Value*>(V))
183         std::cerr << typeid(*Val).name() << " '" << Val->getName();
184     }
185     std::cerr << "'...\n";
186   }
187 }
188
189 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
190                                    Pass *P, const std::vector<AnalysisID> &Set){
191   if (PassDebugging >= Details && !Set.empty()) {
192     std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
193     for (unsigned i = 0; i != Set.size(); ++i) {
194       // FIXME: This can use the local pass map!
195       Pass *P = Set[i]->createPass();   // Good thing this is just debug code...
196       std::cerr << "  " << P->getPassName();
197       delete P;
198     }
199     std::cerr << "\n";
200   }
201 }
202
203 // dumpPassStructure - Implement the -debug-passes=Structure option
204 void Pass::dumpPassStructure(unsigned Offset) {
205   std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
206 }
207
208
209 //===----------------------------------------------------------------------===//
210 // Pass Implementation
211 //
212
213 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
214   PM->addPass(this, AU);
215 }
216
217
218 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
219 //
220 const char *Pass::getPassName() const {
221   if (const PassInfo *PI = getPassInfo())
222     return PI->getPassName();
223   return typeid(*this).name();
224 }
225
226 // print - Print out the internal state of the pass.  This is called by Analyse
227 // to print out the contents of an analysis.  Otherwise it is not neccesary to
228 // implement this method.
229 //
230 void Pass::print(std::ostream &O) const {
231   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
232 }
233
234 // dump - call print(std::cerr);
235 void Pass::dump() const {
236   print(std::cerr, 0);
237 }
238
239 //===----------------------------------------------------------------------===//
240 // FunctionPass Implementation
241 //
242
243 // run - On a module, we run this pass by initializing, runOnFunction'ing once
244 // for every function in the module, then by finalizing.
245 //
246 bool FunctionPass::run(Module &M) {
247   bool Changed = doInitialization(M);
248   
249   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
250     if (!I->isExternal())      // Passes are not run on external functions!
251     Changed |= runOnFunction(*I);
252   
253   return Changed | doFinalization(M);
254 }
255
256 // run - On a function, we simply initialize, run the function, then finalize.
257 //
258 bool FunctionPass::run(Function &F) {
259   if (F.isExternal()) return false;// Passes are not run on external functions!
260
261   return doInitialization(*F.getParent()) | runOnFunction(F)
262        | doFinalization(*F.getParent());
263 }
264
265 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
266                                     AnalysisUsage &AU) {
267   PM->addPass(this, AU);
268 }
269
270 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
271                                     AnalysisUsage &AU) {
272   PM->addPass(this, AU);
273 }
274
275 //===----------------------------------------------------------------------===//
276 // BasicBlockPass Implementation
277 //
278
279 // To run this pass on a function, we simply call runOnBasicBlock once for each
280 // function.
281 //
282 bool BasicBlockPass::runOnFunction(Function &F) {
283   bool Changed = false;
284   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
285     Changed |= runOnBasicBlock(*I);
286   return Changed;
287 }
288
289 // To run directly on the basic block, we initialize, runOnBasicBlock, then
290 // finalize.
291 //
292 bool BasicBlockPass::run(BasicBlock &BB) {
293   Module &M = *BB.getParent()->getParent();
294   return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
295 }
296
297 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
298                                       AnalysisUsage &AU) {
299   PM->addPass(this, AU);
300 }
301
302 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
303                                       AnalysisUsage &AU) {
304   PM->addPass(this, AU);
305 }
306
307
308 //===----------------------------------------------------------------------===//
309 // Pass Registration mechanism
310 //
311 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
312 static std::vector<PassRegistrationListener*> *Listeners = 0;
313
314 // getPassInfo - Return the PassInfo data structure that corresponds to this
315 // pass...
316 const PassInfo *Pass::getPassInfo() const {
317   if (PassInfoCache) return PassInfoCache;
318   if (PassInfoMap == 0) return 0;
319   std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(typeid(*this));
320   return (I != PassInfoMap->end()) ? I->second : 0;
321 }
322
323 void RegisterPassBase::registerPass(PassInfo *PI) {
324   if (PassInfoMap == 0)
325     PassInfoMap = new std::map<TypeInfo, PassInfo*>();
326
327   assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
328          "Pass already registered!");
329   PIObj = PI;
330   PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
331
332   // Notify any listeners...
333   if (Listeners)
334     for (std::vector<PassRegistrationListener*>::iterator
335            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
336       (*I)->passRegistered(PI);
337 }
338
339 RegisterPassBase::~RegisterPassBase() {
340   assert(PassInfoMap && "Pass registered but not in map!");
341   std::map<TypeInfo, PassInfo*>::iterator I =
342     PassInfoMap->find(PIObj->getTypeInfo());
343   assert(I != PassInfoMap->end() && "Pass registered but not in map!");
344
345   // Remove pass from the map...
346   PassInfoMap->erase(I);
347   if (PassInfoMap->empty()) {
348     delete PassInfoMap;
349     PassInfoMap = 0;
350   }
351
352   // Notify any listeners...
353   if (Listeners)
354     for (std::vector<PassRegistrationListener*>::iterator
355            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
356       (*I)->passUnregistered(PIObj);
357
358   // Delete the PassInfo object itself...
359   delete PIObj;
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   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
372   Listeners->push_back(this);
373 }
374
375 // dtor - Remove object from list of listeners...
376 PassRegistrationListener::~PassRegistrationListener() {
377   std::vector<PassRegistrationListener*>::iterator I =
378     std::find(Listeners->begin(), Listeners->end(), this);
379   assert(Listeners && I != Listeners->end() &&
380          "PassRegistrationListener not registered!");
381   Listeners->erase(I);
382
383   if (Listeners->empty()) {
384     delete Listeners;
385     Listeners = 0;
386   }
387 }
388
389 // enumeratePasses - Iterate over the registered passes, calling the
390 // passEnumerate callback on each PassInfo object.
391 //
392 void PassRegistrationListener::enumeratePasses() {
393   if (PassInfoMap)
394     for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
395            E = PassInfoMap->end(); I != E; ++I)
396       passEnumerate(I->second);
397 }