1 //===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/InstrTypes.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
21 #include "llvm/Analysis/ProfileInfo.h"
22 #include "llvm/Analysis/ProfileInfoLoader.h"
23 #include "llvm/Analysis/Passes.h"
24 #include "llvm/Bitcode/ReaderWriter.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/FormattedStream.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/System/Signals.h"
42 BitcodeFile(cl::Positional, cl::desc("<program bitcode file>"),
46 ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
47 cl::Optional, cl::init("llvmprof.out"));
50 PrintAnnotatedLLVM("annotated-llvm",
51 cl::desc("Print LLVM code with frequency annotations"));
52 cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"),
53 cl::aliasopt(PrintAnnotatedLLVM));
55 PrintAllCode("print-all-code",
56 cl::desc("Print annotated code for the entire program"));
59 // PairSecondSort - A sorting predicate to sort by the second element of a pair.
61 struct PairSecondSortReverse
62 : public std::binary_function<std::pair<T, double>,
63 std::pair<T, double>, bool> {
64 bool operator()(const std::pair<T, double> &LHS,
65 const std::pair<T, double> &RHS) const {
66 return LHS.second > RHS.second;
70 static double ignoreMissing(double w) {
71 if (w == ProfileInfo::MissingValue) return 0;
76 class ProfileAnnotator : public AssemblyAnnotationWriter {
79 ProfileAnnotator(ProfileInfo &pi) : PI(pi) {}
81 virtual void emitFunctionAnnot(const Function *F,
82 formatted_raw_ostream &OS) {
83 double w = PI.getExecutionCount(F);
84 if (w != ProfileInfo::MissingValue) {
85 OS << ";;; %" << F->getName() << " called "<<(unsigned)w
89 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
90 formatted_raw_ostream &OS) {
91 double w = PI.getExecutionCount(BB);
92 if (w != ProfileInfo::MissingValue) {
94 OS << "\t;;; Basic block executed " << (unsigned)w << " times.\n";
96 OS << "\t;;; Never executed!\n";
101 virtual void emitBasicBlockEndAnnot(const BasicBlock *BB,
102 formatted_raw_ostream &OS) {
103 // Figure out how many times each successor executed.
104 std::vector<std::pair<ProfileInfo::Edge, double> > SuccCounts;
106 const TerminatorInst *TI = BB->getTerminator();
107 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
108 BasicBlock* Succ = TI->getSuccessor(s);
109 double w = ignoreMissing(PI.getEdgeWeight(std::make_pair(BB, Succ)));
111 SuccCounts.push_back(std::make_pair(std::make_pair(BB, Succ), w));
113 if (!SuccCounts.empty()) {
114 OS << "\t;;; Out-edge counts:";
115 for (unsigned i = 0, e = SuccCounts.size(); i != e; ++i)
116 OS << " [" << (SuccCounts[i]).second << " -> "
117 << (SuccCounts[i]).first.second->getName() << "]";
125 /// ProfileInfoPrinterPass - Helper pass to dump the profile information for
128 // FIXME: This should move elsewhere.
129 class ProfileInfoPrinterPass : public ModulePass {
130 ProfileInfoLoader &PIL;
132 static char ID; // Class identification, replacement for typeinfo.
133 explicit ProfileInfoPrinterPass(ProfileInfoLoader &_PIL)
134 : ModulePass(ID), PIL(_PIL) {}
136 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
137 AU.setPreservesAll();
138 AU.addRequired<ProfileInfo>();
141 bool runOnModule(Module &M);
145 char ProfileInfoPrinterPass::ID = 0;
147 bool ProfileInfoPrinterPass::runOnModule(Module &M) {
148 ProfileInfo &PI = getAnalysis<ProfileInfo>();
149 std::map<const Function *, unsigned> FuncFreqs;
150 std::map<const BasicBlock*, unsigned> BlockFreqs;
151 std::map<ProfileInfo::Edge, unsigned> EdgeFreqs;
153 // Output a report. Eventually, there will be multiple reports selectable on
154 // the command line, for now, just keep things simple.
156 // Emit the most frequent function table...
157 std::vector<std::pair<Function*, double> > FunctionCounts;
158 std::vector<std::pair<BasicBlock*, double> > Counts;
159 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
160 if (FI->isDeclaration()) continue;
161 double w = ignoreMissing(PI.getExecutionCount(FI));
162 FunctionCounts.push_back(std::make_pair(FI, w));
163 for (Function::iterator BB = FI->begin(), BBE = FI->end();
165 double w = ignoreMissing(PI.getExecutionCount(BB));
166 Counts.push_back(std::make_pair(BB, w));
170 // Sort by the frequency, backwards.
171 sort(FunctionCounts.begin(), FunctionCounts.end(),
172 PairSecondSortReverse<Function*>());
174 double TotalExecutions = 0;
175 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
176 TotalExecutions += FunctionCounts[i].second;
178 outs() << "===" << std::string(73, '-') << "===\n"
179 << "LLVM profiling output for execution";
180 if (PIL.getNumExecutions() != 1) outs() << "s";
183 for (unsigned i = 0, e = PIL.getNumExecutions(); i != e; ++i) {
185 if (e != 1) outs() << i+1 << ". ";
186 outs() << PIL.getExecution(i) << "\n";
189 outs() << "\n===" << std::string(73, '-') << "===\n";
190 outs() << "Function execution frequencies:\n\n";
192 // Print out the function frequencies...
193 outs() << " ## Frequency\n";
194 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
195 if (FunctionCounts[i].second == 0) {
196 outs() << "\n NOTE: " << e-i << " function"
197 << (e-i-1 ? "s were" : " was") << " never executed!\n";
201 outs() << format("%3d", i+1) << ". "
202 << format("%5.2g", FunctionCounts[i].second) << "/"
203 << format("%g", TotalExecutions) << " "
204 << FunctionCounts[i].first->getNameStr() << "\n";
207 std::set<Function*> FunctionsToPrint;
210 for (unsigned i = 0, e = Counts.size(); i != e; ++i)
211 TotalExecutions += Counts[i].second;
213 // Sort by the frequency, backwards.
214 sort(Counts.begin(), Counts.end(),
215 PairSecondSortReverse<BasicBlock*>());
217 outs() << "\n===" << std::string(73, '-') << "===\n";
218 outs() << "Top 20 most frequently executed basic blocks:\n\n";
220 // Print out the function frequencies...
221 outs() <<" ## %% \tFrequency\n";
222 unsigned BlocksToPrint = Counts.size();
223 if (BlocksToPrint > 20) BlocksToPrint = 20;
224 for (unsigned i = 0; i != BlocksToPrint; ++i) {
225 if (Counts[i].second == 0) break;
226 Function *F = Counts[i].first->getParent();
227 outs() << format("%3d", i+1) << ". "
228 << format("%5g", Counts[i].second/(double)TotalExecutions*100) << "% "
229 << format("%5.0f", Counts[i].second) << "/"
230 << format("%g", TotalExecutions) << "\t"
231 << F->getNameStr() << "() - "
232 << Counts[i].first->getNameStr() << "\n";
233 FunctionsToPrint.insert(F);
236 if (PrintAnnotatedLLVM || PrintAllCode) {
237 outs() << "\n===" << std::string(73, '-') << "===\n";
238 outs() << "Annotated LLVM code for the module:\n\n";
240 ProfileAnnotator PA(PI);
242 if (FunctionsToPrint.empty() || PrintAllCode)
243 M.print(outs(), &PA);
245 // Print just a subset of the functions.
246 for (std::set<Function*>::iterator I = FunctionsToPrint.begin(),
247 E = FunctionsToPrint.end(); I != E; ++I)
248 (*I)->print(outs(), &PA);
254 int main(int argc, char **argv) {
255 // Print a stack trace if we signal out.
256 sys::PrintStackTraceOnErrorSignal();
257 PrettyStackTraceProgram X(argc, argv);
259 LLVMContext &Context = getGlobalContext();
260 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
262 cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");
264 // Read in the bitcode file...
265 std::string ErrorMessage;
267 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile,
269 M = ParseBitcodeFile(Buffer, Context, &ErrorMessage);
273 errs() << argv[0] << ": " << BitcodeFile << ": "
274 << ErrorMessage << "\n";
278 // Read the profiling information. This is redundant since we load it again
279 // using the standard profile info provider pass, but for now this gives us
280 // access to additional information not exposed via the ProfileInfo
282 ProfileInfoLoader PIL(argv[0], ProfileDataFile, *M);
284 // Run the printer pass.
286 PassMgr.add(createProfileLoaderPass(ProfileDataFile));
287 PassMgr.add(new ProfileInfoPrinterPass(PIL));