blob: c25cbc2b64dfd3addf7a0e6944258f3f1847a904 [file] [log] [blame]
Duncan P. N. Exon Smithddc5a012014-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 Slingerland991a399f2015-11-18 17:10:24 +000014#include "llvm/ADT/SmallSet.h"
Nathan Slingerland824c3ec2015-12-15 17:37:09 +000015#include "llvm/ADT/SmallVector.h"
Duncan P. N. Exon Smithddc5a012014-02-17 23:22:49 +000016#include "llvm/ADT/StringRef.h"
Chandler Carruth1b279142015-01-14 11:23:27 +000017#include "llvm/IR/LLVMContext.h"
Justin Bognerc0f3b722014-03-21 17:24:48 +000018#include "llvm/ProfileData/InstrProfReader.h"
Justin Bogner496d7f62014-03-21 17:46:22 +000019#include "llvm/ProfileData/InstrProfWriter.h"
Easwaran Raman4bf45e82016-02-04 23:34:31 +000020#include "llvm/ProfileData/ProfileCommon.h"
Diego Novillo9657de5f2014-11-01 00:56:55 +000021#include "llvm/ProfileData/SampleProfReader.h"
22#include "llvm/ProfileData/SampleProfWriter.h"
Duncan P. N. Exon Smithddc5a012014-02-17 23:22:49 +000023#include "llvm/Support/CommandLine.h"
Nathan Slingerland824c3ec2015-12-15 17:37:09 +000024#include "llvm/Support/Errc.h"
Benjamin Kramer7259f142014-04-29 23:26:49 +000025#include "llvm/Support/FileSystem.h"
Justin Bogner5ecdfc12014-03-23 20:43:50 +000026#include "llvm/Support/Format.h"
Rui Ueyama0b9d56a2018-04-13 18:26:06 +000027#include "llvm/Support/InitLLVM.h"
Duncan P. N. Exon Smithddc5a012014-02-17 23:22:49 +000028#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramerdf93f4b2015-03-23 18:07:13 +000029#include "llvm/Support/Path.h"
Jonas Devlieghere331449e2018-04-18 14:42:33 +000030#include "llvm/Support/WithColor.h"
Vedant Kumard91d3782016-07-19 01:17:20 +000031#include "llvm/Support/ThreadPool.h"
Duncan P. N. Exon Smithddc5a012014-02-17 23:22:49 +000032#include "llvm/Support/raw_ostream.h"
Nathan Slingerland824c3ec2015-12-15 17:37:09 +000033#include <algorithm>
Duncan P. N. Exon Smithddc5a012014-02-17 23:22:49 +000034
35using namespace llvm;
36
Wei Mi93bc7462018-06-11 22:40:43 +000037enum ProfileFormat {
38 PF_None = 0,
39 PF_Text,
40 PF_Compact_Binary,
41 PF_GCC,
Wei Mi7253cd82018-06-12 05:53:49 +000042 PF_Binary
Wei Mi93bc7462018-06-11 22:40:43 +000043};
Xinliang David Li55f78332015-11-23 20:47:38 +000044
Jonas Devlieghere331449e2018-04-18 14:42:33 +000045static void warn(Twine Message, std::string Whence = "",
Vedant Kumarddb44a62017-11-17 21:18:32 +000046 std::string Hint = "") {
Jonas Devlieghere331449e2018-04-18 14:42:33 +000047 WithColor::warning();
Justin Bognerc0f3b722014-03-21 17:24:48 +000048 if (!Whence.empty())
49 errs() << Whence << ": ";
50 errs() << Message << "\n";
Nathan Slingerland572e6332015-11-13 03:47:58 +000051 if (!Hint.empty())
Jonas Devlieghere331449e2018-04-18 14:42:33 +000052 WithColor::note() << Hint << "\n";
Vedant Kumarddb44a62017-11-17 21:18:32 +000053}
54
55static void exitWithError(Twine Message, std::string Whence = "",
56 std::string Hint = "") {
Jonas Devlieghere331449e2018-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 Smithddc5a012014-02-17 23:22:49 +000063 ::exit(1);
64}
65
Vedant Kumarc77570e2016-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 Slingerland572e6332015-11-13 03:47:58 +000077 }
Vedant Kumarc77570e2016-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 Slingerland572e6332015-11-13 03:47:58 +000084}
85
Duncan P. N. Exon Smith4aee54e2015-06-16 00:43:04 +000086namespace {
Diego Novillo914ed192015-12-14 20:37:15 +000087enum ProfileKinds { instr, sample };
Duncan P. N. Exon Smith4aee54e2015-06-16 00:43:04 +000088}
Justin Bogner695043f2014-03-19 02:20:46 +000089
Vedant Kumarc77570e2016-05-19 03:54:45 +000090static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
Nathan Slingerland0833ccb2015-11-17 22:08:53 +000091 StringRef WhenceFunction = "",
Diego Novillo914ed192015-12-14 20:37:15 +000092 bool ShowHint = true) {
Nathan Slingerland0833ccb2015-11-17 22:08:53 +000093 if (!WhenceFile.empty())
94 errs() << WhenceFile << ": ";
95 if (!WhenceFunction.empty())
96 errs() << WhenceFunction << ": ";
Vedant Kumarc77570e2016-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 Slingerland0833ccb2015-11-17 22:08:53 +0000105
106 if (ShowHint) {
107 StringRef Hint = "";
Vedant Kumarc77570e2016-05-19 03:54:45 +0000108 if (IPE != instrprof_error::success) {
109 switch (IPE) {
Nathan Slingerland3d2c6fc2015-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 Novillo914ed192015-12-14 20:37:15 +0000113 Hint = "Make sure that all profile data to be merged is generated "
Nathan Slingerland0833ccb2015-11-17 22:08:53 +0000114 "from the same binary.";
Nathan Slingerland3d2c6fc2015-11-17 23:37:09 +0000115 break;
Nathan Slingerland9dcdf0d2015-11-18 00:52:45 +0000116 default:
117 break;
Nathan Slingerland0833ccb2015-11-17 22:08:53 +0000118 }
119 }
120
121 if (!Hint.empty())
122 errs() << Hint << "\n";
123 }
124}
125
Richard Smith61be1ad2018-09-13 20:22:02 +0000126namespace {
127/// A remapper from original symbol names to new symbol names based on a file
128/// containing a list of mappings from old name to new name.
129class SymbolRemapper {
130 std::unique_ptr<MemoryBuffer> File;
131 DenseMap<StringRef, StringRef> RemappingTable;
132
133public:
134 /// Build a SymbolRemapper from a file containing a list of old/new symbols.
135 static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
136 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
137 if (!BufOrError)
138 exitWithErrorCode(BufOrError.getError(), InputFile);
139
140 auto Remapper = llvm::make_unique<SymbolRemapper>();
141 Remapper->File = std::move(BufOrError.get());
142
143 for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
144 !LineIt.is_at_eof(); ++LineIt) {
145 std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
146 if (Parts.first.empty() || Parts.second.empty() ||
147 Parts.second.count(' ')) {
148 exitWithError("unexpected line in remapping file",
149 (InputFile + ":" + Twine(LineIt.line_number())).str(),
150 "expected 'old_symbol new_symbol'");
151 }
152 Remapper->RemappingTable.insert(Parts);
153 }
154 return Remapper;
155 }
156
157 /// Attempt to map the given old symbol into a new symbol.
158 ///
159 /// \return The new symbol, or \p Name if no such symbol was found.
160 StringRef operator()(StringRef Name) {
161 StringRef New = RemappingTable.lookup(Name);
162 return New.empty() ? Name : New;
163 }
164};
165}
166
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000167struct WeightedFile {
Xinliang David Li30a38832016-07-20 22:24:52 +0000168 std::string Filename;
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000169 uint64_t Weight;
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000170};
171typedef SmallVector<WeightedFile, 5> WeightedFileVector;
172
Vedant Kumard91d3782016-07-19 01:17:20 +0000173/// Keep track of merged data and reported errors.
174struct WriterContext {
175 std::mutex Lock;
176 InstrProfWriter Writer;
177 Error Err;
Vedant Kumar0ff70a62017-11-17 02:58:23 +0000178 std::string ErrWhence;
Vedant Kumard91d3782016-07-19 01:17:20 +0000179 std::mutex &ErrLock;
180 SmallSet<instrprof_error, 4> &WriterErrorCodes;
181
182 WriterContext(bool IsSparse, std::mutex &ErrLock,
183 SmallSet<instrprof_error, 4> &WriterErrorCodes)
184 : Lock(), Writer(IsSparse), Err(Error::success()), ErrWhence(""),
185 ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {}
186};
187
Vedant Kumarddb44a62017-11-17 21:18:32 +0000188/// Determine whether an error is fatal for profile merging.
189static bool isFatalError(instrprof_error IPE) {
190 switch (IPE) {
191 default:
192 return true;
193 case instrprof_error::success:
194 case instrprof_error::eof:
195 case instrprof_error::unknown_function:
196 case instrprof_error::hash_mismatch:
197 case instrprof_error::count_mismatch:
198 case instrprof_error::counter_overflow:
199 case instrprof_error::value_site_count_mismatch:
200 return false;
201 }
202}
203
Vedant Kumard91d3782016-07-19 01:17:20 +0000204/// Load an input into a writer context.
Richard Smith61be1ad2018-09-13 20:22:02 +0000205static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
206 WriterContext *WC) {
Vedant Kumard91d3782016-07-19 01:17:20 +0000207 std::unique_lock<std::mutex> CtxGuard{WC->Lock};
208
209 // If there's a pending hard error, don't do more work.
210 if (WC->Err)
211 return;
212
Vedant Kumar0ff70a62017-11-17 02:58:23 +0000213 // Copy the filename, because llvm::ThreadPool copied the input "const
214 // WeightedFile &" by value, making a reference to the filename within it
215 // invalid outside of this packaged task.
Vedant Kumard91d3782016-07-19 01:17:20 +0000216 WC->ErrWhence = Input.Filename;
217
218 auto ReaderOrErr = InstrProfReader::create(Input.Filename);
Rong Xuc8872302016-10-19 22:51:17 +0000219 if (Error E = ReaderOrErr.takeError()) {
220 // Skip the empty profiles by returning sliently.
221 instrprof_error IPE = InstrProfError::take(std::move(E));
222 if (IPE != instrprof_error::empty_raw_profile)
223 WC->Err = make_error<InstrProfError>(IPE);
Vedant Kumard91d3782016-07-19 01:17:20 +0000224 return;
Rong Xuc8872302016-10-19 22:51:17 +0000225 }
Vedant Kumard91d3782016-07-19 01:17:20 +0000226
227 auto Reader = std::move(ReaderOrErr.get());
228 bool IsIRProfile = Reader->isIRLevelProfile();
229 if (WC->Writer.setIsIRLevelProfile(IsIRProfile)) {
230 WC->Err = make_error<StringError>(
231 "Merge IR generated profile with Clang generated profile.",
232 std::error_code());
233 return;
234 }
235
236 for (auto &I : *Reader) {
Richard Smith61be1ad2018-09-13 20:22:02 +0000237 if (Remapper)
238 I.Name = (*Remapper)(I.Name);
Rong Xufa327ae2016-10-19 23:31:59 +0000239 const StringRef FuncName = I.Name;
David Blaikiecb160612017-07-10 03:04:59 +0000240 bool Reported = false;
241 WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
242 if (Reported) {
243 consumeError(std::move(E));
244 return;
245 }
246 Reported = true;
Vedant Kumard91d3782016-07-19 01:17:20 +0000247 // Only show hint the first time an error occurs.
248 instrprof_error IPE = InstrProfError::take(std::move(E));
249 std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
250 bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
251 handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
Rong Xufa327ae2016-10-19 23:31:59 +0000252 FuncName, firstTime);
David Blaikiecb160612017-07-10 03:04:59 +0000253 });
Vedant Kumard91d3782016-07-19 01:17:20 +0000254 }
Vedant Kumarddb44a62017-11-17 21:18:32 +0000255 if (Reader->hasError()) {
256 if (Error E = Reader->getError()) {
257 instrprof_error IPE = InstrProfError::take(std::move(E));
258 if (isFatalError(IPE))
259 WC->Err = make_error<InstrProfError>(IPE);
260 }
261 }
Vedant Kumard91d3782016-07-19 01:17:20 +0000262}
263
264/// Merge the \p Src writer context into \p Dst.
265static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
Vedant Kumar0ff70a62017-11-17 02:58:23 +0000266 // If we've already seen a hard error, continuing with the merge would
267 // clobber it.
268 if (Dst->Err || Src->Err)
269 return;
270
David Blaikiecb160612017-07-10 03:04:59 +0000271 bool Reported = false;
272 Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
273 if (Reported) {
274 consumeError(std::move(E));
275 return;
276 }
277 Reported = true;
Vedant Kumard91d3782016-07-19 01:17:20 +0000278 Dst->Err = std::move(E);
David Blaikiecb160612017-07-10 03:04:59 +0000279 });
Vedant Kumard91d3782016-07-19 01:17:20 +0000280}
281
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000282static void mergeInstrProfile(const WeightedFileVector &Inputs,
Richard Smith61be1ad2018-09-13 20:22:02 +0000283 SymbolRemapper *Remapper,
Xinliang David Li55f78332015-11-23 20:47:38 +0000284 StringRef OutputFilename,
Vedant Kumard91d3782016-07-19 01:17:20 +0000285 ProfileFormat OutputFormat, bool OutputSparse,
286 unsigned NumThreads) {
Justin Bognere153fb32014-04-18 21:48:40 +0000287 if (OutputFilename.compare("-") == 0)
288 exitWithError("Cannot write indexed profdata format to stdout.");
Justin Bognerefa94162014-03-12 22:00:57 +0000289
Wei Mi7253cd82018-06-12 05:53:49 +0000290 if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
Wei Mi93bc7462018-06-11 22:40:43 +0000291 OutputFormat != PF_Text)
Xinliang David Li55f78332015-11-23 20:47:38 +0000292 exitWithError("Unknown format is specified.");
293
Rafael Espindola8c968622014-08-25 18:16:47 +0000294 std::error_code EC;
295 raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None);
296 if (EC)
Nathan Slingerland572e6332015-11-13 03:47:58 +0000297 exitWithErrorCode(EC, OutputFilename);
Justin Bognerefa94162014-03-12 22:00:57 +0000298
Vedant Kumard91d3782016-07-19 01:17:20 +0000299 std::mutex ErrorLock;
Vedant Kumarc77570e2016-05-19 03:54:45 +0000300 SmallSet<instrprof_error, 4> WriterErrorCodes;
Justin Bognerc0f3b722014-03-21 17:24:48 +0000301
Vedant Kumard91d3782016-07-19 01:17:20 +0000302 // If NumThreads is not specified, auto-detect a good default.
303 if (NumThreads == 0)
Rafael Espindolaa72e2a92017-10-04 20:27:01 +0000304 NumThreads =
305 std::min(hardware_concurrency(), unsigned((Inputs.size() + 1) / 2));
Rong Xuc7d7fb02016-02-10 17:18:30 +0000306
Vedant Kumard91d3782016-07-19 01:17:20 +0000307 // Initialize the writer contexts.
308 SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
309 for (unsigned I = 0; I < NumThreads; ++I)
310 Contexts.emplace_back(llvm::make_unique<WriterContext>(
311 OutputSparse, ErrorLock, WriterErrorCodes));
312
313 if (NumThreads == 1) {
314 for (const auto &Input : Inputs)
Richard Smith61be1ad2018-09-13 20:22:02 +0000315 loadInput(Input, Remapper, Contexts[0].get());
Vedant Kumard91d3782016-07-19 01:17:20 +0000316 } else {
317 ThreadPool Pool(NumThreads);
318
319 // Load the inputs in parallel (N/NumThreads serial steps).
320 unsigned Ctx = 0;
321 for (const auto &Input : Inputs) {
Richard Smith61be1ad2018-09-13 20:22:02 +0000322 Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
Vedant Kumard91d3782016-07-19 01:17:20 +0000323 Ctx = (Ctx + 1) % NumThreads;
Nathan Slingerland0833ccb2015-11-17 22:08:53 +0000324 }
Vedant Kumard91d3782016-07-19 01:17:20 +0000325 Pool.wait();
326
327 // Merge the writer contexts together (~ lg(NumThreads) serial steps).
328 unsigned Mid = Contexts.size() / 2;
329 unsigned End = Contexts.size();
330 assert(Mid > 0 && "Expected more than one context");
331 do {
332 for (unsigned I = 0; I < Mid; ++I)
333 Pool.async(mergeWriterContexts, Contexts[I].get(),
334 Contexts[I + Mid].get());
335 Pool.wait();
336 if (End & 1) {
337 Pool.async(mergeWriterContexts, Contexts[0].get(),
338 Contexts[End - 1].get());
339 Pool.wait();
340 }
341 End = Mid;
342 Mid /= 2;
343 } while (Mid > 0);
Justin Bogner4207c672014-03-12 20:14:17 +0000344 }
Vedant Kumard91d3782016-07-19 01:17:20 +0000345
346 // Handle deferred hard errors encountered during merging.
Vedant Kumarddb44a62017-11-17 21:18:32 +0000347 for (std::unique_ptr<WriterContext> &WC : Contexts) {
348 if (!WC->Err)
349 continue;
350 if (!WC->Err.isA<InstrProfError>())
Vedant Kumard91d3782016-07-19 01:17:20 +0000351 exitWithError(std::move(WC->Err), WC->ErrWhence);
352
Vedant Kumarddb44a62017-11-17 21:18:32 +0000353 instrprof_error IPE = InstrProfError::take(std::move(WC->Err));
354 if (isFatalError(IPE))
355 exitWithError(make_error<InstrProfError>(IPE), WC->ErrWhence);
356 else
Jonas Devlieghere331449e2018-04-18 14:42:33 +0000357 warn(toString(make_error<InstrProfError>(IPE)),
Vedant Kumarddb44a62017-11-17 21:18:32 +0000358 WC->ErrWhence);
359 }
360
Vedant Kumard91d3782016-07-19 01:17:20 +0000361 InstrProfWriter &Writer = Contexts[0]->Writer;
Vedant Kumarb9454632017-06-20 01:38:56 +0000362 if (OutputFormat == PF_Text) {
363 if (Error E = Writer.writeText(Output))
364 exitWithError(std::move(E));
365 } else {
Xinliang David Li55f78332015-11-23 20:47:38 +0000366 Writer.write(Output);
Vedant Kumarb9454632017-06-20 01:38:56 +0000367 }
Diego Novillo9657de5f2014-11-01 00:56:55 +0000368}
369
Richard Smith61be1ad2018-09-13 20:22:02 +0000370/// Make a copy of the given function samples with all symbol names remapped
371/// by the provided symbol remapper.
372static sampleprof::FunctionSamples
373remapSamples(const sampleprof::FunctionSamples &Samples,
374 SymbolRemapper &Remapper, sampleprof_error &Error) {
375 sampleprof::FunctionSamples Result;
376 Result.setName(Remapper(Samples.getName()));
377 Result.addTotalSamples(Samples.getTotalSamples());
378 Result.addHeadSamples(Samples.getHeadSamples());
379 for (const auto &BodySample : Samples.getBodySamples()) {
380 Result.addBodySamples(BodySample.first.LineOffset,
381 BodySample.first.Discriminator,
382 BodySample.second.getSamples());
383 for (const auto &Target : BodySample.second.getCallTargets()) {
384 Result.addCalledTargetSamples(BodySample.first.LineOffset,
385 BodySample.first.Discriminator,
386 Remapper(Target.first()), Target.second);
387 }
388 }
389 for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
390 sampleprof::FunctionSamplesMap &Target =
391 Result.functionSamplesAt(CallsiteSamples.first);
392 for (const auto &Callsite : CallsiteSamples.second) {
393 sampleprof::FunctionSamples Remapped =
394 remapSamples(Callsite.second, Remapper, Error);
395 MergeResult(Error, Target[Remapped.getName()].merge(Remapped));
396 }
397 }
398 return Result;
399}
400
Xinliang David Li55f78332015-11-23 20:47:38 +0000401static sampleprof::SampleProfileFormat FormatMap[] = {
Wei Mi93bc7462018-06-11 22:40:43 +0000402 sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Compact_Binary,
Wei Mi7253cd82018-06-12 05:53:49 +0000403 sampleprof::SPF_GCC, sampleprof::SPF_Binary};
Xinliang David Li55f78332015-11-23 20:47:38 +0000404
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000405static void mergeSampleProfile(const WeightedFileVector &Inputs,
Richard Smith61be1ad2018-09-13 20:22:02 +0000406 SymbolRemapper *Remapper,
Benjamin Kramer0df4e222015-03-09 16:23:46 +0000407 StringRef OutputFilename,
Xinliang David Li55f78332015-11-23 20:47:38 +0000408 ProfileFormat OutputFormat) {
Diego Novillo9657de5f2014-11-01 00:56:55 +0000409 using namespace sampleprof;
Xinliang David Li55f78332015-11-23 20:47:38 +0000410 auto WriterOrErr =
411 SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
Diego Novillo2b6bd7a2014-11-03 00:51:45 +0000412 if (std::error_code EC = WriterOrErr.getError())
Nathan Slingerland572e6332015-11-13 03:47:58 +0000413 exitWithErrorCode(EC, OutputFilename);
Diego Novillo9657de5f2014-11-01 00:56:55 +0000414
Diego Novillo2b6bd7a2014-11-03 00:51:45 +0000415 auto Writer = std::move(WriterOrErr.get());
Diego Novillo9657de5f2014-11-01 00:56:55 +0000416 StringMap<FunctionSamples> ProfileMap;
Diego Novillo3bc8dc32015-10-08 19:40:37 +0000417 SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
Mehdi Amini8be77072016-04-14 21:59:01 +0000418 LLVMContext Context;
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000419 for (const auto &Input : Inputs) {
Mehdi Amini8be77072016-04-14 21:59:01 +0000420 auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
Diego Novillo2b6bd7a2014-11-03 00:51:45 +0000421 if (std::error_code EC = ReaderOrErr.getError())
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000422 exitWithErrorCode(EC, Input.Filename);
Diego Novillo9657de5f2014-11-01 00:56:55 +0000423
Diego Novillo3bc8dc32015-10-08 19:40:37 +0000424 // We need to keep the readers around until after all the files are
425 // read so that we do not lose the function names stored in each
426 // reader's memory. The function names are needed to write out the
427 // merged profile map.
428 Readers.push_back(std::move(ReaderOrErr.get()));
429 const auto Reader = Readers.back().get();
Diego Novillo9657de5f2014-11-01 00:56:55 +0000430 if (std::error_code EC = Reader->read())
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000431 exitWithErrorCode(EC, Input.Filename);
Diego Novillo9657de5f2014-11-01 00:56:55 +0000432
433 StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
434 for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
435 E = Profiles.end();
436 I != E; ++I) {
Richard Smith61be1ad2018-09-13 20:22:02 +0000437 sampleprof_error Result = sampleprof_error::success;
438 FunctionSamples Remapped =
439 Remapper ? remapSamples(I->second, *Remapper, Result)
440 : FunctionSamples();
441 FunctionSamples &Samples = Remapper ? Remapped : I->second;
442 StringRef FName = Samples.getName();
443 MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
Nathan Slingerlandfd568242015-12-16 21:45:43 +0000444 if (Result != sampleprof_error::success) {
445 std::error_code EC = make_error_code(Result);
Vedant Kumarc77570e2016-05-19 03:54:45 +0000446 handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
Nathan Slingerlandfd568242015-12-16 21:45:43 +0000447 }
Diego Novillo9657de5f2014-11-01 00:56:55 +0000448 }
449 }
450 Writer->write(ProfileMap);
451}
452
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000453static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
Vedant Kumar43331642016-06-06 23:43:56 +0000454 StringRef WeightStr, FileName;
455 std::tie(WeightStr, FileName) = WeightedFilename.split(',');
Diego Novillo9657de5f2014-11-01 00:56:55 +0000456
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000457 uint64_t Weight;
458 if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
459 exitWithError("Input weight must be a positive integer.");
460
Benjamin Kramerd31d3eb2016-07-21 14:29:11 +0000461 return {FileName, Weight};
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000462}
463
Vedant Kumar19240402016-06-07 22:47:31 +0000464static std::unique_ptr<MemoryBuffer>
465getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) {
466 if (InputFilenamesFile == "")
467 return {};
468
469 auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile);
470 if (!BufOrError)
471 exitWithErrorCode(BufOrError.getError(), InputFilenamesFile);
472
473 return std::move(*BufOrError);
474}
475
Xinliang David Li30a38832016-07-20 22:24:52 +0000476static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
477 StringRef Filename = WF.Filename;
478 uint64_t Weight = WF.Weight;
Benjamin Kramer3d6f5132016-07-22 12:39:55 +0000479
480 // If it's STDIN just pass it on.
481 if (Filename == "-") {
482 WNI.push_back({Filename, Weight});
483 return;
484 }
485
Xinliang David Li30a38832016-07-20 22:24:52 +0000486 llvm::sys::fs::file_status Status;
487 llvm::sys::fs::status(Filename, Status);
488 if (!llvm::sys::fs::exists(Status))
489 exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
490 Filename);
491 // If it's a source file, collect it.
492 if (llvm::sys::fs::is_regular_file(Status)) {
Benjamin Kramerd31d3eb2016-07-21 14:29:11 +0000493 WNI.push_back({Filename, Weight});
Xinliang David Li30a38832016-07-20 22:24:52 +0000494 return;
495 }
496
497 if (llvm::sys::fs::is_directory(Status)) {
498 std::error_code EC;
499 for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
500 F != E && !EC; F.increment(EC)) {
501 if (llvm::sys::fs::is_regular_file(F->path())) {
502 addWeightedInput(WNI, {F->path(), Weight});
503 }
504 }
505 if (EC)
506 exitWithErrorCode(EC, Filename);
507 }
508}
509
Vedant Kumar19240402016-06-07 22:47:31 +0000510static void parseInputFilenamesFile(MemoryBuffer *Buffer,
511 WeightedFileVector &WFV) {
512 if (!Buffer)
513 return;
514
515 SmallVector<StringRef, 8> Entries;
516 StringRef Data = Buffer->getBuffer();
517 Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
518 for (const StringRef &FileWeightEntry : Entries) {
519 StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
520 // Skip comments.
521 if (SanitizedEntry.startswith("#"))
522 continue;
523 // If there's no comma, it's an unweighted profile.
524 else if (SanitizedEntry.find(',') == StringRef::npos)
Xinliang David Li30a38832016-07-20 22:24:52 +0000525 addWeightedInput(WFV, {SanitizedEntry, 1});
Vedant Kumar19240402016-06-07 22:47:31 +0000526 else
Xinliang David Li30a38832016-07-20 22:24:52 +0000527 addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
Vedant Kumar19240402016-06-07 22:47:31 +0000528 }
529}
530
Nathan Slingerland824c3ec2015-12-15 17:37:09 +0000531static int merge_main(int argc, const char *argv[]) {
532 cl::list<std::string> InputFilenames(cl::Positional,
533 cl::desc("<filename...>"));
534 cl::list<std::string> WeightedInputFilenames("weighted-input",
535 cl::desc("<weight>,<filename>"));
Vedant Kumar19240402016-06-07 22:47:31 +0000536 cl::opt<std::string> InputFilenamesFile(
537 "input-files", cl::init(""),
538 cl::desc("Path to file containing newline-separated "
539 "[<weight>,]<filename> entries"));
540 cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
541 cl::aliasopt(InputFilenamesFile));
542 cl::opt<bool> DumpInputFileList(
543 "dump-input-file-list", cl::init(false), cl::Hidden,
544 cl::desc("Dump the list of input files and their weights, then exit"));
Richard Smith61be1ad2018-09-13 20:22:02 +0000545 cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
546 cl::desc("Symbol remapping file"));
547 cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
548 cl::aliasopt(RemappingFile));
Diego Novillo9657de5f2014-11-01 00:56:55 +0000549 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
550 cl::init("-"), cl::Required,
551 cl::desc("Output file"));
552 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
553 cl::aliasopt(OutputFilename));
554 cl::opt<ProfileKinds> ProfileKind(
555 cl::desc("Profile kind:"), cl::init(instr),
556 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini3ffe1132016-10-08 19:41:06 +0000557 clEnumVal(sample, "Sample profile")));
Xinliang David Li55f78332015-11-23 20:47:38 +0000558 cl::opt<ProfileFormat> OutputFormat(
Wei Mi7253cd82018-06-12 05:53:49 +0000559 cl::desc("Format of output profile"), cl::init(PF_Binary),
560 cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
561 clEnumValN(PF_Compact_Binary, "compbinary",
562 "Compact binary encoding"),
563 clEnumValN(PF_Text, "text", "Text encoding"),
564 clEnumValN(PF_GCC, "gcc",
565 "GCC encoding (only meaningful for -sample)")));
Vedant Kumar0c94d7d2016-01-29 22:54:45 +0000566 cl::opt<bool> OutputSparse("sparse", cl::init(false),
567 cl::desc("Generate a sparse profile (only meaningful for -instr)"));
Vedant Kumard91d3782016-07-19 01:17:20 +0000568 cl::opt<unsigned> NumThreads(
569 "num-threads", cl::init(0),
570 cl::desc("Number of merge threads to use (default: autodetect)"));
571 cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
572 cl::aliasopt(NumThreads));
Vedant Kumar0c94d7d2016-01-29 22:54:45 +0000573
Diego Novillo9657de5f2014-11-01 00:56:55 +0000574 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
575
Vedant Kumar19240402016-06-07 22:47:31 +0000576 WeightedFileVector WeightedInputs;
577 for (StringRef Filename : InputFilenames)
Xinliang David Li30a38832016-07-20 22:24:52 +0000578 addWeightedInput(WeightedInputs, {Filename, 1});
Vedant Kumar19240402016-06-07 22:47:31 +0000579 for (StringRef WeightedFilename : WeightedInputFilenames)
Xinliang David Li30a38832016-07-20 22:24:52 +0000580 addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
Vedant Kumar19240402016-06-07 22:47:31 +0000581
582 // Make sure that the file buffer stays alive for the duration of the
583 // weighted input vector's lifetime.
584 auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile);
585 parseInputFilenamesFile(Buffer.get(), WeightedInputs);
586
587 if (WeightedInputs.empty())
Chandler Carruth557c6242016-06-04 03:08:01 +0000588 exitWithError("No input files specified. See " +
589 sys::path::filename(argv[0]) + " -help");
590
Vedant Kumar19240402016-06-07 22:47:31 +0000591 if (DumpInputFileList) {
592 for (auto &WF : WeightedInputs)
593 outs() << WF.Weight << "," << WF.Filename << "\n";
594 return 0;
595 }
Vedant Kumarae736272016-06-04 00:36:28 +0000596
Richard Smith61be1ad2018-09-13 20:22:02 +0000597 std::unique_ptr<SymbolRemapper> Remapper;
598 if (!RemappingFile.empty())
599 Remapper = SymbolRemapper::create(RemappingFile);
600
Diego Novillo9657de5f2014-11-01 00:56:55 +0000601 if (ProfileKind == instr)
Richard Smith61be1ad2018-09-13 20:22:02 +0000602 mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
603 OutputFormat, OutputSparse, NumThreads);
Diego Novillo9657de5f2014-11-01 00:56:55 +0000604 else
Richard Smith61be1ad2018-09-13 20:22:02 +0000605 mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
606 OutputFormat);
Justin Bogner4207c672014-03-12 20:14:17 +0000607
Justin Bognerefa94162014-03-12 22:00:57 +0000608 return 0;
Justin Bogner4207c672014-03-12 20:14:17 +0000609}
Justin Bogner695043f2014-03-19 02:20:46 +0000610
Rong Xufbfbf062017-03-09 19:03:57 +0000611typedef struct ValueSitesStats {
612 ValueSitesStats()
613 : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
614 TotalNumValues(0) {}
615 uint64_t TotalNumValueSites;
616 uint64_t TotalNumValueSitesWithValueProfile;
617 uint64_t TotalNumValues;
618 std::vector<unsigned> ValueSitesHistogram;
619} ValueSitesStats;
620
621static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
622 ValueSitesStats &Stats, raw_fd_ostream &OS,
Rong Xu6f00c7b2017-03-16 21:15:48 +0000623 InstrProfSymtab *Symtab) {
Rong Xufbfbf062017-03-09 19:03:57 +0000624 uint32_t NS = Func.getNumValueSites(VK);
625 Stats.TotalNumValueSites += NS;
626 for (size_t I = 0; I < NS; ++I) {
627 uint32_t NV = Func.getNumValueDataForSite(VK, I);
628 std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
629 Stats.TotalNumValues += NV;
630 if (NV) {
631 Stats.TotalNumValueSitesWithValueProfile++;
632 if (NV > Stats.ValueSitesHistogram.size())
633 Stats.ValueSitesHistogram.resize(NV, 0);
634 Stats.ValueSitesHistogram[NV - 1]++;
635 }
Rong Xuc445cab2019-01-08 22:41:48 +0000636
637 uint64_t SiteSum = 0;
638 for (uint32_t V = 0; V < NV; V++)
639 SiteSum += VD[V].Count;
640 if (SiteSum == 0)
641 SiteSum = 1;
642
Rong Xufbfbf062017-03-09 19:03:57 +0000643 for (uint32_t V = 0; V < NV; V++) {
Rong Xuc445cab2019-01-08 22:41:48 +0000644 OS << "\t[ " << format("%2u", I) << ", ";
Rong Xu6f00c7b2017-03-16 21:15:48 +0000645 if (Symtab == nullptr)
Rong Xuc445cab2019-01-08 22:41:48 +0000646 OS << format("%4u", VD[V].Value);
Rong Xu6f00c7b2017-03-16 21:15:48 +0000647 else
648 OS << Symtab->getFuncName(VD[V].Value);
Rong Xuc445cab2019-01-08 22:41:48 +0000649 OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
650 << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
Rong Xufbfbf062017-03-09 19:03:57 +0000651 }
652 }
653}
654
655static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
656 ValueSitesStats &Stats) {
657 OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
658 OS << " Total number of sites with values: "
659 << Stats.TotalNumValueSitesWithValueProfile << "\n";
660 OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
661
662 OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
663 for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
664 if (Stats.ValueSitesHistogram[I] > 0)
665 OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
666 }
667}
668
Benjamin Kramere5eb6732016-06-17 20:41:14 +0000669static int showInstrProfile(const std::string &Filename, bool ShowCounts,
Xinliang David Lidcb98bd2017-07-11 20:30:43 +0000670 uint32_t TopN, bool ShowIndirectCallTargets,
671 bool ShowMemOPSizes, bool ShowDetailedSummary,
Easwaran Ramanfa283c32016-01-13 21:44:36 +0000672 std::vector<uint32_t> DetailedSummaryCutoffs,
Rong Xuc445cab2019-01-08 22:41:48 +0000673 bool ShowAllFunctions, uint64_t ValueCutoff,
674 bool OnlyListBelow, const std::string &ShowFunction,
675 bool TextFormat, raw_fd_ostream &OS) {
Diego Novillo2b6bd7a2014-11-03 00:51:45 +0000676 auto ReaderOrErr = InstrProfReader::create(Filename);
Benjamin Kramere5eb6732016-06-17 20:41:14 +0000677 std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
678 if (ShowDetailedSummary && Cutoffs.empty()) {
Easwaran Ramanfa283c32016-01-13 21:44:36 +0000679 Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
680 }
Benjamin Kramere5eb6732016-06-17 20:41:14 +0000681 InstrProfSummaryBuilder Builder(std::move(Cutoffs));
Vedant Kumarc77570e2016-05-19 03:54:45 +0000682 if (Error E = ReaderOrErr.takeError())
683 exitWithError(std::move(E), Filename);
Justin Bogner60bc9062014-03-21 17:29:44 +0000684
Diego Novillo2b6bd7a2014-11-03 00:51:45 +0000685 auto Reader = std::move(ReaderOrErr.get());
Rong Xuc7d7fb02016-02-10 17:18:30 +0000686 bool IsIRInstr = Reader->isIRLevelProfile();
Easwaran Ramanfa283c32016-01-13 21:44:36 +0000687 size_t ShownFunctions = 0;
Rong Xuc445cab2019-01-08 22:41:48 +0000688 size_t BelowCutoffFunctions = 0;
Rong Xufbfbf062017-03-09 19:03:57 +0000689 int NumVPKind = IPVK_Last - IPVK_First + 1;
690 std::vector<ValueSitesStats> VPStats(NumVPKind);
Xinliang David Lidcb98bd2017-07-11 20:30:43 +0000691
692 auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
693 const std::pair<std::string, uint64_t> &v2) {
694 return v1.second > v2.second;
695 };
696
697 std::priority_queue<std::pair<std::string, uint64_t>,
698 std::vector<std::pair<std::string, uint64_t>>,
699 decltype(MinCmp)>
700 HottestFuncs(MinCmp);
701
Rong Xuc445cab2019-01-08 22:41:48 +0000702 if (!TextFormat && OnlyListBelow) {
703 OS << "The list of functions with the maximum counter less than "
704 << ValueCutoff << ":\n";
705 }
706
Richard Smitha11014c2018-08-24 01:34:45 +0000707 // Add marker so that IR-level instrumentation round-trips properly.
708 if (TextFormat && IsIRInstr)
709 OS << ":ir\n";
710
Justin Bogner60bc9062014-03-21 17:29:44 +0000711 for (const auto &Func : *Reader) {
Diego Novillo9657de5f2014-11-01 00:56:55 +0000712 bool Show =
713 ShowAllFunctions || (!ShowFunction.empty() &&
714 Func.Name.find(ShowFunction) != Func.Name.npos);
Justin Bogner60bc9062014-03-21 17:29:44 +0000715
Richard Smitha11014c2018-08-24 01:34:45 +0000716 bool doTextFormatDump = (Show && TextFormat);
Xinliang David Li55f78332015-11-23 20:47:38 +0000717
718 if (doTextFormatDump) {
Xinliang David Licfbaf112015-12-20 06:22:13 +0000719 InstrProfSymtab &Symtab = Reader->getSymtab();
David Blaikie450ef2a2017-07-06 19:00:12 +0000720 InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
721 OS);
Xinliang David Li55f78332015-11-23 20:47:38 +0000722 continue;
723 }
724
Justin Bogner38ac7e92014-04-25 02:45:33 +0000725 assert(Func.Counts.size() > 0 && "function missing entry counter");
Easwaran Raman17e7f1192016-05-19 21:07:12 +0000726 Builder.addRecord(Func);
Xinliang David Li55f78332015-11-23 20:47:38 +0000727
Rong Xuc445cab2019-01-08 22:41:48 +0000728 uint64_t FuncMax = 0;
729 uint64_t FuncSum = 0;
730 for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
731 FuncMax = std::max(FuncMax, Func.Counts[I]);
732 FuncSum += Func.Counts[I];
733 }
Rong Xu5f281ed2019-01-08 22:37:12 +0000734
Rong Xuc445cab2019-01-08 22:41:48 +0000735 if (FuncMax < ValueCutoff) {
736 ++BelowCutoffFunctions;
737 if (OnlyListBelow) {
738 OS << " " << Func.Name << ": (Max = " << FuncMax
739 << " Sum = " << FuncSum << ")\n";
740 }
741 continue;
742 } else if (OnlyListBelow)
743 continue;
744
745 if (TopN) {
Xinliang David Lidcb98bd2017-07-11 20:30:43 +0000746 if (HottestFuncs.size() == TopN) {
747 if (HottestFuncs.top().second < FuncMax) {
748 HottestFuncs.pop();
749 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
750 }
751 } else
752 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
753 }
754
Justin Bogner60bc9062014-03-21 17:29:44 +0000755 if (Show) {
756 if (!ShownFunctions)
757 OS << "Counters:\n";
Xinliang David Li55f78332015-11-23 20:47:38 +0000758
Justin Bogner60bc9062014-03-21 17:29:44 +0000759 ++ShownFunctions;
760
761 OS << " " << Func.Name << ":\n"
Justin Bogner5ecdfc12014-03-23 20:43:50 +0000762 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
Rong Xuc7d7fb02016-02-10 17:18:30 +0000763 << " Counters: " << Func.Counts.size() << "\n";
764 if (!IsIRInstr)
765 OS << " Function count: " << Func.Counts[0] << "\n";
Xinliang David Li55f78332015-11-23 20:47:38 +0000766
Justin Bognerc96f87a2015-09-29 22:13:58 +0000767 if (ShowIndirectCallTargets)
Xinliang David Li61c7e682015-11-02 05:08:23 +0000768 OS << " Indirect Call Site Count: "
769 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
Justin Bogner60bc9062014-03-21 17:29:44 +0000770
Rong Xu6f00c7b2017-03-16 21:15:48 +0000771 uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
772 if (ShowMemOPSizes && NumMemOPCalls > 0)
773 OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
774 << "\n";
775
Xinliang David Li55f78332015-11-23 20:47:38 +0000776 if (ShowCounts) {
777 OS << " Block counts: [";
Rong Xuc7d7fb02016-02-10 17:18:30 +0000778 size_t Start = (IsIRInstr ? 0 : 1);
779 for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
780 OS << (I == Start ? "" : ", ") << Func.Counts[I];
Xinliang David Li55f78332015-11-23 20:47:38 +0000781 }
782 OS << "]\n";
783 }
Justin Bognerc96f87a2015-09-29 22:13:58 +0000784
Xinliang David Li55f78332015-11-23 20:47:38 +0000785 if (ShowIndirectCallTargets) {
Rong Xufbfbf062017-03-09 19:03:57 +0000786 OS << " Indirect Target Results:\n";
787 traverseAllValueSites(Func, IPVK_IndirectCallTarget,
788 VPStats[IPVK_IndirectCallTarget], OS,
Rong Xu6f00c7b2017-03-16 21:15:48 +0000789 &(Reader->getSymtab()));
790 }
791
792 if (ShowMemOPSizes && NumMemOPCalls > 0) {
Teresa Johnson4c833e22017-05-24 17:55:25 +0000793 OS << " Memory Intrinsic Size Results:\n";
Rong Xu6f00c7b2017-03-16 21:15:48 +0000794 traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
795 nullptr);
Justin Bognerc96f87a2015-09-29 22:13:58 +0000796 }
797 }
Justin Bogner60bc9062014-03-21 17:29:44 +0000798 }
Justin Bognerf5afb782014-03-23 20:55:53 +0000799 if (Reader->hasError())
Vedant Kumarc77570e2016-05-19 03:54:45 +0000800 exitWithError(Reader->getError(), Filename);
Justin Bogner60bc9062014-03-21 17:29:44 +0000801
Richard Smitha11014c2018-08-24 01:34:45 +0000802 if (TextFormat)
Xinliang David Li55f78332015-11-23 20:47:38 +0000803 return 0;
Easwaran Raman30c760d2016-05-19 21:53:28 +0000804 std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
Adam Nemetd90634b2017-11-14 16:59:18 +0000805 OS << "Instrumentation level: "
806 << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n";
Justin Bogner60bc9062014-03-21 17:29:44 +0000807 if (ShowAllFunctions || !ShowFunction.empty())
808 OS << "Functions shown: " << ShownFunctions << "\n";
Easwaran Raman17e7f1192016-05-19 21:07:12 +0000809 OS << "Total functions: " << PS->getNumFunctions() << "\n";
Rong Xuc445cab2019-01-08 22:41:48 +0000810 if (ValueCutoff > 0) {
811 OS << "Number of functions with maximum count (< " << ValueCutoff
812 << "): " << BelowCutoffFunctions << "\n";
813 OS << "Number of functions with maximum count (>= " << ValueCutoff
814 << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
815 }
Easwaran Raman17e7f1192016-05-19 21:07:12 +0000816 OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
Easwaran Raman30c760d2016-05-19 21:53:28 +0000817 OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
Rong Xu6f00c7b2017-03-16 21:15:48 +0000818
Xinliang David Lidcb98bd2017-07-11 20:30:43 +0000819 if (TopN) {
820 std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
821 while (!HottestFuncs.empty()) {
822 SortedHottestFuncs.emplace_back(HottestFuncs.top());
823 HottestFuncs.pop();
824 }
825 OS << "Top " << TopN
826 << " functions with the largest internal block counts: \n";
827 for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
828 OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
829 }
830
Xinliang David Li1386ead2016-05-23 16:36:11 +0000831 if (ShownFunctions && ShowIndirectCallTargets) {
Rong Xufbfbf062017-03-09 19:03:57 +0000832 OS << "Statistics for indirect call sites profile:\n";
833 showValueSitesStats(OS, IPVK_IndirectCallTarget,
834 VPStats[IPVK_IndirectCallTarget]);
Xinliang David Li1386ead2016-05-23 16:36:11 +0000835 }
Easwaran Ramanfa283c32016-01-13 21:44:36 +0000836
Rong Xu6f00c7b2017-03-16 21:15:48 +0000837 if (ShownFunctions && ShowMemOPSizes) {
838 OS << "Statistics for memory intrinsic calls sizes profile:\n";
839 showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
840 }
841
Easwaran Ramanfa283c32016-01-13 21:44:36 +0000842 if (ShowDetailedSummary) {
843 OS << "Detailed summary:\n";
Easwaran Raman30c760d2016-05-19 21:53:28 +0000844 OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
Easwaran Raman17e7f1192016-05-19 21:07:12 +0000845 OS << "Total count: " << PS->getTotalCount() << "\n";
846 for (auto Entry : PS->getDetailedSummary()) {
Easwaran Raman233e7d32016-02-17 18:18:47 +0000847 OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
Easwaran Ramanfa283c32016-01-13 21:44:36 +0000848 << " account for "
849 << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
850 << " percentage of the total counts.\n";
851 }
852 }
Justin Bogner60bc9062014-03-21 17:29:44 +0000853 return 0;
854}
855
Benjamin Kramere5eb6732016-06-17 20:41:14 +0000856static int showSampleProfile(const std::string &Filename, bool ShowCounts,
857 bool ShowAllFunctions,
858 const std::string &ShowFunction,
Benjamin Kramer0df4e222015-03-09 16:23:46 +0000859 raw_fd_ostream &OS) {
Diego Novillo9657de5f2014-11-01 00:56:55 +0000860 using namespace sampleprof;
Mehdi Amini8be77072016-04-14 21:59:01 +0000861 LLVMContext Context;
862 auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
Diego Novillo2b6bd7a2014-11-03 00:51:45 +0000863 if (std::error_code EC = ReaderOrErr.getError())
Nathan Slingerland572e6332015-11-13 03:47:58 +0000864 exitWithErrorCode(EC, Filename);
Diego Novillo9657de5f2014-11-01 00:56:55 +0000865
Diego Novillo2b6bd7a2014-11-03 00:51:45 +0000866 auto Reader = std::move(ReaderOrErr.get());
Diego Novillo1e5eaad2015-09-17 00:17:21 +0000867 if (std::error_code EC = Reader->read())
Nathan Slingerland572e6332015-11-13 03:47:58 +0000868 exitWithErrorCode(EC, Filename);
Diego Novillo1e5eaad2015-09-17 00:17:21 +0000869
Diego Novillo9657de5f2014-11-01 00:56:55 +0000870 if (ShowAllFunctions || ShowFunction.empty())
871 Reader->dump(OS);
872 else
873 Reader->dumpFunctionProfile(ShowFunction, OS);
874
875 return 0;
876}
877
Benjamin Kramer0df4e222015-03-09 16:23:46 +0000878static int show_main(int argc, const char *argv[]) {
Diego Novillo9657de5f2014-11-01 00:56:55 +0000879 cl::opt<std::string> Filename(cl::Positional, cl::Required,
880 cl::desc("<profdata-file>"));
881
882 cl::opt<bool> ShowCounts("counts", cl::init(false),
883 cl::desc("Show counter values for shown functions"));
Xinliang David Li55f78332015-11-23 20:47:38 +0000884 cl::opt<bool> TextFormat(
885 "text", cl::init(false),
886 cl::desc("Show instr profile data in text dump format"));
Justin Bognerc96f87a2015-09-29 22:13:58 +0000887 cl::opt<bool> ShowIndirectCallTargets(
888 "ic-targets", cl::init(false),
889 cl::desc("Show indirect call site target values for shown functions"));
Rong Xu6f00c7b2017-03-16 21:15:48 +0000890 cl::opt<bool> ShowMemOPSizes(
891 "memop-sizes", cl::init(false),
892 cl::desc("Show the profiled sizes of the memory intrinsic calls "
893 "for shown functions"));
Easwaran Ramanfa283c32016-01-13 21:44:36 +0000894 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
895 cl::desc("Show detailed profile summary"));
896 cl::list<uint32_t> DetailedSummaryCutoffs(
897 cl::CommaSeparated, "detailed-summary-cutoffs",
898 cl::desc(
899 "Cutoff percentages (times 10000) for generating detailed summary"),
900 cl::value_desc("800000,901000,999999"));
Diego Novillo9657de5f2014-11-01 00:56:55 +0000901 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
902 cl::desc("Details for every function"));
903 cl::opt<std::string> ShowFunction("function",
904 cl::desc("Details for matching functions"));
905
906 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
907 cl::init("-"), cl::desc("Output file"));
908 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
909 cl::aliasopt(OutputFilename));
910 cl::opt<ProfileKinds> ProfileKind(
911 cl::desc("Profile kind:"), cl::init(instr),
912 cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
Mehdi Amini3ffe1132016-10-08 19:41:06 +0000913 clEnumVal(sample, "Sample profile")));
Xinliang David Lidcb98bd2017-07-11 20:30:43 +0000914 cl::opt<uint32_t> TopNFunctions(
915 "topn", cl::init(0),
916 cl::desc("Show the list of functions with the largest internal counts"));
Rong Xuc445cab2019-01-08 22:41:48 +0000917 cl::opt<uint32_t> ValueCutoff(
918 "value-cutoff", cl::init(0),
919 cl::desc("Set the count value cutoff. Functions with the maximum count "
920 "less than this value will not be printed out. (Default is 0)"));
921 cl::opt<bool> OnlyListBelow(
922 "list-below-cutoff", cl::init(false),
923 cl::desc("Only output names of functions whose max count values are "
924 "below the cutoff value"));
Diego Novillo9657de5f2014-11-01 00:56:55 +0000925 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
926
927 if (OutputFilename.empty())
928 OutputFilename = "-";
929
930 std::error_code EC;
931 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text);
932 if (EC)
Xinliang David Li55f78332015-11-23 20:47:38 +0000933 exitWithErrorCode(EC, OutputFilename);
Diego Novillo9657de5f2014-11-01 00:56:55 +0000934
935 if (ShowAllFunctions && !ShowFunction.empty())
Jonas Devlieghere331449e2018-04-18 14:42:33 +0000936 WithColor::warning() << "-function argument ignored: showing all functions\n";
Diego Novillo9657de5f2014-11-01 00:56:55 +0000937
Easwaran Ramanfa283c32016-01-13 21:44:36 +0000938 std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(),
939 DetailedSummaryCutoffs.end());
Diego Novillo9657de5f2014-11-01 00:56:55 +0000940 if (ProfileKind == instr)
Xinliang David Lidcb98bd2017-07-11 20:30:43 +0000941 return showInstrProfile(Filename, ShowCounts, TopNFunctions,
942 ShowIndirectCallTargets, ShowMemOPSizes,
943 ShowDetailedSummary, DetailedSummaryCutoffs,
Rong Xuc445cab2019-01-08 22:41:48 +0000944 ShowAllFunctions, ValueCutoff, OnlyListBelow,
945 ShowFunction, TextFormat, OS);
Diego Novillo9657de5f2014-11-01 00:56:55 +0000946 else
947 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
948 ShowFunction, OS);
949}
950
Justin Bogner695043f2014-03-19 02:20:46 +0000951int main(int argc, const char *argv[]) {
Rui Ueyama0b9d56a2018-04-13 18:26:06 +0000952 InitLLVM X(argc, argv);
Justin Bogner695043f2014-03-19 02:20:46 +0000953
954 StringRef ProgName(sys::path::filename(argv[0]));
955 if (argc > 1) {
Craig Topper573faec2014-04-25 04:24:47 +0000956 int (*func)(int, const char *[]) = nullptr;
Justin Bogner695043f2014-03-19 02:20:46 +0000957
958 if (strcmp(argv[1], "merge") == 0)
959 func = merge_main;
Justin Bogner60bc9062014-03-21 17:29:44 +0000960 else if (strcmp(argv[1], "show") == 0)
961 func = show_main;
Justin Bogner695043f2014-03-19 02:20:46 +0000962
963 if (func) {
964 std::string Invocation(ProgName.str() + " " + argv[1]);
965 argv[1] = Invocation.c_str();
966 return func(argc - 1, argv + 1);
967 }
968
Diego Novillo914ed192015-12-14 20:37:15 +0000969 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
Justin Bogner695043f2014-03-19 02:20:46 +0000970 strcmp(argv[1], "--help") == 0) {
971
972 errs() << "OVERVIEW: LLVM profile data tools\n\n"
973 << "USAGE: " << ProgName << " <command> [args...]\n"
974 << "USAGE: " << ProgName << " <command> -help\n\n"
Justin Bognere1dd1542016-08-03 23:10:51 +0000975 << "See each individual command --help for more details.\n"
Justin Bogner60bc9062014-03-21 17:29:44 +0000976 << "Available commands: merge, show\n";
Justin Bogner695043f2014-03-19 02:20:46 +0000977 return 0;
978 }
979 }
980
981 if (argc < 2)
982 errs() << ProgName << ": No command specified!\n";
983 else
984 errs() << ProgName << ": Unknown command!\n";
985
Justin Bogner60bc9062014-03-21 17:29:44 +0000986 errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n";
Justin Bogner695043f2014-03-19 02:20:46 +0000987 return 1;
988}