1 //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
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 // llvm-profdata merges .profdata files.
12 //===----------------------------------------------------------------------===//
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"
34 static void exitWithError(const Twine &Message,
35 StringRef Whence = "",
36 StringRef Hint = "") {
39 errs() << Whence << ": ";
40 errs() << Message << "\n";
42 errs() << Hint << "\n";
46 static void exitWithErrorCode(const std::error_code &Error,
47 StringRef Whence = "") {
48 if (Error.category() == instrprof_category()) {
49 instrprof_error instrError = static_cast<instrprof_error>(Error.value());
50 if (instrError == instrprof_error::unrecognized_format) {
51 // Hint for common error of forgetting -sample for sample profiles.
52 exitWithError(Error.message(), Whence,
53 "Perhaps you forgot to use the -sample option?");
56 exitWithError(Error.message(), Whence);
60 enum ProfileKinds { instr, sample };
63 static void handleMergeWriterError(std::error_code &Error,
64 StringRef WhenceFile = "",
65 StringRef WhenceFunction = "",
68 if (!WhenceFile.empty())
69 errs() << WhenceFile << ": ";
70 if (!WhenceFunction.empty())
71 errs() << WhenceFunction << ": ";
72 errs() << Error.message() << "\n";
76 if (Error.category() == instrprof_category()) {
77 instrprof_error instrError = static_cast<instrprof_error>(Error.value());
79 case instrprof_error::hash_mismatch:
80 case instrprof_error::count_mismatch:
81 case instrprof_error::value_site_count_mismatch:
82 Hint = "Make sure that all profile data to be merged is generated " \
83 "from the same binary.";
91 errs() << Hint << "\n";
95 static void mergeInstrProfile(const cl::list<std::string> &Inputs,
96 StringRef OutputFilename) {
97 if (OutputFilename.compare("-") == 0)
98 exitWithError("Cannot write indexed profdata format to stdout.");
101 raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
103 exitWithErrorCode(EC, OutputFilename);
105 InstrProfWriter Writer;
106 std::set<std::error_code> WriterErrorCodes;
107 for (const auto &Filename : Inputs) {
108 auto ReaderOrErr = InstrProfReader::create(Filename);
109 if (std::error_code ec = ReaderOrErr.getError())
110 exitWithErrorCode(ec, Filename);
112 auto Reader = std::move(ReaderOrErr.get());
113 for (auto &I : *Reader) {
114 if (std::error_code EC = Writer.addRecord(std::move(I))) {
115 // Only show hint the first time an error occurs.
116 bool firstTime = WriterErrorCodes.insert(EC).second;
117 handleMergeWriterError(EC, Filename, I.Name, firstTime);
120 if (Reader->hasError())
121 exitWithErrorCode(Reader->getError(), Filename);
123 Writer.write(Output);
126 static void mergeSampleProfile(const cl::list<std::string> &Inputs,
127 StringRef OutputFilename,
128 sampleprof::SampleProfileFormat OutputFormat) {
129 using namespace sampleprof;
130 auto WriterOrErr = SampleProfileWriter::create(OutputFilename, OutputFormat);
131 if (std::error_code EC = WriterOrErr.getError())
132 exitWithErrorCode(EC, OutputFilename);
134 auto Writer = std::move(WriterOrErr.get());
135 StringMap<FunctionSamples> ProfileMap;
136 SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
137 for (const auto &Filename : Inputs) {
139 SampleProfileReader::create(Filename, getGlobalContext());
140 if (std::error_code EC = ReaderOrErr.getError())
141 exitWithErrorCode(EC, Filename);
143 // We need to keep the readers around until after all the files are
144 // read so that we do not lose the function names stored in each
145 // reader's memory. The function names are needed to write out the
146 // merged profile map.
147 Readers.push_back(std::move(ReaderOrErr.get()));
148 const auto Reader = Readers.back().get();
149 if (std::error_code EC = Reader->read())
150 exitWithErrorCode(EC, Filename);
152 StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
153 for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
156 StringRef FName = I->first();
157 FunctionSamples &Samples = I->second;
158 ProfileMap[FName].merge(Samples);
161 Writer->write(ProfileMap);
164 static int merge_main(int argc, const char *argv[]) {
165 cl::list<std::string> Inputs(cl::Positional, cl::Required, cl::OneOrMore,
166 cl::desc("<filenames...>"));
168 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
169 cl::init("-"), cl::Required,
170 cl::desc("Output file"));
171 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
172 cl::aliasopt(OutputFilename));
173 cl::opt<ProfileKinds> ProfileKind(
174 cl::desc("Profile kind:"), cl::init(instr),
175 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
176 clEnumVal(sample, "Sample profile"), clEnumValEnd));
178 cl::opt<sampleprof::SampleProfileFormat> OutputFormat(
179 cl::desc("Format of output profile (only meaningful with --sample)"),
180 cl::init(sampleprof::SPF_Binary),
181 cl::values(clEnumValN(sampleprof::SPF_Binary, "binary",
182 "Binary encoding (default)"),
183 clEnumValN(sampleprof::SPF_Text, "text", "Text encoding"),
184 clEnumValN(sampleprof::SPF_GCC, "gcc", "GCC encoding"),
187 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
189 if (ProfileKind == instr)
190 mergeInstrProfile(Inputs, OutputFilename);
192 mergeSampleProfile(Inputs, OutputFilename, OutputFormat);
197 static int showInstrProfile(std::string Filename, bool ShowCounts,
198 bool ShowIndirectCallTargets, bool ShowAllFunctions,
199 std::string ShowFunction, raw_fd_ostream &OS) {
200 auto ReaderOrErr = InstrProfReader::create(Filename);
201 if (std::error_code EC = ReaderOrErr.getError())
202 exitWithErrorCode(EC, Filename);
204 auto Reader = std::move(ReaderOrErr.get());
205 uint64_t MaxFunctionCount = 0, MaxBlockCount = 0;
206 size_t ShownFunctions = 0, TotalFunctions = 0;
207 for (const auto &Func : *Reader) {
209 ShowAllFunctions || (!ShowFunction.empty() &&
210 Func.Name.find(ShowFunction) != Func.Name.npos);
213 assert(Func.Counts.size() > 0 && "function missing entry counter");
214 if (Func.Counts[0] > MaxFunctionCount)
215 MaxFunctionCount = Func.Counts[0];
222 OS << " " << Func.Name << ":\n"
223 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
224 << " Counters: " << Func.Counts.size() << "\n"
225 << " Function count: " << Func.Counts[0] << "\n";
226 if (ShowIndirectCallTargets)
227 OS << " Indirect Call Site Count: "
228 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
231 if (Show && ShowCounts)
232 OS << " Block counts: [";
233 for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) {
234 if (Func.Counts[I] > MaxBlockCount)
235 MaxBlockCount = Func.Counts[I];
236 if (Show && ShowCounts)
237 OS << (I == 1 ? "" : ", ") << Func.Counts[I];
239 if (Show && ShowCounts)
242 if (Show && ShowIndirectCallTargets) {
243 uint32_t NS = Func.getNumValueSites(IPVK_IndirectCallTarget);
244 OS << " Indirect Target Results: \n";
245 for (size_t I = 0; I < NS; ++I) {
246 uint32_t NV = Func.getNumValueDataForSite(IPVK_IndirectCallTarget, I);
247 std::unique_ptr<InstrProfValueData[]> VD =
248 Func.getValueForSite(IPVK_IndirectCallTarget, I);
249 for (uint32_t V = 0; V < NV; V++) {
250 OS << "\t[ " << I << ", ";
251 OS << (const char *)VD[V].Value << ", " << VD[V].Count << " ]\n";
256 if (Reader->hasError())
257 exitWithErrorCode(Reader->getError(), Filename);
259 if (ShowAllFunctions || !ShowFunction.empty())
260 OS << "Functions shown: " << ShownFunctions << "\n";
261 OS << "Total functions: " << TotalFunctions << "\n";
262 OS << "Maximum function count: " << MaxFunctionCount << "\n";
263 OS << "Maximum internal block count: " << MaxBlockCount << "\n";
267 static int showSampleProfile(std::string Filename, bool ShowCounts,
268 bool ShowAllFunctions, std::string ShowFunction,
269 raw_fd_ostream &OS) {
270 using namespace sampleprof;
271 auto ReaderOrErr = SampleProfileReader::create(Filename, getGlobalContext());
272 if (std::error_code EC = ReaderOrErr.getError())
273 exitWithErrorCode(EC, Filename);
275 auto Reader = std::move(ReaderOrErr.get());
276 if (std::error_code EC = Reader->read())
277 exitWithErrorCode(EC, Filename);
279 if (ShowAllFunctions || ShowFunction.empty())
282 Reader->dumpFunctionProfile(ShowFunction, OS);
287 static int show_main(int argc, const char *argv[]) {
288 cl::opt<std::string> Filename(cl::Positional, cl::Required,
289 cl::desc("<profdata-file>"));
291 cl::opt<bool> ShowCounts("counts", cl::init(false),
292 cl::desc("Show counter values for shown functions"));
293 cl::opt<bool> ShowIndirectCallTargets(
294 "ic-targets", cl::init(false),
295 cl::desc("Show indirect call site target values for shown functions"));
296 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
297 cl::desc("Details for every function"));
298 cl::opt<std::string> ShowFunction("function",
299 cl::desc("Details for matching functions"));
301 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
302 cl::init("-"), cl::desc("Output file"));
303 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
304 cl::aliasopt(OutputFilename));
305 cl::opt<ProfileKinds> ProfileKind(
306 cl::desc("Profile kind:"), cl::init(instr),
307 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
308 clEnumVal(sample, "Sample profile"), clEnumValEnd));
310 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
312 if (OutputFilename.empty())
313 OutputFilename = "-";
316 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
318 exitWithErrorCode(EC, OutputFilename);
320 if (ShowAllFunctions && !ShowFunction.empty())
321 errs() << "warning: -function argument ignored: showing all functions\n";
323 if (ProfileKind == instr)
324 return showInstrProfile(Filename, ShowCounts, ShowIndirectCallTargets,
325 ShowAllFunctions, ShowFunction, OS);
327 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
331 int main(int argc, const char *argv[]) {
332 // Print a stack trace if we signal out.
333 sys::PrintStackTraceOnErrorSignal();
334 PrettyStackTraceProgram X(argc, argv);
335 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
337 StringRef ProgName(sys::path::filename(argv[0]));
339 int (*func)(int, const char *[]) = nullptr;
341 if (strcmp(argv[1], "merge") == 0)
343 else if (strcmp(argv[1], "show") == 0)
347 std::string Invocation(ProgName.str() + " " + argv[1]);
348 argv[1] = Invocation.c_str();
349 return func(argc - 1, argv + 1);
352 if (strcmp(argv[1], "-h") == 0 ||
353 strcmp(argv[1], "-help") == 0 ||
354 strcmp(argv[1], "--help") == 0) {
356 errs() << "OVERVIEW: LLVM profile data tools\n\n"
357 << "USAGE: " << ProgName << " <command> [args...]\n"
358 << "USAGE: " << ProgName << " <command> -help\n\n"
359 << "Available commands: merge, show\n";
365 errs() << ProgName << ": No command specified!\n";
367 errs() << ProgName << ": Unknown command!\n";
369 errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";