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