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/AsmAnnotationWriter.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/ManagedStatic.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Signals.h"
41 BitcodeFile(cl::Positional, cl::desc("<program bitcode file>"),
45 ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
46 cl::Optional, cl::init("llvmprof.out"));
49 PrintAnnotatedLLVM("annotated-llvm",
50 cl::desc("Print LLVM code with frequency annotations"));
51 cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"),
52 cl::aliasopt(PrintAnnotatedLLVM));
54 PrintAllCode("print-all-code",
55 cl::desc("Print annotated code for the entire program"));
58 // PairSecondSort - A sorting predicate to sort by the second element of a pair.
60 struct PairSecondSortReverse
61 : public std::binary_function<std::pair<T, unsigned>,
62 std::pair<T, unsigned>, bool> {
63 bool operator()(const std::pair<T, unsigned> &LHS,
64 const std::pair<T, unsigned> &RHS) const {
65 return LHS.second > RHS.second;
70 class ProfileAnnotator : public AssemblyAnnotationWriter {
73 ProfileAnnotator(ProfileInfo& pi) : PI(pi) {}
75 virtual void emitFunctionAnnot(const Function *F, raw_ostream &OS) {
76 OS << ";;; %" << F->getName() << " called " << PI.getExecutionCount(F)
79 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
81 unsigned w = PI.getExecutionCount(BB);
83 OS << "\t;;; Basic block executed " << w << " times.\n";
85 OS << "\t;;; Never executed!\n";
88 virtual void emitBasicBlockEndAnnot(const BasicBlock *BB, raw_ostream &OS) {
89 // Figure out how many times each successor executed.
90 std::vector<std::pair<ProfileInfo::Edge, unsigned> > SuccCounts;
92 const TerminatorInst *TI = BB->getTerminator();
93 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {
94 BasicBlock* Succ = TI->getSuccessor(s);
95 SuccCounts.push_back(std::make_pair(std::make_pair(BB,Succ),
96 PI.getEdgeWeight(BB,Succ)));
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.second->getName() << "]";
110 /// ProfileInfoPrinterPass - Helper pass to dump the profile information for
113 // FIXME: This should move elsewhere.
114 class ProfileInfoPrinterPass : public ModulePass {
115 ProfileInfoLoader &PIL;
117 static char ID; // Class identification, replacement for typeinfo.
118 explicit ProfileInfoPrinterPass(ProfileInfoLoader &_PIL)
119 : ModulePass(&ID), PIL(_PIL) {}
121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
122 AU.setPreservesAll();
123 AU.addRequired<ProfileInfo>();
126 bool runOnModule(Module &M);
130 char ProfileInfoPrinterPass::ID = 0;
132 bool ProfileInfoPrinterPass::runOnModule(Module &M) {
133 ProfileInfo &PI = getAnalysis<ProfileInfo>();
134 std::map<const Function *, unsigned> FuncFreqs;
135 std::map<const BasicBlock*, unsigned> BlockFreqs;
136 std::map<ProfileInfo::Edge, unsigned> EdgeFreqs;
138 // Output a report. Eventually, there will be multiple reports selectable on
139 // the command line, for now, just keep things simple.
141 // Emit the most frequent function table...
142 std::vector<std::pair<Function*, unsigned> > FunctionCounts;
143 std::vector<std::pair<BasicBlock*, unsigned> > Counts;
144 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
145 if (FI->isDeclaration()) continue;
146 FunctionCounts.push_back(std::make_pair(FI,PI.getExecutionCount(FI)));
147 for (Function::iterator BB = FI->begin(), BBE = FI->end();
149 Counts.push_back(std::make_pair(BB,PI.getExecutionCount(BB)));
153 // Sort by the frequency, backwards.
154 sort(FunctionCounts.begin(), FunctionCounts.end(),
155 PairSecondSortReverse<Function*>());
157 uint64_t TotalExecutions = 0;
158 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
159 TotalExecutions += FunctionCounts[i].second;
161 std::cout << "===" << std::string(73, '-') << "===\n"
162 << "LLVM profiling output for execution";
163 if (PIL.getNumExecutions() != 1) std::cout << "s";
166 for (unsigned i = 0, e = PIL.getNumExecutions(); i != e; ++i) {
168 if (e != 1) std::cout << i+1 << ". ";
169 std::cout << PIL.getExecution(i) << "\n";
172 std::cout << "\n===" << std::string(73, '-') << "===\n";
173 std::cout << "Function execution frequencies:\n\n";
175 // Print out the function frequencies...
176 std::cout << " ## Frequency\n";
177 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
178 if (FunctionCounts[i].second == 0) {
179 std::cout << "\n NOTE: " << e-i << " function" <<
180 (e-i-1 ? "s were" : " was") << " never executed!\n";
184 std::cout << std::setw(3) << i+1 << ". "
185 << std::setw(5) << FunctionCounts[i].second << "/"
186 << TotalExecutions << " "
187 << FunctionCounts[i].first->getNameStr() << "\n";
190 std::set<Function*> FunctionsToPrint;
193 for (unsigned i = 0, e = Counts.size(); i != e; ++i)
194 TotalExecutions += Counts[i].second;
196 // Sort by the frequency, backwards.
197 sort(Counts.begin(), Counts.end(),
198 PairSecondSortReverse<BasicBlock*>());
200 std::cout << "\n===" << std::string(73, '-') << "===\n";
201 std::cout << "Top 20 most frequently executed basic blocks:\n\n";
203 // Print out the function frequencies...
204 std::cout <<" ## %% \tFrequency\n";
205 unsigned BlocksToPrint = Counts.size();
206 if (BlocksToPrint > 20) BlocksToPrint = 20;
207 for (unsigned i = 0; i != BlocksToPrint; ++i) {
208 if (Counts[i].second == 0) break;
209 Function *F = Counts[i].first->getParent();
210 std::cout << std::setw(3) << i+1 << ". "
211 << std::setw(5) << std::setprecision(3)
212 << Counts[i].second/(double)TotalExecutions*100 << "% "
213 << std::setw(5) << Counts[i].second << "/"
214 << TotalExecutions << "\t"
215 << F->getNameStr() << "() - "
216 << Counts[i].first->getNameStr() << "\n";
217 FunctionsToPrint.insert(F);
220 if (PrintAnnotatedLLVM || PrintAllCode) {
221 std::cout << "\n===" << std::string(73, '-') << "===\n";
222 std::cout << "Annotated LLVM code for the module:\n\n";
224 ProfileAnnotator PA(PI);
226 if (FunctionsToPrint.empty() || PrintAllCode)
227 M.print(std::cout, &PA);
229 // Print just a subset of the functions.
230 for (std::set<Function*>::iterator I = FunctionsToPrint.begin(),
231 E = FunctionsToPrint.end(); I != E; ++I)
232 (*I)->print(std::cout, &PA);
238 int main(int argc, char **argv) {
239 // Print a stack trace if we signal out.
240 sys::PrintStackTraceOnErrorSignal();
241 PrettyStackTraceProgram X(argc, argv);
243 LLVMContext &Context = getGlobalContext();
244 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
246 cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");
248 // Read in the bitcode file...
249 std::string ErrorMessage;
251 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile,
253 M = ParseBitcodeFile(Buffer, Context, &ErrorMessage);
257 errs() << argv[0] << ": " << BitcodeFile << ": "
258 << ErrorMessage << "\n";
262 // Read the profiling information. This is redundant since we load it again
263 // using the standard profile info provider pass, but for now this gives us
264 // access to additional information not exposed via the ProfileInfo
266 ProfileInfoLoader PIL(argv[0], ProfileDataFile, *M);
268 // Run the printer pass.
270 PassMgr.add(createProfileLoaderPass(ProfileDataFile));
271 PassMgr.add(new ProfileInfoPrinterPass(PIL));
275 } catch (const std::string& msg) {
276 errs() << argv[0] << ": " << msg << "\n";
278 errs() << argv[0] << ": Unexpected unknown exception occurred.\n";