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