blob: d62505af40e5cb76c086165028fab9f9fc2a496b [file] [log] [blame]
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +00001//===- 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
Nathan Slingerlandc21a44d2015-11-18 17:10:24 +000014#include "llvm/ADT/SmallSet.h"
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +000015#include "llvm/ADT/SmallVector.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000016#include "llvm/ADT/StringRef.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000017#include "llvm/IR/LLVMContext.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000018#include "llvm/ProfileData/InstrProfReader.h"
Justin Bognerb9bd7f82014-03-21 17:46:22 +000019#include "llvm/ProfileData/InstrProfWriter.h"
Easwaran Ramand68aae22016-02-04 23:34:31 +000020#include "llvm/ProfileData/ProfileCommon.h"
Diego Novillod5336ae2014-11-01 00:56:55 +000021#include "llvm/ProfileData/SampleProfReader.h"
22#include "llvm/ProfileData/SampleProfWriter.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000023#include "llvm/Support/CommandLine.h"
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +000024#include "llvm/Support/Errc.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000025#include "llvm/Support/FileSystem.h"
Justin Bogner423380f2014-03-23 20:43:50 +000026#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000027#include "llvm/Support/InitLLVM.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000029#include "llvm/Support/Path.h"
Jonas Devliegheree46b7562018-04-18 14:42:33 +000030#include "llvm/Support/WithColor.h"
Vedant Kumare3a0bf52016-07-19 01:17:20 +000031#include "llvm/Support/ThreadPool.h"
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000032#include "llvm/Support/raw_ostream.h"
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +000033#include <algorithm>
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000034
35using namespace llvm;
36
Wei Mia0c08572018-06-11 22:40:43 +000037enum ProfileFormat {
38 PF_None = 0,
39 PF_Text,
40 PF_Compact_Binary,
41 PF_GCC,
Wei Mid9be2c72018-06-12 05:53:49 +000042 PF_Binary
Wei Mia0c08572018-06-11 22:40:43 +000043};
Xinliang David Li6f7c19a2015-11-23 20:47:38 +000044
Jonas Devliegheree46b7562018-04-18 14:42:33 +000045static void warn(Twine Message, std::string Whence = "",
Vedant Kumar188efda2017-11-17 21:18:32 +000046 std::string Hint = "") {
Jonas Devliegheree46b7562018-04-18 14:42:33 +000047 WithColor::warning();
Justin Bognerf8d79192014-03-21 17:24:48 +000048 if (!Whence.empty())
49 errs() << Whence << ": ";
50 errs() << Message << "\n";
Nathan Slingerland4f823662015-11-13 03:47:58 +000051 if (!Hint.empty())
Jonas Devliegheree46b7562018-04-18 14:42:33 +000052 WithColor::note() << Hint << "\n";
Vedant Kumar188efda2017-11-17 21:18:32 +000053}
54
55static void exitWithError(Twine Message, std::string Whence = "",
56 std::string Hint = "") {
Jonas Devliegheree46b7562018-04-18 14:42:33 +000057 WithColor::error();
58 if (!Whence.empty())
59 errs() << Whence << ": ";
60 errs() << Message << "\n";
61 if (!Hint.empty())
62 WithColor::note() << Hint << "\n";
Duncan P. N. Exon Smith846a6272014-02-17 23:22:49 +000063 ::exit(1);
64}
65
Vedant Kumar9152fd12016-05-19 03:54:45 +000066static void exitWithError(Error E, StringRef Whence = "") {
67 if (E.isA<InstrProfError>()) {
68 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
69 instrprof_error instrError = IPE.get();
70 StringRef Hint = "";
71 if (instrError == instrprof_error::unrecognized_format) {
72 // Hint for common error of forgetting -sample for sample profiles.
73 Hint = "Perhaps you forgot to use the -sample option?";
74 }
75 exitWithError(IPE.message(), Whence, Hint);
76 });
Nathan Slingerland4f823662015-11-13 03:47:58 +000077 }
Vedant Kumar9152fd12016-05-19 03:54:45 +000078
79 exitWithError(toString(std::move(E)), Whence);
80}
81
82static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
83 exitWithError(EC.message(), Whence);
Nathan Slingerland4f823662015-11-13 03:47:58 +000084}
85
Duncan P. N. Exon Smith02b6fa92015-06-16 00:43:04 +000086namespace {
Diego Novillod3babdb2015-12-14 20:37:15 +000087enum ProfileKinds { instr, sample };
Duncan P. N. Exon Smith02b6fa92015-06-16 00:43:04 +000088}
Justin Bogner618bcea2014-03-19 02:20:46 +000089
Vedant Kumar9152fd12016-05-19 03:54:45 +000090static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000091 StringRef WhenceFunction = "",
Diego Novillod3babdb2015-12-14 20:37:15 +000092 bool ShowHint = true) {
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000093 if (!WhenceFile.empty())
94 errs() << WhenceFile << ": ";
95 if (!WhenceFunction.empty())
96 errs() << WhenceFunction << ": ";
Vedant Kumar9152fd12016-05-19 03:54:45 +000097
98 auto IPE = instrprof_error::success;
99 E = handleErrors(std::move(E),
100 [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
101 IPE = E->get();
102 return Error(std::move(E));
103 });
104 errs() << toString(std::move(E)) << "\n";
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000105
106 if (ShowHint) {
107 StringRef Hint = "";
Vedant Kumar9152fd12016-05-19 03:54:45 +0000108 if (IPE != instrprof_error::success) {
109 switch (IPE) {
Nathan Slingerland11c938d12015-11-17 23:37:09 +0000110 case instrprof_error::hash_mismatch:
111 case instrprof_error::count_mismatch:
112 case instrprof_error::value_site_count_mismatch:
Diego Novillod3babdb2015-12-14 20:37:15 +0000113 Hint = "Make sure that all profile data to be merged is generated "
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000114 "from the same binary.";
Nathan Slingerland11c938d12015-11-17 23:37:09 +0000115 break;
Nathan Slingerlandb2d95f02015-11-18 00:52:45 +0000116 default:
117 break;
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000118 }
119 }
120
121 if (!Hint.empty())
122 errs() << Hint << "\n";
123 }
124}
125
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000126struct WeightedFile {
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000127 std::string Filename;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000128 uint64_t Weight;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000129};
130typedef SmallVector<WeightedFile, 5> WeightedFileVector;
131
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000132/// Keep track of merged data and reported errors.
133struct WriterContext {
134 std::mutex Lock;
135 InstrProfWriter Writer;
136 Error Err;
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000137 std::string ErrWhence;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000138 std::mutex &ErrLock;
139 SmallSet<instrprof_error, 4> &WriterErrorCodes;
140
141 WriterContext(bool IsSparse, std::mutex &ErrLock,
142 SmallSet<instrprof_error, 4> &WriterErrorCodes)
143 : Lock(), Writer(IsSparse), Err(Error::success()), ErrWhence(""),
144 ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {}
145};
146
Vedant Kumar188efda2017-11-17 21:18:32 +0000147/// Determine whether an error is fatal for profile merging.
148static bool isFatalError(instrprof_error IPE) {
149 switch (IPE) {
150 default:
151 return true;
152 case instrprof_error::success:
153 case instrprof_error::eof:
154 case instrprof_error::unknown_function:
155 case instrprof_error::hash_mismatch:
156 case instrprof_error::count_mismatch:
157 case instrprof_error::counter_overflow:
158 case instrprof_error::value_site_count_mismatch:
159 return false;
160 }
161}
162
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000163/// Load an input into a writer context.
164static void loadInput(const WeightedFile &Input, WriterContext *WC) {
165 std::unique_lock<std::mutex> CtxGuard{WC->Lock};
166
167 // If there's a pending hard error, don't do more work.
168 if (WC->Err)
169 return;
170
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000171 // Copy the filename, because llvm::ThreadPool copied the input "const
172 // WeightedFile &" by value, making a reference to the filename within it
173 // invalid outside of this packaged task.
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000174 WC->ErrWhence = Input.Filename;
175
176 auto ReaderOrErr = InstrProfReader::create(Input.Filename);
Rong Xu2c684cf2016-10-19 22:51:17 +0000177 if (Error E = ReaderOrErr.takeError()) {
178 // Skip the empty profiles by returning sliently.
179 instrprof_error IPE = InstrProfError::take(std::move(E));
180 if (IPE != instrprof_error::empty_raw_profile)
181 WC->Err = make_error<InstrProfError>(IPE);
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000182 return;
Rong Xu2c684cf2016-10-19 22:51:17 +0000183 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000184
185 auto Reader = std::move(ReaderOrErr.get());
186 bool IsIRProfile = Reader->isIRLevelProfile();
187 if (WC->Writer.setIsIRLevelProfile(IsIRProfile)) {
188 WC->Err = make_error<StringError>(
189 "Merge IR generated profile with Clang generated profile.",
190 std::error_code());
191 return;
192 }
193
194 for (auto &I : *Reader) {
Rong Xufe90d862016-10-19 23:31:59 +0000195 const StringRef FuncName = I.Name;
David Blaikie98cce002017-07-10 03:04:59 +0000196 bool Reported = false;
197 WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
198 if (Reported) {
199 consumeError(std::move(E));
200 return;
201 }
202 Reported = true;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000203 // Only show hint the first time an error occurs.
204 instrprof_error IPE = InstrProfError::take(std::move(E));
205 std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
206 bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
207 handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
Rong Xufe90d862016-10-19 23:31:59 +0000208 FuncName, firstTime);
David Blaikie98cce002017-07-10 03:04:59 +0000209 });
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000210 }
Vedant Kumar188efda2017-11-17 21:18:32 +0000211 if (Reader->hasError()) {
212 if (Error E = Reader->getError()) {
213 instrprof_error IPE = InstrProfError::take(std::move(E));
214 if (isFatalError(IPE))
215 WC->Err = make_error<InstrProfError>(IPE);
216 }
217 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000218}
219
220/// Merge the \p Src writer context into \p Dst.
221static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
Vedant Kumarfaaa42a2017-11-17 02:58:23 +0000222 // If we've already seen a hard error, continuing with the merge would
223 // clobber it.
224 if (Dst->Err || Src->Err)
225 return;
226
David Blaikie98cce002017-07-10 03:04:59 +0000227 bool Reported = false;
228 Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
229 if (Reported) {
230 consumeError(std::move(E));
231 return;
232 }
233 Reported = true;
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000234 Dst->Err = std::move(E);
David Blaikie98cce002017-07-10 03:04:59 +0000235 });
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000236}
237
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000238static void mergeInstrProfile(const WeightedFileVector &Inputs,
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000239 StringRef OutputFilename,
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000240 ProfileFormat OutputFormat, bool OutputSparse,
241 unsigned NumThreads) {
Justin Bognerb7aa2632014-04-18 21:48:40 +0000242 if (OutputFilename.compare("-") == 0)
243 exitWithError("Cannot write indexed profdata format to stdout.");
Justin Bognerec49f982014-03-12 22:00:57 +0000244
Wei Mid9be2c72018-06-12 05:53:49 +0000245 if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
Wei Mia0c08572018-06-11 22:40:43 +0000246 OutputFormat != PF_Text)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000247 exitWithError("Unknown format is specified.");
248
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000249 std::error_code EC;
250 raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
251 if (EC)
Nathan Slingerland4f823662015-11-13 03:47:58 +0000252 exitWithErrorCode(EC, OutputFilename);
Justin Bognerec49f982014-03-12 22:00:57 +0000253
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000254 std::mutex ErrorLock;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000255 SmallSet<instrprof_error, 4> WriterErrorCodes;
Justin Bognerf8d79192014-03-21 17:24:48 +0000256
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000257 // If NumThreads is not specified, auto-detect a good default.
258 if (NumThreads == 0)
Rafael Espindola8c0ff952017-10-04 20:27:01 +0000259 NumThreads =
260 std::min(hardware_concurrency(), unsigned((Inputs.size() + 1) / 2));
Rong Xu33c76c02016-02-10 17:18:30 +0000261
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000262 // Initialize the writer contexts.
263 SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
264 for (unsigned I = 0; I < NumThreads; ++I)
265 Contexts.emplace_back(llvm::make_unique<WriterContext>(
266 OutputSparse, ErrorLock, WriterErrorCodes));
267
268 if (NumThreads == 1) {
269 for (const auto &Input : Inputs)
270 loadInput(Input, Contexts[0].get());
271 } else {
272 ThreadPool Pool(NumThreads);
273
274 // Load the inputs in parallel (N/NumThreads serial steps).
275 unsigned Ctx = 0;
276 for (const auto &Input : Inputs) {
277 Pool.async(loadInput, Input, Contexts[Ctx].get());
278 Ctx = (Ctx + 1) % NumThreads;
Nathan Slingerlande6e30d52015-11-17 22:08:53 +0000279 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000280 Pool.wait();
281
282 // Merge the writer contexts together (~ lg(NumThreads) serial steps).
283 unsigned Mid = Contexts.size() / 2;
284 unsigned End = Contexts.size();
285 assert(Mid > 0 && "Expected more than one context");
286 do {
287 for (unsigned I = 0; I < Mid; ++I)
288 Pool.async(mergeWriterContexts, Contexts[I].get(),
289 Contexts[I + Mid].get());
290 Pool.wait();
291 if (End & 1) {
292 Pool.async(mergeWriterContexts, Contexts[0].get(),
293 Contexts[End - 1].get());
294 Pool.wait();
295 }
296 End = Mid;
297 Mid /= 2;
298 } while (Mid > 0);
Justin Bognerbfee8d42014-03-12 20:14:17 +0000299 }
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000300
301 // Handle deferred hard errors encountered during merging.
Vedant Kumar188efda2017-11-17 21:18:32 +0000302 for (std::unique_ptr<WriterContext> &WC : Contexts) {
303 if (!WC->Err)
304 continue;
305 if (!WC->Err.isA<InstrProfError>())
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000306 exitWithError(std::move(WC->Err), WC->ErrWhence);
307
Vedant Kumar188efda2017-11-17 21:18:32 +0000308 instrprof_error IPE = InstrProfError::take(std::move(WC->Err));
309 if (isFatalError(IPE))
310 exitWithError(make_error<InstrProfError>(IPE), WC->ErrWhence);
311 else
Jonas Devliegheree46b7562018-04-18 14:42:33 +0000312 warn(toString(make_error<InstrProfError>(IPE)),
Vedant Kumar188efda2017-11-17 21:18:32 +0000313 WC->ErrWhence);
314 }
315
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000316 InstrProfWriter &Writer = Contexts[0]->Writer;
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000317 if (OutputFormat == PF_Text) {
318 if (Error E = Writer.writeText(Output))
319 exitWithError(std::move(E));
320 } else {
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000321 Writer.write(Output);
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000322 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000323}
324
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000325static sampleprof::SampleProfileFormat FormatMap[] = {
Wei Mia0c08572018-06-11 22:40:43 +0000326 sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Compact_Binary,
Wei Mid9be2c72018-06-12 05:53:49 +0000327 sampleprof::SPF_GCC, sampleprof::SPF_Binary};
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000328
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000329static void mergeSampleProfile(const WeightedFileVector &Inputs,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000330 StringRef OutputFilename,
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000331 ProfileFormat OutputFormat) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000332 using namespace sampleprof;
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000333 auto WriterOrErr =
334 SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
Diego Novillofcd55602014-11-03 00:51:45 +0000335 if (std::error_code EC = WriterOrErr.getError())
Nathan Slingerland4f823662015-11-13 03:47:58 +0000336 exitWithErrorCode(EC, OutputFilename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000337
Diego Novillofcd55602014-11-03 00:51:45 +0000338 auto Writer = std::move(WriterOrErr.get());
Diego Novillod5336ae2014-11-01 00:56:55 +0000339 StringMap<FunctionSamples> ProfileMap;
Diego Novilloaae1ed82015-10-08 19:40:37 +0000340 SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
Mehdi Amini03b42e42016-04-14 21:59:01 +0000341 LLVMContext Context;
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000342 for (const auto &Input : Inputs) {
Mehdi Amini03b42e42016-04-14 21:59:01 +0000343 auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
Diego Novillofcd55602014-11-03 00:51:45 +0000344 if (std::error_code EC = ReaderOrErr.getError())
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000345 exitWithErrorCode(EC, Input.Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000346
Diego Novilloaae1ed82015-10-08 19:40:37 +0000347 // We need to keep the readers around until after all the files are
348 // read so that we do not lose the function names stored in each
349 // reader's memory. The function names are needed to write out the
350 // merged profile map.
351 Readers.push_back(std::move(ReaderOrErr.get()));
352 const auto Reader = Readers.back().get();
Diego Novillod5336ae2014-11-01 00:56:55 +0000353 if (std::error_code EC = Reader->read())
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000354 exitWithErrorCode(EC, Input.Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000355
356 StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
357 for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
358 E = Profiles.end();
359 I != E; ++I) {
360 StringRef FName = I->first();
361 FunctionSamples &Samples = I->second;
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000362 sampleprof_error Result = ProfileMap[FName].merge(Samples, Input.Weight);
363 if (Result != sampleprof_error::success) {
364 std::error_code EC = make_error_code(Result);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000365 handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
Nathan Slingerland48dd0802015-12-16 21:45:43 +0000366 }
Diego Novillod5336ae2014-11-01 00:56:55 +0000367 }
368 }
369 Writer->write(ProfileMap);
370}
371
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000372static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
Vedant Kumar8d0e8612016-06-06 23:43:56 +0000373 StringRef WeightStr, FileName;
374 std::tie(WeightStr, FileName) = WeightedFilename.split(',');
Diego Novillod5336ae2014-11-01 00:56:55 +0000375
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000376 uint64_t Weight;
377 if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
378 exitWithError("Input weight must be a positive integer.");
379
Benjamin Kramer929e7db2016-07-21 14:29:11 +0000380 return {FileName, Weight};
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000381}
382
Vedant Kumarcef43602016-06-07 22:47:31 +0000383static std::unique_ptr<MemoryBuffer>
384getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
385 if (InputFilenamesFile == "")
386 return {};
387
388 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
389 if (!BufOrError)
390 exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
391
392 return std::move(*BufOrError);
393}
394
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000395static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
396 StringRef Filename = WF.Filename;
397 uint64_t Weight = WF.Weight;
Benjamin Kramera81f4722016-07-22 12:39:55 +0000398
399 // If it's STDIN just pass it on.
400 if (Filename == "-") {
401 WNI.push_back({Filename, Weight});
402 return;
403 }
404
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000405 llvm::sys::fs::file_status Status;
406 llvm::sys::fs::status(Filename, Status);
407 if (!llvm::sys::fs::exists(Status))
408 exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
409 Filename);
410 // If it's a source file, collect it.
411 if (llvm::sys::fs::is_regular_file(Status)) {
Benjamin Kramer929e7db2016-07-21 14:29:11 +0000412 WNI.push_back({Filename, Weight});
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000413 return;
414 }
415
416 if (llvm::sys::fs::is_directory(Status)) {
417 std::error_code EC;
418 for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
419 F != E && !EC; F.increment(EC)) {
420 if (llvm::sys::fs::is_regular_file(F->path())) {
421 addWeightedInput(WNI, {F->path(), Weight});
422 }
423 }
424 if (EC)
425 exitWithErrorCode(EC, Filename);
426 }
427}
428
Vedant Kumarcef43602016-06-07 22:47:31 +0000429static void parseInputFilenamesFile(MemoryBuffer *Buffer,
430 WeightedFileVector &WFV) {
431 if (!Buffer)
432 return;
433
434 SmallVector<StringRef, 8> Entries;
435 StringRef Data = Buffer->getBuffer();
436 Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
437 for (const StringRef &FileWeightEntry : Entries) {
438 StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
439 // Skip comments.
440 if (SanitizedEntry.startswith("#"))
441 continue;
442 // If there's no comma, it's an unweighted profile.
443 else if (SanitizedEntry.find(',') == StringRef::npos)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000444 addWeightedInput(WFV, {SanitizedEntry, 1});
Vedant Kumarcef43602016-06-07 22:47:31 +0000445 else
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000446 addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
Vedant Kumarcef43602016-06-07 22:47:31 +0000447 }
448}
449
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000450static int merge_main(int argc, const char *argv[]) {
451 cl::list<std::string> InputFilenames(cl::Positional,
452 cl::desc("<filename...>"));
453 cl::list<std::string> WeightedInputFilenames("weighted-input",
454 cl::desc("<weight>,<filename>"));
Vedant Kumarcef43602016-06-07 22:47:31 +0000455 cl::opt<std::string> InputFilenamesFile(
456 "input-files", cl::init(""),
457 cl::desc("Path to file containing newline-separated "
458 "[<weight>,]<filename> entries"));
459 cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
460 cl::aliasopt(InputFilenamesFile));
461 cl::opt<bool> DumpInputFileList(
462 "dump-input-file-list", cl::init(false), cl::Hidden,
463 cl::desc("Dump the list of input files and their weights, then exit"));
Diego Novillod5336ae2014-11-01 00:56:55 +0000464 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
465 cl::init("-"), cl::Required,
466 cl::desc("Output file"));
467 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
468 cl::aliasopt(OutputFilename));
469 cl::opt<ProfileKinds> ProfileKind(
470 cl::desc("Profile kind:"), cl::init(instr),
471 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000472 clEnumVal(sample, "Sample profile")));
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000473 cl::opt<ProfileFormat> OutputFormat(
Wei Mid9be2c72018-06-12 05:53:49 +0000474 cl::desc("Format of output profile"), cl::init(PF_Binary),
475 cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
476 clEnumValN(PF_Compact_Binary, "compbinary",
477 "Compact binary encoding"),
478 clEnumValN(PF_Text, "text", "Text encoding"),
479 clEnumValN(PF_GCC, "gcc",
480 "GCC encoding (only meaningful for -sample)")));
Vedant Kumar00dab222016-01-29 22:54:45 +0000481 cl::opt<bool> OutputSparse("sparse", cl::init(false),
482 cl::desc("Generate a sparse profile (only meaningful for -instr)"));
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000483 cl::opt<unsigned> NumThreads(
484 "num-threads", cl::init(0),
485 cl::desc("Number of merge threads to use (default: autodetect)"));
486 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
487 cl::aliasopt(NumThreads));
Vedant Kumar00dab222016-01-29 22:54:45 +0000488
Diego Novillod5336ae2014-11-01 00:56:55 +0000489 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
490
Vedant Kumarcef43602016-06-07 22:47:31 +0000491 WeightedFileVector WeightedInputs;
492 for (StringRef Filename : InputFilenames)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000493 addWeightedInput(WeightedInputs, {Filename, 1});
Vedant Kumarcef43602016-06-07 22:47:31 +0000494 for (StringRef WeightedFilename : WeightedInputFilenames)
Xinliang David Li9a1bfcf2016-07-20 22:24:52 +0000495 addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
Vedant Kumarcef43602016-06-07 22:47:31 +0000496
497 // Make sure that the file buffer stays alive for the duration of the
498 // weighted input vector's lifetime.
499 auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
500 parseInputFilenamesFile(Buffer.get(), WeightedInputs);
501
502 if (WeightedInputs.empty())
Chandler Carruth0c30f892016-06-04 03:08:01 +0000503 exitWithError("No input files specified. See " +
504 sys::path::filename(argv[0]) + " -help");
505
Vedant Kumarcef43602016-06-07 22:47:31 +0000506 if (DumpInputFileList) {
507 for (auto &WF : WeightedInputs)
508 outs() << WF.Weight << "," << WF.Filename << "\n";
509 return 0;
510 }
Vedant Kumarf771a052016-06-04 00:36:28 +0000511
Diego Novillod5336ae2014-11-01 00:56:55 +0000512 if (ProfileKind == instr)
Vedant Kumar00dab222016-01-29 22:54:45 +0000513 mergeInstrProfile(WeightedInputs, OutputFilename, OutputFormat,
Vedant Kumare3a0bf52016-07-19 01:17:20 +0000514 OutputSparse, NumThreads);
Diego Novillod5336ae2014-11-01 00:56:55 +0000515 else
Nathan Slingerland7f5b47d2015-12-15 17:37:09 +0000516 mergeSampleProfile(WeightedInputs, OutputFilename, OutputFormat);
Justin Bognerbfee8d42014-03-12 20:14:17 +0000517
Justin Bognerec49f982014-03-12 22:00:57 +0000518 return 0;
Justin Bognerbfee8d42014-03-12 20:14:17 +0000519}
Justin Bogner618bcea2014-03-19 02:20:46 +0000520
Rong Xu0cf1f562017-03-09 19:03:57 +0000521typedef struct ValueSitesStats {
522 ValueSitesStats()
523 : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
524 TotalNumValues(0) {}
525 uint64_t TotalNumValueSites;
526 uint64_t TotalNumValueSitesWithValueProfile;
527 uint64_t TotalNumValues;
528 std::vector<unsigned> ValueSitesHistogram;
529} ValueSitesStats;
530
531static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
532 ValueSitesStats &Stats, raw_fd_ostream &OS,
Rong Xu60faea12017-03-16 21:15:48 +0000533 InstrProfSymtab *Symtab) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000534 uint32_t NS = Func.getNumValueSites(VK);
535 Stats.TotalNumValueSites += NS;
536 for (size_t I = 0; I < NS; ++I) {
537 uint32_t NV = Func.getNumValueDataForSite(VK, I);
538 std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
539 Stats.TotalNumValues += NV;
540 if (NV) {
541 Stats.TotalNumValueSitesWithValueProfile++;
542 if (NV > Stats.ValueSitesHistogram.size())
543 Stats.ValueSitesHistogram.resize(NV, 0);
544 Stats.ValueSitesHistogram[NV - 1]++;
545 }
546 for (uint32_t V = 0; V < NV; V++) {
547 OS << "\t[ " << I << ", ";
Rong Xu60faea12017-03-16 21:15:48 +0000548 if (Symtab == nullptr)
549 OS << VD[V].Value;
550 else
551 OS << Symtab->getFuncName(VD[V].Value);
552 OS << ", " << VD[V].Count << " ]\n";
Rong Xu0cf1f562017-03-09 19:03:57 +0000553 }
554 }
555}
556
557static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
558 ValueSitesStats &Stats) {
559 OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
560 OS << " Total number of sites with values: "
561 << Stats.TotalNumValueSitesWithValueProfile << "\n";
562 OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
563
564 OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
565 for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
566 if (Stats.ValueSitesHistogram[I] > 0)
567 OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
568 }
569}
570
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000571static int showInstrProfile(const std::string &Filename, bool ShowCounts,
Xinliang David Li801b5312017-07-11 20:30:43 +0000572 uint32_t TopN, bool ShowIndirectCallTargets,
573 bool ShowMemOPSizes, bool ShowDetailedSummary,
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000574 std::vector<uint32_t> DetailedSummaryCutoffs,
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000575 bool ShowAllFunctions,
576 const std::string &ShowFunction, bool TextFormat,
577 raw_fd_ostream &OS) {
Diego Novillofcd55602014-11-03 00:51:45 +0000578 auto ReaderOrErr = InstrProfReader::create(Filename);
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000579 std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
580 if (ShowDetailedSummary && Cutoffs.empty()) {
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000581 Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
582 }
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000583 InstrProfSummaryBuilder Builder(std::move(Cutoffs));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000584 if (Error E = ReaderOrErr.takeError())
585 exitWithError(std::move(E), Filename);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000586
Diego Novillofcd55602014-11-03 00:51:45 +0000587 auto Reader = std::move(ReaderOrErr.get());
Rong Xu33c76c02016-02-10 17:18:30 +0000588 bool IsIRInstr = Reader->isIRLevelProfile();
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000589 size_t ShownFunctions = 0;
Rong Xu0cf1f562017-03-09 19:03:57 +0000590 int NumVPKind = IPVK_Last - IPVK_First + 1;
591 std::vector<ValueSitesStats> VPStats(NumVPKind);
Xinliang David Li801b5312017-07-11 20:30:43 +0000592
593 auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
594 const std::pair<std::string, uint64_t> &v2) {
595 return v1.second > v2.second;
596 };
597
598 std::priority_queue<std::pair<std::string, uint64_t>,
599 std::vector<std::pair<std::string, uint64_t>>,
600 decltype(MinCmp)>
601 HottestFuncs(MinCmp);
602
Richard Smithc6ba9ca2018-08-24 01:34:45 +0000603 // Add marker so that IR-level instrumentation round-trips properly.
604 if (TextFormat && IsIRInstr)
605 OS << ":ir\n";
606
Justin Bogner9af28ef2014-03-21 17:29:44 +0000607 for (const auto &Func : *Reader) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000608 bool Show =
609 ShowAllFunctions || (!ShowFunction.empty() &&
610 Func.Name.find(ShowFunction) != Func.Name.npos);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000611
Richard Smithc6ba9ca2018-08-24 01:34:45 +0000612 bool doTextFormatDump = (Show && TextFormat);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000613
614 if (doTextFormatDump) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000615 InstrProfSymtab &Symtab = Reader->getSymtab();
David Blaikiecf9d52c2017-07-06 19:00:12 +0000616 InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
617 OS);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000618 continue;
619 }
620
Justin Bognerb59d7c72014-04-25 02:45:33 +0000621 assert(Func.Counts.size() > 0 && "function missing entry counter");
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000622 Builder.addRecord(Func);
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000623
Xinliang David Li801b5312017-07-11 20:30:43 +0000624 if (TopN) {
625 uint64_t FuncMax = 0;
626 for (size_t I = 0, E = Func.Counts.size(); I < E; ++I)
627 FuncMax = std::max(FuncMax, Func.Counts[I]);
628
629 if (HottestFuncs.size() == TopN) {
630 if (HottestFuncs.top().second < FuncMax) {
631 HottestFuncs.pop();
632 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
633 }
634 } else
635 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
636 }
637
Justin Bogner9af28ef2014-03-21 17:29:44 +0000638 if (Show) {
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000639
Justin Bogner9af28ef2014-03-21 17:29:44 +0000640 if (!ShownFunctions)
641 OS << "Counters:\n";
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000642
Justin Bogner9af28ef2014-03-21 17:29:44 +0000643 ++ShownFunctions;
644
645 OS << " " << Func.Name << ":\n"
Justin Bogner423380f2014-03-23 20:43:50 +0000646 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
Rong Xu33c76c02016-02-10 17:18:30 +0000647 << " Counters: " << Func.Counts.size() << "\n";
648 if (!IsIRInstr)
649 OS << " Function count: " << Func.Counts[0] << "\n";
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000650
Justin Bogner9e9a0572015-09-29 22:13:58 +0000651 if (ShowIndirectCallTargets)
Xinliang David Li2004f002015-11-02 05:08:23 +0000652 OS << " Indirect Call Site Count: "
653 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
Justin Bogner9af28ef2014-03-21 17:29:44 +0000654
Rong Xu60faea12017-03-16 21:15:48 +0000655 uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
656 if (ShowMemOPSizes && NumMemOPCalls > 0)
657 OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
658 << "\n";
659
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000660 if (ShowCounts) {
661 OS << " Block counts: [";
Rong Xu33c76c02016-02-10 17:18:30 +0000662 size_t Start = (IsIRInstr ? 0 : 1);
663 for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
664 OS << (I == Start ? "" : ", ") << Func.Counts[I];
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000665 }
666 OS << "]\n";
667 }
Justin Bogner9e9a0572015-09-29 22:13:58 +0000668
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000669 if (ShowIndirectCallTargets) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000670 OS << " Indirect Target Results:\n";
671 traverseAllValueSites(Func, IPVK_IndirectCallTarget,
672 VPStats[IPVK_IndirectCallTarget], OS,
Rong Xu60faea12017-03-16 21:15:48 +0000673 &(Reader->getSymtab()));
674 }
675
676 if (ShowMemOPSizes && NumMemOPCalls > 0) {
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000677 OS << " Memory Intrinsic Size Results:\n";
Rong Xu60faea12017-03-16 21:15:48 +0000678 traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
679 nullptr);
Justin Bogner9e9a0572015-09-29 22:13:58 +0000680 }
681 }
Justin Bogner9af28ef2014-03-21 17:29:44 +0000682 }
Justin Bognerdb1225d2014-03-23 20:55:53 +0000683 if (Reader->hasError())
Vedant Kumar9152fd12016-05-19 03:54:45 +0000684 exitWithError(Reader->getError(), Filename);
Justin Bogner9af28ef2014-03-21 17:29:44 +0000685
Richard Smithc6ba9ca2018-08-24 01:34:45 +0000686 if (TextFormat)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000687 return 0;
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000688 std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
Adam Nemet1142b2d2017-11-14 16:59:18 +0000689 OS << "Instrumentation level: "
690 << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n";
Justin Bogner9af28ef2014-03-21 17:29:44 +0000691 if (ShowAllFunctions || !ShowFunction.empty())
692 OS << "Functions shown: " << ShownFunctions << "\n";
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000693 OS << "Total functions: " << PS->getNumFunctions() << "\n";
694 OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000695 OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
Rong Xu60faea12017-03-16 21:15:48 +0000696
Xinliang David Li801b5312017-07-11 20:30:43 +0000697 if (TopN) {
698 std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
699 while (!HottestFuncs.empty()) {
700 SortedHottestFuncs.emplace_back(HottestFuncs.top());
701 HottestFuncs.pop();
702 }
703 OS << "Top " << TopN
704 << " functions with the largest internal block counts: \n";
705 for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
706 OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
707 }
708
Xinliang David Li872362c2016-05-23 16:36:11 +0000709 if (ShownFunctions && ShowIndirectCallTargets) {
Rong Xu0cf1f562017-03-09 19:03:57 +0000710 OS << "Statistics for indirect call sites profile:\n";
711 showValueSitesStats(OS, IPVK_IndirectCallTarget,
712 VPStats[IPVK_IndirectCallTarget]);
Xinliang David Li872362c2016-05-23 16:36:11 +0000713 }
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000714
Rong Xu60faea12017-03-16 21:15:48 +0000715 if (ShownFunctions && ShowMemOPSizes) {
716 OS << "Statistics for memory intrinsic calls sizes profile:\n";
717 showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
718 }
719
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000720 if (ShowDetailedSummary) {
721 OS << "Detailed summary:\n";
Easwaran Raman7cefdb82016-05-19 21:53:28 +0000722 OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
Easwaran Ramane5a17e32016-05-19 21:07:12 +0000723 OS << "Total count: " << PS->getTotalCount() << "\n";
724 for (auto Entry : PS->getDetailedSummary()) {
Easwaran Raman43095702016-02-17 18:18:47 +0000725 OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000726 << " account for "
727 << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
728 << " percentage of the total counts.\n";
729 }
730 }
Justin Bogner9af28ef2014-03-21 17:29:44 +0000731 return 0;
732}
733
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000734static int showSampleProfile(const std::string &Filename, bool ShowCounts,
735 bool ShowAllFunctions,
736 const std::string &ShowFunction,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000737 raw_fd_ostream &OS) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000738 using namespace sampleprof;
Mehdi Amini03b42e42016-04-14 21:59:01 +0000739 LLVMContext Context;
740 auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
Diego Novillofcd55602014-11-03 00:51:45 +0000741 if (std::error_code EC = ReaderOrErr.getError())
Nathan Slingerland4f823662015-11-13 03:47:58 +0000742 exitWithErrorCode(EC, Filename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000743
Diego Novillofcd55602014-11-03 00:51:45 +0000744 auto Reader = std::move(ReaderOrErr.get());
Diego Novilloc6d032a2015-09-17 00:17:21 +0000745 if (std::error_code EC = Reader->read())
Nathan Slingerland4f823662015-11-13 03:47:58 +0000746 exitWithErrorCode(EC, Filename);
Diego Novilloc6d032a2015-09-17 00:17:21 +0000747
Diego Novillod5336ae2014-11-01 00:56:55 +0000748 if (ShowAllFunctions || ShowFunction.empty())
749 Reader->dump(OS);
750 else
751 Reader->dumpFunctionProfile(ShowFunction, OS);
752
753 return 0;
754}
755
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000756static int show_main(int argc, const char *argv[]) {
Diego Novillod5336ae2014-11-01 00:56:55 +0000757 cl::opt<std::string> Filename(cl::Positional, cl::Required,
758 cl::desc("<profdata-file>"));
759
760 cl::opt<bool> ShowCounts("counts", cl::init(false),
761 cl::desc("Show counter values for shown functions"));
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000762 cl::opt<bool> TextFormat(
763 "text", cl::init(false),
764 cl::desc("Show instr profile data in text dump format"));
Justin Bogner9e9a0572015-09-29 22:13:58 +0000765 cl::opt<bool> ShowIndirectCallTargets(
766 "ic-targets", cl::init(false),
767 cl::desc("Show indirect call site target values for shown functions"));
Rong Xu60faea12017-03-16 21:15:48 +0000768 cl::opt<bool> ShowMemOPSizes(
769 "memop-sizes", cl::init(false),
770 cl::desc("Show the profiled sizes of the memory intrinsic calls "
771 "for shown functions"));
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000772 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
773 cl::desc("Show detailed profile summary"));
774 cl::list<uint32_t> DetailedSummaryCutoffs(
775 cl::CommaSeparated, "detailed-summary-cutoffs",
776 cl::desc(
777 "Cutoff percentages (times 10000) for generating detailed summary"),
778 cl::value_desc("800000,901000,999999"));
Diego Novillod5336ae2014-11-01 00:56:55 +0000779 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
780 cl::desc("Details for every function"));
781 cl::opt<std::string> ShowFunction("function",
782 cl::desc("Details for matching functions"));
783
784 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
785 cl::init("-"), cl::desc("Output file"));
786 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
787 cl::aliasopt(OutputFilename));
788 cl::opt<ProfileKinds> ProfileKind(
789 cl::desc("Profile kind:"), cl::init(instr),
790 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000791 clEnumVal(sample, "Sample profile")));
Xinliang David Li801b5312017-07-11 20:30:43 +0000792 cl::opt<uint32_t> TopNFunctions(
793 "topn", cl::init(0),
794 cl::desc("Show the list of functions with the largest internal counts"));
Diego Novillod5336ae2014-11-01 00:56:55 +0000795
796 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
797
798 if (OutputFilename.empty())
799 OutputFilename = "-";
800
801 std::error_code EC;
802 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
803 if (EC)
Xinliang David Li6f7c19a2015-11-23 20:47:38 +0000804 exitWithErrorCode(EC, OutputFilename);
Diego Novillod5336ae2014-11-01 00:56:55 +0000805
806 if (ShowAllFunctions && !ShowFunction.empty())
Jonas Devliegheree46b7562018-04-18 14:42:33 +0000807 WithColor::warning() << "-function argument ignored: showing all functions\n";
Diego Novillod5336ae2014-11-01 00:56:55 +0000808
Easwaran Raman183ebbe2016-01-13 21:44:36 +0000809 std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(),
810 DetailedSummaryCutoffs.end());
Diego Novillod5336ae2014-11-01 00:56:55 +0000811 if (ProfileKind == instr)
Xinliang David Li801b5312017-07-11 20:30:43 +0000812 return showInstrProfile(Filename, ShowCounts, TopNFunctions,
813 ShowIndirectCallTargets, ShowMemOPSizes,
814 ShowDetailedSummary, DetailedSummaryCutoffs,
815 ShowAllFunctions, ShowFunction, TextFormat, OS);
Diego Novillod5336ae2014-11-01 00:56:55 +0000816 else
817 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
818 ShowFunction, OS);
819}
820
Justin Bogner618bcea2014-03-19 02:20:46 +0000821int main(int argc, const char *argv[]) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000822 InitLLVM X(argc, argv);
Justin Bogner618bcea2014-03-19 02:20:46 +0000823
824 StringRef ProgName(sys::path::filename(argv[0]));
825 if (argc > 1) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000826 int (*func)(int, const char *[]) = nullptr;
Justin Bogner618bcea2014-03-19 02:20:46 +0000827
828 if (strcmp(argv[1], "merge") == 0)
829 func = merge_main;
Justin Bogner9af28ef2014-03-21 17:29:44 +0000830 else if (strcmp(argv[1], "show") == 0)
831 func = show_main;
Justin Bogner618bcea2014-03-19 02:20:46 +0000832
833 if (func) {
834 std::string Invocation(ProgName.str() + " " + argv[1]);
835 argv[1] = Invocation.c_str();
836 return func(argc - 1, argv + 1);
837 }
838
Diego Novillod3babdb2015-12-14 20:37:15 +0000839 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
Justin Bogner618bcea2014-03-19 02:20:46 +0000840 strcmp(argv[1], "--help") == 0) {
841
842 errs() << "OVERVIEW: LLVM profile data tools\n\n"
843 << "USAGE: " << ProgName << " <command> [args...]\n"
844 << "USAGE: " << ProgName << " <command> -help\n\n"
Justin Bogner253eb172016-08-03 23:10:51 +0000845 << "See each individual command --help for more details.\n"
Justin Bogner9af28ef2014-03-21 17:29:44 +0000846 << "Available commands: merge, show\n";
Justin Bogner618bcea2014-03-19 02:20:46 +0000847 return 0;
848 }
849 }
850
851 if (argc < 2)
852 errs() << ProgName << ": No command specified!\n";
853 else
854 errs() << ProgName << ": Unknown command!\n";
855
Justin Bogner9af28ef2014-03-21 17:29:44 +0000856 errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
Justin Bogner618bcea2014-03-19 02:20:46 +0000857 return 1;
858}