fb751b5db05de2636231cdf98d51f7e8c5739499
[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 { return typeid(*this).name(); }
221
222 // print - Print out the internal state of the pass.  This is called by Analyse
223 // to print out the contents of an analysis.  Otherwise it is not neccesary to
224 // implement this method.
225 //
226 void Pass::print(std::ostream &O) const {
227   O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
228 }
229
230 // dump - call print(std::cerr);
231 void Pass::dump() const {
232   print(std::cerr, 0);
233 }
234
235 //===----------------------------------------------------------------------===//
236 // FunctionPass Implementation
237 //
238
239 // run - On a module, we run this pass by initializing, runOnFunction'ing once
240 // for every function in the module, then by finalizing.
241 //
242 bool FunctionPass::run(Module &M) {
243   bool Changed = doInitialization(M);
244   
245   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
246     if (!I->isExternal())      // Passes are not run on external functions!
247     Changed |= runOnFunction(*I);
248   
249   return Changed | doFinalization(M);
250 }
251
252 // run - On a function, we simply initialize, run the function, then finalize.
253 //
254 bool FunctionPass::run(Function &F) {
255   if (F.isExternal()) return false;// Passes are not run on external functions!
256
257   return doInitialization(*F.getParent()) | runOnFunction(F)
258        | doFinalization(*F.getParent());
259 }
260
261 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
262                                     AnalysisUsage &AU) {
263   PM->addPass(this, AU);
264 }
265
266 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
267                                     AnalysisUsage &AU) {
268   PM->addPass(this, AU);
269 }
270
271 //===----------------------------------------------------------------------===//
272 // BasicBlockPass Implementation
273 //
274
275 // To run this pass on a function, we simply call runOnBasicBlock once for each
276 // function.
277 //
278 bool BasicBlockPass::runOnFunction(Function &F) {
279   bool Changed = false;
280   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
281     Changed |= runOnBasicBlock(*I);
282   return Changed;
283 }
284
285 // To run directly on the basic block, we initialize, runOnBasicBlock, then
286 // finalize.
287 //
288 bool BasicBlockPass::run(BasicBlock &BB) {
289   Module &M = *BB.getParent()->getParent();
290   return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
291 }
292
293 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
294                                       AnalysisUsage &AU) {
295   PM->addPass(this, AU);
296 }
297
298 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
299                                       AnalysisUsage &AU) {
300   PM->addPass(this, AU);
301 }
302
303
304 //===----------------------------------------------------------------------===//
305 // Pass Registration mechanism
306 //
307 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
308 static std::vector<PassRegistrationListener*> *Listeners = 0;
309
310 // getPassInfo - Return the PassInfo data structure that corresponds to this
311 // pass...
312 const PassInfo *Pass::getPassInfo() const {
313   assert(PassInfoMap && "PassInfoMap not constructed yet??");
314   std::map<TypeInfo, PassInfo*>::iterator I =
315     PassInfoMap->find(typeid(*this));
316   assert(I != PassInfoMap->end() && "Pass has not been registered!");
317   return I->second;
318 }
319
320 void RegisterPassBase::registerPass(PassInfo *PI) {
321   if (PassInfoMap == 0)
322     PassInfoMap = new std::map<TypeInfo, PassInfo*>();
323
324   assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
325          "Pass already registered!");
326   PIObj = PI;
327   PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
328
329   // Notify any listeners...
330   if (Listeners)
331     for (std::vector<PassRegistrationListener*>::iterator
332            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
333       (*I)->passRegistered(PI);
334 }
335
336 RegisterPassBase::~RegisterPassBase() {
337   assert(PassInfoMap && "Pass registered but not in map!");
338   std::map<TypeInfo, PassInfo*>::iterator I =
339     PassInfoMap->find(PIObj->getTypeInfo());
340   assert(I != PassInfoMap->end() && "Pass registered but not in map!");
341
342   // Remove pass from the map...
343   PassInfoMap->erase(I);
344   if (PassInfoMap->empty()) {
345     delete PassInfoMap;
346     PassInfoMap = 0;
347   }
348
349   // Notify any listeners...
350   if (Listeners)
351     for (std::vector<PassRegistrationListener*>::iterator
352            I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
353       (*I)->passUnregistered(PIObj);
354
355   // Delete the PassInfo object itself...
356   delete PIObj;
357 }
358
359
360
361 //===----------------------------------------------------------------------===//
362 // PassRegistrationListener implementation
363 //
364
365 // PassRegistrationListener ctor - Add the current object to the list of
366 // PassRegistrationListeners...
367 PassRegistrationListener::PassRegistrationListener() {
368   if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
369   Listeners->push_back(this);
370 }
371
372 // dtor - Remove object from list of listeners...
373 PassRegistrationListener::~PassRegistrationListener() {
374   std::vector<PassRegistrationListener*>::iterator I =
375     std::find(Listeners->begin(), Listeners->end(), this);
376   assert(Listeners && I != Listeners->end() &&
377          "PassRegistrationListener not registered!");
378   Listeners->erase(I);
379
380   if (Listeners->empty()) {
381     delete Listeners;
382     Listeners = 0;
383   }
384 }
385
386 // enumeratePasses - Iterate over the registered passes, calling the
387 // passEnumerate callback on each PassInfo object.
388 //
389 void PassRegistrationListener::enumeratePasses() {
390   if (PassInfoMap)
391     for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
392            E = PassInfoMap->end(); I != E; ++I)
393       passEnumerate(I->second);
394 }