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/StringRef.h"
15#include "llvm/IR/LLVMContext.h"
16#include "llvm/ProfileData/InstrProfReader.h"
17#include "llvm/ProfileData/InstrProfWriter.h"
18#include "llvm/ProfileData/SampleProfReader.h"
19#include "llvm/ProfileData/SampleProfWriter.h"
20#include "llvm/Support/CommandLine.h"
21#include "llvm/Support/FileSystem.h"
22#include "llvm/Support/Format.h"
23#include "llvm/Support/ManagedStatic.h"
24#include "llvm/Support/MemoryBuffer.h"
25#include "llvm/Support/Path.h"
26#include "llvm/Support/PrettyStackTrace.h"
27#include "llvm/Support/Signals.h"
28#include "llvm/Support/raw_ostream.h"
29
30using namespace llvm;
31
32static void exitWithError(const Twine &Message, StringRef Whence = "") {
33  errs() << "error: ";
34  if (!Whence.empty())
35    errs() << Whence << ": ";
36  errs() << Message << "\n";
37  ::exit(1);
38}
39
40enum ProfileKinds { instr, sample };
41
42static void mergeInstrProfile(const cl::list<std::string> &Inputs,
43                              StringRef OutputFilename) {
44  if (OutputFilename.compare("-") == 0)
45    exitWithError("Cannot write indexed profdata format to stdout.");
46
47  std::error_code EC;
48  raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
49  if (EC)
50    exitWithError(EC.message(), OutputFilename);
51
52  InstrProfWriter Writer;
53  for (const auto &Filename : Inputs) {
54    auto ReaderOrErr = InstrProfReader::create(Filename);
55    if (std::error_code ec = ReaderOrErr.getError())
56      exitWithError(ec.message(), Filename);
57
58    auto Reader = std::move(ReaderOrErr.get());
59    for (const auto &I : *Reader)
60      if (std::error_code EC =
61              Writer.addFunctionCounts(I.Name, I.Hash, I.Counts))
62        errs() << Filename << ": " << I.Name << ": " << EC.message() << "\n";
63    if (Reader->hasError())
64      exitWithError(Reader->getError().message(), Filename);
65  }
66  Writer.write(Output);
67}
68
69static void mergeSampleProfile(const cl::list<std::string> &Inputs,
70                               StringRef OutputFilename,
71                               sampleprof::SampleProfileFormat OutputFormat) {
72  using namespace sampleprof;
73  auto WriterOrErr = SampleProfileWriter::create(OutputFilename, OutputFormat);
74  if (std::error_code EC = WriterOrErr.getError())
75    exitWithError(EC.message(), OutputFilename);
76
77  auto Writer = std::move(WriterOrErr.get());
78  StringMap<FunctionSamples> ProfileMap;
79  for (const auto &Filename : Inputs) {
80    auto ReaderOrErr =
81        SampleProfileReader::create(Filename, getGlobalContext());
82    if (std::error_code EC = ReaderOrErr.getError())
83      exitWithError(EC.message(), Filename);
84
85    auto Reader = std::move(ReaderOrErr.get());
86    if (std::error_code EC = Reader->read())
87      exitWithError(EC.message(), Filename);
88
89    StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
90    for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
91                                              E = Profiles.end();
92         I != E; ++I) {
93      StringRef FName = I->first();
94      FunctionSamples &Samples = I->second;
95      ProfileMap[FName].merge(Samples);
96    }
97  }
98  Writer->write(ProfileMap);
99}
100
101static int merge_main(int argc, const char *argv[]) {
102  cl::list<std::string> Inputs(cl::Positional, cl::Required, cl::OneOrMore,
103                               cl::desc("<filenames...>"));
104
105  cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
106                                      cl::init("-"), cl::Required,
107                                      cl::desc("Output file"));
108  cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
109                            cl::aliasopt(OutputFilename));
110  cl::opt<ProfileKinds> ProfileKind(
111      cl::desc("Profile kind:"), cl::init(instr),
112      cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
113                 clEnumVal(sample, "Sample profile"), clEnumValEnd));
114
115  cl::opt<sampleprof::SampleProfileFormat> OutputFormat(
116      cl::desc("Format of output profile (only meaningful with --sample)"),
117      cl::init(sampleprof::SPF_Binary),
118      cl::values(clEnumValN(sampleprof::SPF_Binary, "binary",
119                            "Binary encoding (default)"),
120                 clEnumValN(sampleprof::SPF_Text, "text", "Text encoding"),
121                 clEnumValN(sampleprof::SPF_GCC, "gcc", "GCC encoding"),
122                 clEnumValEnd));
123
124  cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
125
126  if (ProfileKind == instr)
127    mergeInstrProfile(Inputs, OutputFilename);
128  else
129    mergeSampleProfile(Inputs, OutputFilename, OutputFormat);
130
131  return 0;
132}
133
134static int showInstrProfile(std::string Filename, bool ShowCounts,
135                            bool ShowAllFunctions, std::string ShowFunction,
136                            raw_fd_ostream &OS) {
137  auto ReaderOrErr = InstrProfReader::create(Filename);
138  if (std::error_code EC = ReaderOrErr.getError())
139    exitWithError(EC.message(), Filename);
140
141  auto Reader = std::move(ReaderOrErr.get());
142  uint64_t MaxFunctionCount = 0, MaxBlockCount = 0;
143  size_t ShownFunctions = 0, TotalFunctions = 0;
144  for (const auto &Func : *Reader) {
145    bool Show =
146        ShowAllFunctions || (!ShowFunction.empty() &&
147                             Func.Name.find(ShowFunction) != Func.Name.npos);
148
149    ++TotalFunctions;
150    assert(Func.Counts.size() > 0 && "function missing entry counter");
151    if (Func.Counts[0] > MaxFunctionCount)
152      MaxFunctionCount = Func.Counts[0];
153
154    if (Show) {
155      if (!ShownFunctions)
156        OS << "Counters:\n";
157      ++ShownFunctions;
158
159      OS << "  " << Func.Name << ":\n"
160         << "    Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
161         << "    Counters: " << Func.Counts.size() << "\n"
162         << "    Function count: " << Func.Counts[0] << "\n";
163    }
164
165    if (Show && ShowCounts)
166      OS << "    Block counts: [";
167    for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) {
168      if (Func.Counts[I] > MaxBlockCount)
169        MaxBlockCount = Func.Counts[I];
170      if (Show && ShowCounts)
171        OS << (I == 1 ? "" : ", ") << Func.Counts[I];
172    }
173    if (Show && ShowCounts)
174      OS << "]\n";
175  }
176  if (Reader->hasError())
177    exitWithError(Reader->getError().message(), Filename);
178
179  if (ShowAllFunctions || !ShowFunction.empty())
180    OS << "Functions shown: " << ShownFunctions << "\n";
181  OS << "Total functions: " << TotalFunctions << "\n";
182  OS << "Maximum function count: " << MaxFunctionCount << "\n";
183  OS << "Maximum internal block count: " << MaxBlockCount << "\n";
184  return 0;
185}
186
187static int showSampleProfile(std::string Filename, bool ShowCounts,
188                             bool ShowAllFunctions, std::string ShowFunction,
189                             raw_fd_ostream &OS) {
190  using namespace sampleprof;
191  auto ReaderOrErr = SampleProfileReader::create(Filename, getGlobalContext());
192  if (std::error_code EC = ReaderOrErr.getError())
193    exitWithError(EC.message(), Filename);
194
195  auto Reader = std::move(ReaderOrErr.get());
196  Reader->read();
197  if (ShowAllFunctions || ShowFunction.empty())
198    Reader->dump(OS);
199  else
200    Reader->dumpFunctionProfile(ShowFunction, OS);
201
202  return 0;
203}
204
205static int show_main(int argc, const char *argv[]) {
206  cl::opt<std::string> Filename(cl::Positional, cl::Required,
207                                cl::desc("<profdata-file>"));
208
209  cl::opt<bool> ShowCounts("counts", cl::init(false),
210                           cl::desc("Show counter values for shown functions"));
211  cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
212                                 cl::desc("Details for every function"));
213  cl::opt<std::string> ShowFunction("function",
214                                    cl::desc("Details for matching functions"));
215
216  cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
217                                      cl::init("-"), cl::desc("Output file"));
218  cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
219                            cl::aliasopt(OutputFilename));
220  cl::opt<ProfileKinds> ProfileKind(
221      cl::desc("Profile kind:"), cl::init(instr),
222      cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
223                 clEnumVal(sample, "Sample profile"), clEnumValEnd));
224
225  cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
226
227  if (OutputFilename.empty())
228    OutputFilename = "-";
229
230  std::error_code EC;
231  raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
232  if (EC)
233    exitWithError(EC.message(), OutputFilename);
234
235  if (ShowAllFunctions && !ShowFunction.empty())
236    errs() << "warning: -function argument ignored: showing all functions\n";
237
238  if (ProfileKind == instr)
239    return showInstrProfile(Filename, ShowCounts, ShowAllFunctions,
240                            ShowFunction, OS);
241  else
242    return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
243                             ShowFunction, OS);
244}
245
246int main(int argc, const char *argv[]) {
247  // Print a stack trace if we signal out.
248  sys::PrintStackTraceOnErrorSignal();
249  PrettyStackTraceProgram X(argc, argv);
250  llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
251
252  StringRef ProgName(sys::path::filename(argv[0]));
253  if (argc > 1) {
254    int (*func)(int, const char *[]) = nullptr;
255
256    if (strcmp(argv[1], "merge") == 0)
257      func = merge_main;
258    else if (strcmp(argv[1], "show") == 0)
259      func = show_main;
260
261    if (func) {
262      std::string Invocation(ProgName.str() + " " + argv[1]);
263      argv[1] = Invocation.c_str();
264      return func(argc - 1, argv + 1);
265    }
266
267    if (strcmp(argv[1], "-h") == 0 ||
268        strcmp(argv[1], "-help") == 0 ||
269        strcmp(argv[1], "--help") == 0) {
270
271      errs() << "OVERVIEW: LLVM profile data tools\n\n"
272             << "USAGE: " << ProgName << " <command> [args...]\n"
273             << "USAGE: " << ProgName << " <command> -help\n\n"
274             << "Available commands: merge, show\n";
275      return 0;
276    }
277  }
278
279  if (argc < 2)
280    errs() << ProgName << ": No command specified!\n";
281  else
282    errs() << ProgName << ": Unknown command!\n";
283
284  errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
285  return 1;
286}
287