make all llvm tools call llvm_shutdown when they exit, static'ify some stuff.
[oota-llvm.git] / tools / llvm-prof / llvm-prof.cpp
1 //===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===//
2 //
3 //                      The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tools is meant for use with the various LLVM profiling instrumentation
11 // passes.  It reads in the data file produced by executing an instrumented
12 // program, and outputs a nice report.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/InstrTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/Assembly/AsmAnnotationWriter.h"
19 #include "llvm/Analysis/ProfileInfoLoader.h"
20 #include "llvm/Bytecode/Reader.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/System/Signals.h"
24 #include <iostream>
25 #include <iomanip>
26 #include <map>
27 #include <set>
28
29 using namespace llvm;
30
31 namespace {
32   cl::opt<std::string>
33   BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"),
34                cl::Required);
35
36   cl::opt<std::string>
37   ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
38                   cl::Optional, cl::init("llvmprof.out"));
39
40   cl::opt<bool>
41   PrintAnnotatedLLVM("annotated-llvm",
42                      cl::desc("Print LLVM code with frequency annotations"));
43   cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"),
44                             cl::aliasopt(PrintAnnotatedLLVM));
45   cl::opt<bool>
46   PrintAllCode("print-all-code",
47                cl::desc("Print annotated code for the entire program"));
48 }
49
50 // PairSecondSort - A sorting predicate to sort by the second element of a pair.
51 template<class T>
52 struct PairSecondSortReverse
53   : public std::binary_function<std::pair<T, unsigned>,
54                                 std::pair<T, unsigned>, bool> {
55   bool operator()(const std::pair<T, unsigned> &LHS,
56                   const std::pair<T, unsigned> &RHS) const {
57     return LHS.second > RHS.second;
58   }
59 };
60
61 namespace {
62   class ProfileAnnotator : public AssemblyAnnotationWriter {
63     std::map<const Function  *, unsigned> &FuncFreqs;
64     std::map<const BasicBlock*, unsigned> &BlockFreqs;
65     std::map<ProfileInfoLoader::Edge, unsigned> &EdgeFreqs;
66   public:
67     ProfileAnnotator(std::map<const Function  *, unsigned> &FF,
68                      std::map<const BasicBlock*, unsigned> &BF,
69                      std::map<ProfileInfoLoader::Edge, unsigned> &EF)
70       : FuncFreqs(FF), BlockFreqs(BF), EdgeFreqs(EF) {}
71
72     virtual void emitFunctionAnnot(const Function *F, std::ostream &OS) {
73       OS << ";;; %" << F->getName() << " called " << FuncFreqs[F]
74          << " times.\n;;;\n";
75     }
76     virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
77                                           std::ostream &OS) {
78       if (BlockFreqs.empty()) return;
79       if (unsigned Count = BlockFreqs[BB])
80         OS << "\t;;; Basic block executed " << Count << " times.\n";
81       else
82         OS << "\t;;; Never executed!\n";
83     }
84
85     virtual void emitBasicBlockEndAnnot(const BasicBlock *BB, std::ostream &OS){
86       if (EdgeFreqs.empty()) return;
87
88       // Figure out how many times each successor executed.
89       std::vector<std::pair<const BasicBlock*, unsigned> > SuccCounts;
90       const TerminatorInst *TI = BB->getTerminator();
91
92       std::map<ProfileInfoLoader::Edge, unsigned>::iterator I =
93         EdgeFreqs.lower_bound(std::make_pair(const_cast<BasicBlock*>(BB), 0U));
94       for (; I != EdgeFreqs.end() && I->first.first == BB; ++I)
95         if (I->second)
96           SuccCounts.push_back(std::make_pair(TI->getSuccessor(I->first.second),
97                                               I->second));
98       if (!SuccCounts.empty()) {
99         OS << "\t;;; Out-edge counts:";
100         for (unsigned i = 0, e = SuccCounts.size(); i != e; ++i)
101           OS << " [" << SuccCounts[i].second << " -> "
102              << SuccCounts[i].first->getName() << "]";
103         OS << "\n";
104       }
105     }
106   };
107 }
108
109
110 int main(int argc, char **argv) {
111   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
112   try {
113     cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n");
114     sys::PrintStackTraceOnErrorSignal();
115
116     // Read in the bytecode file...
117     std::string ErrorMessage;
118     Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage);
119     if (M == 0) {
120       std::cerr << argv[0] << ": " << BytecodeFile << ": " 
121         << ErrorMessage << "\n";
122       return 1;
123     }
124
125     // Read the profiling information
126     ProfileInfoLoader PI(argv[0], ProfileDataFile, *M);
127
128     std::map<const Function  *, unsigned> FuncFreqs;
129     std::map<const BasicBlock*, unsigned> BlockFreqs;
130     std::map<ProfileInfoLoader::Edge, unsigned> EdgeFreqs;
131
132     // Output a report. Eventually, there will be multiple reports selectable on
133     // the command line, for now, just keep things simple.
134
135     // Emit the most frequent function table...
136     std::vector<std::pair<Function*, unsigned> > FunctionCounts;
137     PI.getFunctionCounts(FunctionCounts);
138     FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end());
139
140     // Sort by the frequency, backwards.
141     sort(FunctionCounts.begin(), FunctionCounts.end(),
142               PairSecondSortReverse<Function*>());
143
144     uint64_t TotalExecutions = 0;
145     for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
146       TotalExecutions += FunctionCounts[i].second;
147
148     std::cout << "===" << std::string(73, '-') << "===\n"
149               << "LLVM profiling output for execution";
150     if (PI.getNumExecutions() != 1) std::cout << "s";
151     std::cout << ":\n";
152
153     for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) {
154       std::cout << "  ";
155       if (e != 1) std::cout << i+1 << ". ";
156       std::cout << PI.getExecution(i) << "\n";
157     }
158
159     std::cout << "\n===" << std::string(73, '-') << "===\n";
160     std::cout << "Function execution frequencies:\n\n";
161
162     // Print out the function frequencies...
163     std::cout << " ##   Frequency\n";
164     for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
165       if (FunctionCounts[i].second == 0) {
166         std::cout << "\n  NOTE: " << e-i << " function" <<
167                (e-i-1 ? "s were" : " was") << " never executed!\n";
168         break;
169       }
170
171       std::cout << std::setw(3) << i+1 << ". " 
172         << std::setw(5) << FunctionCounts[i].second << "/"
173         << TotalExecutions << " "
174         << FunctionCounts[i].first->getName().c_str() << "\n";
175     }
176
177     std::set<Function*> FunctionsToPrint;
178
179     // If we have block count information, print out the LLVM module with
180     // frequency annotations.
181     if (PI.hasAccurateBlockCounts()) {
182       std::vector<std::pair<BasicBlock*, unsigned> > Counts;
183       PI.getBlockCounts(Counts);
184
185       TotalExecutions = 0;
186       for (unsigned i = 0, e = Counts.size(); i != e; ++i)
187         TotalExecutions += Counts[i].second;
188
189       // Sort by the frequency, backwards.
190       sort(Counts.begin(), Counts.end(),
191                 PairSecondSortReverse<BasicBlock*>());
192
193       std::cout << "\n===" << std::string(73, '-') << "===\n";
194       std::cout << "Top 20 most frequently executed basic blocks:\n\n";
195
196       // Print out the function frequencies...
197       std::cout <<" ##      %% \tFrequency\n";
198       unsigned BlocksToPrint = Counts.size();
199       if (BlocksToPrint > 20) BlocksToPrint = 20;
200       for (unsigned i = 0; i != BlocksToPrint; ++i) {
201         if (Counts[i].second == 0) break;
202         Function *F = Counts[i].first->getParent();
203         std::cout << std::setw(3) << i+1 << ". " 
204           << std::setw(5) << std::setprecision(2) 
205           << Counts[i].second/(double)TotalExecutions*100 << "% "
206           << std::setw(5) << Counts[i].second << "/"
207           << TotalExecutions << "\t"
208           << F->getName().c_str() << "() - "
209           << Counts[i].first->getName().c_str() << "\n";
210         FunctionsToPrint.insert(F);
211       }
212
213       BlockFreqs.insert(Counts.begin(), Counts.end());
214     }
215
216     if (PI.hasAccurateEdgeCounts()) {
217       std::vector<std::pair<ProfileInfoLoader::Edge, unsigned> > Counts;
218       PI.getEdgeCounts(Counts);
219       EdgeFreqs.insert(Counts.begin(), Counts.end());
220     }
221
222     if (PrintAnnotatedLLVM || PrintAllCode) {
223       std::cout << "\n===" << std::string(73, '-') << "===\n";
224       std::cout << "Annotated LLVM code for the module:\n\n";
225
226       ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs);
227
228       if (FunctionsToPrint.empty() || PrintAllCode)
229         M->print(std::cout, &PA);
230       else
231         // Print just a subset of the functions...
232         for (std::set<Function*>::iterator I = FunctionsToPrint.begin(),
233                E = FunctionsToPrint.end(); I != E; ++I)
234           (*I)->print(std::cout, &PA);
235     }
236
237     return 0;
238   } catch (const std::string& msg) {
239     std::cerr << argv[0] << ": " << msg << "\n";
240   } catch (...) {
241     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
242   }
243   return 1;
244 }