9669c7dfa45f332ddd85891750eba2923cc5b4e3
[oota-llvm.git] / tools / llvm-profdata / llvm-profdata.cpp
1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // llvm-profdata merges .profdata files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/SmallSet.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/ProfileData/InstrProfReader.h"
18 #include "llvm/ProfileData/InstrProfWriter.h"
19 #include "llvm/ProfileData/SampleProfReader.h"
20 #include "llvm/ProfileData/SampleProfWriter.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/PrettyStackTrace.h"
28 #include "llvm/Support/Signals.h"
29 #include "llvm/Support/raw_ostream.h"
30
31 using namespace llvm;
32
33 static void exitWithError(const Twine &Message,
34                           StringRef Whence = "",
35                           StringRef Hint = "") {
36   errs() << "error: ";
37   if (!Whence.empty())
38     errs() << Whence << ": ";
39   errs() << Message << "\n";
40   if (!Hint.empty())
41     errs() << Hint << "\n";
42   ::exit(1);
43 }
44
45 static void exitWithErrorCode(const std::error_code &Error,
46                               StringRef Whence = "") {
47   if (Error.category() == instrprof_category()) {
48     instrprof_error instrError = static_cast<instrprof_error>(Error.value());
49     if (instrError == instrprof_error::unrecognized_format) {
50       // Hint for common error of forgetting -sample for sample profiles.
51       exitWithError(Error.message(), Whence,
52                     "Perhaps you forgot to use the -sample option?");
53     }
54   }
55   exitWithError(Error.message(), Whence);
56 }
57
58 namespace {
59     enum ProfileKinds { instr, sample };
60 }
61
62 static void handleMergeWriterError(std::error_code &Error,
63                                    StringRef WhenceFile = "",
64                                    StringRef WhenceFunction = "",
65                                    bool ShowHint = true)
66 {
67   if (!WhenceFile.empty())
68     errs() << WhenceFile << ": ";
69   if (!WhenceFunction.empty())
70     errs() << WhenceFunction << ": ";
71   errs() << Error.message() << "\n";
72
73   if (ShowHint) {
74     StringRef Hint = "";
75     if (Error.category() == instrprof_category()) {
76       instrprof_error instrError = static_cast<instrprof_error>(Error.value());
77       switch (instrError) {
78       case instrprof_error::hash_mismatch:
79       case instrprof_error::count_mismatch:
80       case instrprof_error::value_site_count_mismatch:
81         Hint = "Make sure that all profile data to be merged is generated " \
82                "from the same binary.";
83         break;
84       default:
85         break;
86       }
87     }
88
89     if (!Hint.empty())
90       errs() << Hint << "\n";
91   }
92 }
93
94 static void mergeInstrProfile(const cl::list<std::string> &Inputs,
95                               StringRef OutputFilename) {
96   if (OutputFilename.compare("-") == 0)
97     exitWithError("Cannot write indexed profdata format to stdout.");
98
99   std::error_code EC;
100   raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
101   if (EC)
102     exitWithErrorCode(EC, OutputFilename);
103
104   InstrProfWriter Writer;
105   SmallSet<std::error_code, 4> WriterErrorCodes;
106   for (const auto &Filename : Inputs) {
107     auto ReaderOrErr = InstrProfReader::create(Filename);
108     if (std::error_code ec = ReaderOrErr.getError())
109       exitWithErrorCode(ec, Filename);
110
111     auto Reader = std::move(ReaderOrErr.get());
112     for (auto &I : *Reader) {
113       if (std::error_code EC = Writer.addRecord(std::move(I))) {
114         // Only show hint the first time an error occurs.
115         bool firstTime = WriterErrorCodes.insert(EC).second;
116         handleMergeWriterError(EC, Filename, I.Name, firstTime);
117       }
118     }
119     if (Reader->hasError())
120       exitWithErrorCode(Reader->getError(), Filename);
121   }
122   Writer.write(Output);
123 }
124
125 static void mergeSampleProfile(const cl::list<std::string> &Inputs,
126                                StringRef OutputFilename,
127                                sampleprof::SampleProfileFormat OutputFormat) {
128   using namespace sampleprof;
129   auto WriterOrErr = SampleProfileWriter::create(OutputFilename, OutputFormat);
130   if (std::error_code EC = WriterOrErr.getError())
131     exitWithErrorCode(EC, OutputFilename);
132
133   auto Writer = std::move(WriterOrErr.get());
134   StringMap<FunctionSamples> ProfileMap;
135   SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
136   for (const auto &Filename : Inputs) {
137     auto ReaderOrErr =
138         SampleProfileReader::create(Filename, getGlobalContext());
139     if (std::error_code EC = ReaderOrErr.getError())
140       exitWithErrorCode(EC, Filename);
141
142     // We need to keep the readers around until after all the files are
143     // read so that we do not lose the function names stored in each
144     // reader's memory. The function names are needed to write out the
145     // merged profile map.
146     Readers.push_back(std::move(ReaderOrErr.get()));
147     const auto Reader = Readers.back().get();
148     if (std::error_code EC = Reader->read())
149       exitWithErrorCode(EC, Filename);
150
151     StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
152     for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
153                                               E = Profiles.end();
154          I != E; ++I) {
155       StringRef FName = I->first();
156       FunctionSamples &Samples = I->second;
157       ProfileMap[FName].merge(Samples);
158     }
159   }
160   Writer->write(ProfileMap);
161 }
162
163 static int merge_main(int argc, const char *argv[]) {
164   cl::list<std::string> Inputs(cl::Positional, cl::Required, cl::OneOrMore,
165                                cl::desc("<filenames...>"));
166
167   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
168                                       cl::init("-"), cl::Required,
169                                       cl::desc("Output file"));
170   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
171                             cl::aliasopt(OutputFilename));
172   cl::opt<ProfileKinds> ProfileKind(
173       cl::desc("Profile kind:"), cl::init(instr),
174       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
175                  clEnumVal(sample, "Sample profile"), clEnumValEnd));
176
177   cl::opt<sampleprof::SampleProfileFormat> OutputFormat(
178       cl::desc("Format of output profile (only meaningful with --sample)"),
179       cl::init(sampleprof::SPF_Binary),
180       cl::values(clEnumValN(sampleprof::SPF_Binary, "binary",
181                             "Binary encoding (default)"),
182                  clEnumValN(sampleprof::SPF_Text, "text", "Text encoding"),
183                  clEnumValN(sampleprof::SPF_GCC, "gcc", "GCC encoding"),
184                  clEnumValEnd));
185
186   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
187
188   if (ProfileKind == instr)
189     mergeInstrProfile(Inputs, OutputFilename);
190   else
191     mergeSampleProfile(Inputs, OutputFilename, OutputFormat);
192
193   return 0;
194 }
195
196 static int showInstrProfile(std::string Filename, bool ShowCounts,
197                             bool ShowIndirectCallTargets, bool ShowAllFunctions,
198                             std::string ShowFunction, raw_fd_ostream &OS) {
199   auto ReaderOrErr = InstrProfReader::create(Filename);
200   if (std::error_code EC = ReaderOrErr.getError())
201     exitWithErrorCode(EC, Filename);
202
203   auto Reader = std::move(ReaderOrErr.get());
204   uint64_t MaxFunctionCount = 0, MaxBlockCount = 0;
205   size_t ShownFunctions = 0, TotalFunctions = 0;
206   for (const auto &Func : *Reader) {
207     bool Show =
208         ShowAllFunctions || (!ShowFunction.empty() &&
209                              Func.Name.find(ShowFunction) != Func.Name.npos);
210
211     ++TotalFunctions;
212     assert(Func.Counts.size() > 0 && "function missing entry counter");
213     if (Func.Counts[0] > MaxFunctionCount)
214       MaxFunctionCount = Func.Counts[0];
215
216     if (Show) {
217       if (!ShownFunctions)
218         OS << "Counters:\n";
219       ++ShownFunctions;
220
221       OS << "  " << Func.Name << ":\n"
222          << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
223          << "    Counters: " << Func.Counts.size() << "\n"
224          << "    Function count: " << Func.Counts[0] << "\n";
225       if (ShowIndirectCallTargets)
226         OS << "    Indirect Call Site Count: "
227            << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
228     }
229
230     if (Show && ShowCounts)
231       OS << "    Block counts: [";
232     for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) {
233       if (Func.Counts[I] > MaxBlockCount)
234         MaxBlockCount = Func.Counts[I];
235       if (Show && ShowCounts)
236         OS << (I == 1 ? "" : ", ") << Func.Counts[I];
237     }
238     if (Show && ShowCounts)
239       OS << "]\n";
240
241     if (Show && ShowIndirectCallTargets) {
242       uint32_t NS = Func.getNumValueSites(IPVK_IndirectCallTarget);
243       OS << "    Indirect Target Results: \n";
244       for (size_t I = 0; I < NS; ++I) {
245         uint32_t NV = Func.getNumValueDataForSite(IPVK_IndirectCallTarget, I);
246         std::unique_ptr<InstrProfValueData[]> VD =
247             Func.getValueForSite(IPVK_IndirectCallTarget, I);
248         for (uint32_t V = 0; V < NV; V++) {
249           OS << "\t[ " << I << ", ";
250           OS << (const char *)VD[V].Value << ", " << VD[V].Count << " ]\n";
251         }
252       }
253     }
254   }
255   if (Reader->hasError())
256     exitWithErrorCode(Reader->getError(), Filename);
257
258   if (ShowAllFunctions || !ShowFunction.empty())
259     OS << "Functions shown: " << ShownFunctions << "\n";
260   OS << "Total functions: " << TotalFunctions << "\n";
261   OS << "Maximum function count: " << MaxFunctionCount << "\n";
262   OS << "Maximum internal block count: " << MaxBlockCount << "\n";
263   return 0;
264 }
265
266 static int showSampleProfile(std::string Filename, bool ShowCounts,
267                              bool ShowAllFunctions, std::string ShowFunction,
268                              raw_fd_ostream &OS) {
269   using namespace sampleprof;
270   auto ReaderOrErr = SampleProfileReader::create(Filename, getGlobalContext());
271   if (std::error_code EC = ReaderOrErr.getError())
272     exitWithErrorCode(EC, Filename);
273
274   auto Reader = std::move(ReaderOrErr.get());
275   if (std::error_code EC = Reader->read())
276     exitWithErrorCode(EC, Filename);
277
278   if (ShowAllFunctions || ShowFunction.empty())
279     Reader->dump(OS);
280   else
281     Reader->dumpFunctionProfile(ShowFunction, OS);
282
283   return 0;
284 }
285
286 static int show_main(int argc, const char *argv[]) {
287   cl::opt<std::string> Filename(cl::Positional, cl::Required,
288                                 cl::desc("<profdata-file>"));
289
290   cl::opt<bool> ShowCounts("counts", cl::init(false),
291                            cl::desc("Show counter values for shown functions"));
292   cl::opt<bool> ShowIndirectCallTargets(
293       "ic-targets", cl::init(false),
294       cl::desc("Show indirect call site target values for shown functions"));
295   cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
296                                  cl::desc("Details for every function"));
297   cl::opt<std::string> ShowFunction("function",
298                                     cl::desc("Details for matching functions"));
299
300   cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
301                                       cl::init("-"), cl::desc("Output file"));
302   cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
303                             cl::aliasopt(OutputFilename));
304   cl::opt<ProfileKinds> ProfileKind(
305       cl::desc("Profile kind:"), cl::init(instr),
306       cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
307                  clEnumVal(sample, "Sample profile"), clEnumValEnd));
308
309   cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
310
311   if (OutputFilename.empty())
312     OutputFilename = "-";
313
314   std::error_code EC;
315   raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
316   if (EC)
317       exitWithErrorCode(EC, OutputFilename);
318
319   if (ShowAllFunctions && !ShowFunction.empty())
320     errs() << "warning: -function argument ignored: showing all functions\n";
321
322   if (ProfileKind == instr)
323     return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
324                             ShowAllFunctions, ShowFunction, OS);
325   else
326     return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
327                              ShowFunction, OS);
328 }
329
330 int main(int argc, const char *argv[]) {
331   // Print a stack trace if we signal out.
332   sys::PrintStackTraceOnErrorSignal();
333   PrettyStackTraceProgram X(argc, argv);
334   llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
335
336   StringRef ProgName(sys::path::filename(argv[0]));
337   if (argc > 1) {
338     int (*func)(int, const char *[]) = nullptr;
339
340     if (strcmp(argv[1], "merge") == 0)
341       func = merge_main;
342     else if (strcmp(argv[1], "show") == 0)
343       func = show_main;
344
345     if (func) {
346       std::string Invocation(ProgName.str() + " " + argv[1]);
347       argv[1] = Invocation.c_str();
348       return func(argc - 1, argv + 1);
349     }
350
351     if (strcmp(argv[1], "-h") == 0 ||
352         strcmp(argv[1], "-help") == 0 ||
353         strcmp(argv[1], "--help") == 0) {
354
355       errs() << "OVERVIEW: LLVM profile data tools\n\n"
356              << "USAGE: " << ProgName << " <command> [args...]\n"
357              << "USAGE: " << ProgName << " <command> -help\n\n"
358              << "Available commands: merge, show\n";
359       return 0;
360     }
361   }
362
363   if (argc < 2)
364     errs() << ProgName << ": No command specified!\n";
365   else
366     errs() << ProgName << ": Unknown command!\n";
367
368   errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
369   return 1;
370 }