*** empty log message ***
[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 <typeinfo>
15 #include <iostream>
16 #include <sys/time.h>
17 #include <stdio.h>
18
19 //===----------------------------------------------------------------------===//
20 //   AnalysisID Class Implementation
21 //
22
23 static std::vector<AnalysisID> CFGOnlyAnalyses;
24
25 // Source of unique analysis ID #'s.
26 unsigned AnalysisID::NextID = 0;
27
28 AnalysisID::AnalysisID(const AnalysisID &AID, bool DependsOnlyOnCFG) {
29   ID = AID.ID;                    // Implement the copy ctor part...
30   Constructor = AID.Constructor;
31   
32   // If this analysis only depends on the CFG of the function, add it to the CFG
33   // only list...
34   if (DependsOnlyOnCFG)
35     CFGOnlyAnalyses.push_back(AID);
36 }
37
38 //===----------------------------------------------------------------------===//
39 //   AnalysisResolver Class Implementation
40 //
41
42 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
43   assert(P->Resolver == 0 && "Pass already in a PassManager!");
44   P->Resolver = AR;
45 }
46
47 //===----------------------------------------------------------------------===//
48 //   AnalysisUsage Class Implementation
49 //
50
51 // preservesCFG - This function should be called to by the pass, iff they do
52 // not:
53 //
54 //  1. Add or remove basic blocks from the function
55 //  2. Modify terminator instructions in any way.
56 //
57 // This function annotates the AnalysisUsage info object to say that analyses
58 // that only depend on the CFG are preserved by this pass.
59 //
60 void AnalysisUsage::preservesCFG() {
61   // Since this transformation doesn't modify the CFG, it preserves all analyses
62   // that only depend on the CFG (like dominators, loop info, etc...)
63   //
64   Preserved.insert(Preserved.end(),
65                    CFGOnlyAnalyses.begin(), CFGOnlyAnalyses.end());
66 }
67
68
69 //===----------------------------------------------------------------------===//
70 // PassManager implementation - The PassManager class is a simple Pimpl class
71 // that wraps the PassManagerT template.
72 //
73 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
74 PassManager::~PassManager() { delete PM; }
75 void PassManager::add(Pass *P) { PM->add(P); }
76 bool PassManager::run(Module &M) { return PM->run(M); }
77
78
79 //===----------------------------------------------------------------------===//
80 // TimingInfo Class - This class is used to calculate information about the
81 // amount of time each pass takes to execute.  This only happens with
82 // -time-passes is enabled on the command line.
83 //
84 static cl::opt<bool>
85 EnableTiming("time-passes",
86             cl::desc("Time each pass, printing elapsed time for each on exit"));
87
88 static double getTime() {
89   struct timeval T;
90   gettimeofday(&T, 0);
91   return T.tv_sec + T.tv_usec/1000000.0;
92 }
93
94 // Create method.  If Timing is enabled, this creates and returns a new timing
95 // object, otherwise it returns null.
96 //
97 TimingInfo *TimingInfo::create() {
98   return EnableTiming ? new TimingInfo() : 0;
99 }
100
101 void TimingInfo::passStarted(Pass *P) { TimingData[P] -= getTime(); }
102 void TimingInfo::passEnded(Pass *P) { TimingData[P] += getTime(); }
103
104 // TimingDtor - Print out information about timing information
105 TimingInfo::~TimingInfo() {
106   // Iterate over all of the data, converting it into the dual of the data map,
107   // so that the data is sorted by amount of time taken, instead of pointer.
108   //
109   std::vector<std::pair<double, Pass*> > Data;
110   double TotalTime = 0;
111   for (std::map<Pass*, double>::iterator I = TimingData.begin(),
112          E = TimingData.end(); I != E; ++I)
113     // Throw out results for "grouping" pass managers...
114     if (!dynamic_cast<AnalysisResolver*>(I->first)) {
115       Data.push_back(std::make_pair(I->second, I->first));
116       TotalTime += I->second;
117     }
118   
119   // Sort the data by time as the primary key, in reverse order...
120   std::sort(Data.begin(), Data.end(), std::greater<std::pair<double, Pass*> >());
121
122   // Print out timing header...
123   std::cerr << std::string(79, '=') << "\n"
124        << "                      ... Pass execution timing report ...\n"
125        << std::string(79, '=') << "\n  Total Execution Time: " << TotalTime
126        << " seconds\n\n  % Time: Seconds:\tPass Name:\n";
127
128   // Loop through all of the timing data, printing it out...
129   for (unsigned i = 0, e = Data.size(); i != e; ++i) {
130     fprintf(stderr, "  %6.2f%% %fs\t%s\n", Data[i].first*100 / TotalTime,
131             Data[i].first, Data[i].second->getPassName());
132   }
133   std::cerr << "  100.00% " << TotalTime << "s\tTOTAL\n"
134        << std::string(79, '=') << "\n";
135 }
136
137
138 //===----------------------------------------------------------------------===//
139 // Pass debugging information.  Often it is useful to find out what pass is
140 // running when a crash occurs in a utility.  When this library is compiled with
141 // debugging on, a command line option (--debug-pass) is enabled that causes the
142 // pass name to be printed before it executes.
143 //
144
145 // Different debug levels that can be enabled...
146 enum PassDebugLevel {
147   None, Structure, Executions, Details
148 };
149
150 static cl::opt<enum PassDebugLevel>
151 PassDebugging("debug-pass", cl::Hidden,
152               cl::desc("Print PassManager debugging information"),
153               cl::values(
154   clEnumVal(None      , "disable debug output"),
155   // TODO: add option to print out pass names "PassOptions"
156   clEnumVal(Structure , "print pass structure before run()"),
157   clEnumVal(Executions, "print pass name before it is executed"),
158   clEnumVal(Details   , "print pass details when it is executed"),
159                          0));
160
161 void PMDebug::PrintPassStructure(Pass *P) {
162   if (PassDebugging >= Structure)
163     P->dumpPassStructure();
164 }
165
166 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
167                                    Pass *P, Annotable *V) {
168   if (PassDebugging >= Executions) {
169     std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '" 
170               << P->getPassName();
171     if (V) {
172       std::cerr << "' on ";
173
174       if (dynamic_cast<Module*>(V)) {
175         std::cerr << "Module\n"; return;
176       } else if (Function *F = dynamic_cast<Function*>(V))
177         std::cerr << "Function '" << F->getName();
178       else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
179         std::cerr << "BasicBlock '" << BB->getName();
180       else if (Value *Val = dynamic_cast<Value*>(V))
181         std::cerr << typeid(*Val).name() << " '" << Val->getName();
182     }
183     std::cerr << "'...\n";
184   }
185 }
186
187 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
188                                    Pass *P, const std::vector<AnalysisID> &Set){
189   if (PassDebugging >= Details && !Set.empty()) {
190     std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
191     for (unsigned i = 0; i != Set.size(); ++i) {
192       Pass *P = Set[i].createPass();   // Good thing this is just debug code...
193       std::cerr << "  " << P->getPassName();
194       delete P;
195     }
196     std::cerr << "\n";
197   }
198 }
199
200 // dumpPassStructure - Implement the -debug-passes=Structure option
201 void Pass::dumpPassStructure(unsigned Offset = 0) {
202   std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
203 }
204
205
206 //===----------------------------------------------------------------------===//
207 // Pass Implementation
208 //
209
210 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
211   PM->addPass(this, AU);
212 }
213
214
215 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
216 //
217 const char *Pass::getPassName() const { return typeid(*this).name(); }
218
219 //===----------------------------------------------------------------------===//
220 // FunctionPass Implementation
221 //
222
223 // run - On a module, we run this pass by initializing, runOnFunction'ing once
224 // for every function in the module, then by finalizing.
225 //
226 bool FunctionPass::run(Module &M) {
227   bool Changed = doInitialization(M);
228   
229   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
230     if (!I->isExternal())      // Passes are not run on external functions!
231     Changed |= runOnFunction(*I);
232   
233   return Changed | doFinalization(M);
234 }
235
236 // run - On a function, we simply initialize, run the function, then finalize.
237 //
238 bool FunctionPass::run(Function &F) {
239   if (F.isExternal()) return false;// Passes are not run on external functions!
240
241   return doInitialization(*F.getParent()) | runOnFunction(F)
242        | doFinalization(*F.getParent());
243 }
244
245 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
246                                     AnalysisUsage &AU) {
247   PM->addPass(this, AU);
248 }
249
250 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
251                                     AnalysisUsage &AU) {
252   PM->addPass(this, AU);
253 }
254
255 //===----------------------------------------------------------------------===//
256 // BasicBlockPass Implementation
257 //
258
259 // To run this pass on a function, we simply call runOnBasicBlock once for each
260 // function.
261 //
262 bool BasicBlockPass::runOnFunction(Function &F) {
263   bool Changed = false;
264   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
265     Changed |= runOnBasicBlock(*I);
266   return Changed;
267 }
268
269 // To run directly on the basic block, we initialize, runOnBasicBlock, then
270 // finalize.
271 //
272 bool BasicBlockPass::run(BasicBlock &BB) {
273   Module &M = *BB.getParent()->getParent();
274   return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
275 }
276
277 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
278                                       AnalysisUsage &AU) {
279   PM->addPass(this, AU);
280 }
281
282 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
283                                       AnalysisUsage &AU) {
284   PM->addPass(this, AU);
285 }
286