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