General cleanup:
[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/System/Signals.h"
23 #include <iostream>
24 #include <iomanip>
25 #include <map>
26 #include <set>
27
28 using namespace llvm;
29 using namespace std;
30
31 namespace {
32   cl::opt<string>
33   BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"),
34                cl::Required);
35
36   cl::opt<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 binary_function<pair<T, unsigned>,
54                                 pair<T, unsigned>, bool> {
55   bool operator()(const pair<T, unsigned> &LHS,
56                   const pair<T, unsigned> &RHS) const {
57     return LHS.second > RHS.second;
58   }
59 };
60
61 namespace {
62   class ProfileAnnotator : public AssemblyAnnotationWriter {
63     map<const Function  *, unsigned> &FuncFreqs;
64     map<const BasicBlock*, unsigned> &BlockFreqs;
65     map<ProfileInfoLoader::Edge, unsigned> &EdgeFreqs;
66   public:
67     ProfileAnnotator(map<const Function  *, unsigned> &FF,
68                      map<const BasicBlock*, unsigned> &BF,
69                      map<ProfileInfoLoader::Edge, unsigned> &EF)
70       : FuncFreqs(FF), BlockFreqs(BF), EdgeFreqs(EF) {}
71
72     virtual void emitFunctionAnnot(const Function *F, ostream &OS) {
73       OS << ";;; %" << F->getName() << " called " << FuncFreqs[F]
74          << " times.\n;;;\n";
75     }
76     virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
77                                           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, ostream &OS){
86       if (EdgeFreqs.empty()) return;
87
88       // Figure out how many times each successor executed.
89       vector<pair<const BasicBlock*, unsigned> > SuccCounts;
90       const TerminatorInst *TI = BB->getTerminator();
91
92       map<ProfileInfoLoader::Edge, unsigned>::iterator I =
93         EdgeFreqs.lower_bound(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(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   try {
112     cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n");
113     sys::PrintStackTraceOnErrorSignal();
114
115     // Read in the bytecode file...
116     string ErrorMessage;
117     Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage);
118     if (M == 0) {
119       cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage << "\n";
120       return 1;
121     }
122
123     // Read the profiling information
124     ProfileInfoLoader PI(argv[0], ProfileDataFile, *M);
125
126     map<const Function  *, unsigned> FuncFreqs;
127     map<const BasicBlock*, unsigned> BlockFreqs;
128     map<ProfileInfoLoader::Edge, unsigned> EdgeFreqs;
129
130     // Output a report. Eventually, there will be multiple reports selectable on
131     // the command line, for now, just keep things simple.
132
133     // Emit the most frequent function table...
134     vector<pair<Function*, unsigned> > FunctionCounts;
135     PI.getFunctionCounts(FunctionCounts);
136     FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end());
137
138     // Sort by the frequency, backwards.
139     sort(FunctionCounts.begin(), FunctionCounts.end(),
140               PairSecondSortReverse<Function*>());
141
142     unsigned long long TotalExecutions = 0;
143     for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
144       TotalExecutions += FunctionCounts[i].second;
145
146     cout << "===" << string(73, '-') << "===\n"
147               << "LLVM profiling output for execution";
148     if (PI.getNumExecutions() != 1) cout << "s";
149     cout << ":\n";
150
151     for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) {
152       cout << "  ";
153       if (e != 1) cout << i+1 << ". ";
154       cout << PI.getExecution(i) << "\n";
155     }
156
157     cout << "\n===" << string(73, '-') << "===\n";
158     cout << "Function execution frequencies:\n\n";
159
160     // Print out the function frequencies...
161     cout << " ##   Frequency\n";
162     for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
163       if (FunctionCounts[i].second == 0) {
164         cout << "\n  NOTE: " << e-i << " function" <<
165                (e-i-1 ? "s were" : " was") << " never executed!\n";
166         break;
167       }
168
169       cout << setw(3) << i+1 << ". " 
170         << setw(5) << FunctionCounts[i].second << "/"
171         << TotalExecutions << " "
172         << FunctionCounts[i].first->getName().c_str() << "\n";
173     }
174
175     set<Function*> FunctionsToPrint;
176
177     // If we have block count information, print out the LLVM module with
178     // frequency annotations.
179     if (PI.hasAccurateBlockCounts()) {
180       vector<pair<BasicBlock*, unsigned> > Counts;
181       PI.getBlockCounts(Counts);
182
183       TotalExecutions = 0;
184       for (unsigned i = 0, e = Counts.size(); i != e; ++i)
185         TotalExecutions += Counts[i].second;
186
187       // Sort by the frequency, backwards.
188       sort(Counts.begin(), Counts.end(),
189                 PairSecondSortReverse<BasicBlock*>());
190
191       cout << "\n===" << string(73, '-') << "===\n";
192       cout << "Top 20 most frequently executed basic blocks:\n\n";
193
194       // Print out the function frequencies...
195       cout <<" ##      %% \tFrequency\n";
196       unsigned BlocksToPrint = Counts.size();
197       if (BlocksToPrint > 20) BlocksToPrint = 20;
198       for (unsigned i = 0; i != BlocksToPrint; ++i) {
199         if (Counts[i].second == 0) break;
200         Function *F = Counts[i].first->getParent();
201         cout << setw(3) << i+1 << ". " 
202           << setw(5) << setprecision(2) 
203           << Counts[i].second/(double)TotalExecutions*100 << "% "
204           << setw(5) << Counts[i].second << "/"
205           << TotalExecutions << "\t"
206           << F->getName().c_str() << "() - "
207           << Counts[i].first->getName().c_str() << "\n";
208         FunctionsToPrint.insert(F);
209       }
210
211       BlockFreqs.insert(Counts.begin(), Counts.end());
212     }
213
214     if (PI.hasAccurateEdgeCounts()) {
215       vector<pair<ProfileInfoLoader::Edge, unsigned> > Counts;
216       PI.getEdgeCounts(Counts);
217       EdgeFreqs.insert(Counts.begin(), Counts.end());
218     }
219
220     if (PrintAnnotatedLLVM || PrintAllCode) {
221       cout << "\n===" << string(73, '-') << "===\n";
222       cout << "Annotated LLVM code for the module:\n\n";
223
224       ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs);
225
226       if (FunctionsToPrint.empty() || PrintAllCode)
227         M->print(cout, &PA);
228       else
229         // Print just a subset of the functions...
230         for (set<Function*>::iterator I = FunctionsToPrint.begin(),
231                E = FunctionsToPrint.end(); I != E; ++I)
232           (*I)->print(cout, &PA);
233     }
234
235     return 0;
236   } catch (const string& msg) {
237     cerr << argv[0] << ": " << msg << "\n";
238   } catch (...) {
239     cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
240   }
241   return 1;
242 }