llvm-profdata.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // llvm-profdata merges .profdata files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/SmallSet.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/ADT/StringRef.h"
  15. #include "llvm/IR/LLVMContext.h"
  16. #include "llvm/ProfileData/InstrProfReader.h"
  17. #include "llvm/ProfileData/InstrProfWriter.h"
  18. #include "llvm/ProfileData/ProfileCommon.h"
  19. #include "llvm/ProfileData/SampleProfReader.h"
  20. #include "llvm/ProfileData/SampleProfWriter.h"
  21. #include "llvm/Support/CommandLine.h"
  22. #include "llvm/Support/Errc.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/Format.h"
  25. #include "llvm/Support/InitLLVM.h"
  26. #include "llvm/Support/MemoryBuffer.h"
  27. #include "llvm/Support/Path.h"
  28. #include "llvm/Support/ThreadPool.h"
  29. #include "llvm/Support/WithColor.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <algorithm>
  32. using namespace llvm;
  33. enum ProfileFormat {
  34. PF_None = 0,
  35. PF_Text,
  36. PF_Compact_Binary,
  37. PF_Ext_Binary,
  38. PF_GCC,
  39. PF_Binary
  40. };
  41. static void warn(Twine Message, std::string Whence = "",
  42. std::string Hint = "") {
  43. WithColor::warning();
  44. if (!Whence.empty())
  45. errs() << Whence << ": ";
  46. errs() << Message << "\n";
  47. if (!Hint.empty())
  48. WithColor::note() << Hint << "\n";
  49. }
  50. static void exitWithError(Twine Message, std::string Whence = "",
  51. std::string Hint = "") {
  52. WithColor::error();
  53. if (!Whence.empty())
  54. errs() << Whence << ": ";
  55. errs() << Message << "\n";
  56. if (!Hint.empty())
  57. WithColor::note() << Hint << "\n";
  58. ::exit(1);
  59. }
  60. static void exitWithError(Error E, StringRef Whence = "") {
  61. if (E.isA<InstrProfError>()) {
  62. handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
  63. instrprof_error instrError = IPE.get();
  64. StringRef Hint = "";
  65. if (instrError == instrprof_error::unrecognized_format) {
  66. // Hint for common error of forgetting -sample for sample profiles.
  67. Hint = "Perhaps you forgot to use the -sample option?";
  68. }
  69. exitWithError(IPE.message(), Whence, Hint);
  70. });
  71. }
  72. exitWithError(toString(std::move(E)), Whence);
  73. }
  74. static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
  75. exitWithError(EC.message(), Whence);
  76. }
  77. namespace {
  78. enum ProfileKinds { instr, sample };
  79. enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid };
  80. }
  81. static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
  82. StringRef Whence = "") {
  83. if (FailMode == failIfAnyAreInvalid)
  84. exitWithErrorCode(EC, Whence);
  85. else
  86. warn(EC.message(), Whence);
  87. }
  88. static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
  89. StringRef WhenceFunction = "",
  90. bool ShowHint = true) {
  91. if (!WhenceFile.empty())
  92. errs() << WhenceFile << ": ";
  93. if (!WhenceFunction.empty())
  94. errs() << WhenceFunction << ": ";
  95. auto IPE = instrprof_error::success;
  96. E = handleErrors(std::move(E),
  97. [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
  98. IPE = E->get();
  99. return Error(std::move(E));
  100. });
  101. errs() << toString(std::move(E)) << "\n";
  102. if (ShowHint) {
  103. StringRef Hint = "";
  104. if (IPE != instrprof_error::success) {
  105. switch (IPE) {
  106. case instrprof_error::hash_mismatch:
  107. case instrprof_error::count_mismatch:
  108. case instrprof_error::value_site_count_mismatch:
  109. Hint = "Make sure that all profile data to be merged is generated "
  110. "from the same binary.";
  111. break;
  112. default:
  113. break;
  114. }
  115. }
  116. if (!Hint.empty())
  117. errs() << Hint << "\n";
  118. }
  119. }
  120. namespace {
  121. /// A remapper from original symbol names to new symbol names based on a file
  122. /// containing a list of mappings from old name to new name.
  123. class SymbolRemapper {
  124. std::unique_ptr<MemoryBuffer> File;
  125. DenseMap<StringRef, StringRef> RemappingTable;
  126. public:
  127. /// Build a SymbolRemapper from a file containing a list of old/new symbols.
  128. static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
  129. auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
  130. if (!BufOrError)
  131. exitWithErrorCode(BufOrError.getError(), InputFile);
  132. auto Remapper = std::make_unique<SymbolRemapper>();
  133. Remapper->File = std::move(BufOrError.get());
  134. for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
  135. !LineIt.is_at_eof(); ++LineIt) {
  136. std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
  137. if (Parts.first.empty() || Parts.second.empty() ||
  138. Parts.second.count(' ')) {
  139. exitWithError("unexpected line in remapping file",
  140. (InputFile + ":" + Twine(LineIt.line_number())).str(),
  141. "expected 'old_symbol new_symbol'");
  142. }
  143. Remapper->RemappingTable.insert(Parts);
  144. }
  145. return Remapper;
  146. }
  147. /// Attempt to map the given old symbol into a new symbol.
  148. ///
  149. /// \return The new symbol, or \p Name if no such symbol was found.
  150. StringRef operator()(StringRef Name) {
  151. StringRef New = RemappingTable.lookup(Name);
  152. return New.empty() ? Name : New;
  153. }
  154. };
  155. }
  156. struct WeightedFile {
  157. std::string Filename;
  158. uint64_t Weight;
  159. };
  160. typedef SmallVector<WeightedFile, 5> WeightedFileVector;
  161. /// Keep track of merged data and reported errors.
  162. struct WriterContext {
  163. std::mutex Lock;
  164. InstrProfWriter Writer;
  165. std::vector<std::pair<Error, std::string>> Errors;
  166. std::mutex &ErrLock;
  167. SmallSet<instrprof_error, 4> &WriterErrorCodes;
  168. WriterContext(bool IsSparse, std::mutex &ErrLock,
  169. SmallSet<instrprof_error, 4> &WriterErrorCodes)
  170. : Lock(), Writer(IsSparse), Errors(), ErrLock(ErrLock),
  171. WriterErrorCodes(WriterErrorCodes) {}
  172. };
  173. /// Computer the overlap b/w profile BaseFilename and TestFileName,
  174. /// and store the program level result to Overlap.
  175. static void overlapInput(const std::string &BaseFilename,
  176. const std::string &TestFilename, WriterContext *WC,
  177. OverlapStats &Overlap,
  178. const OverlapFuncFilters &FuncFilter,
  179. raw_fd_ostream &OS, bool IsCS) {
  180. auto ReaderOrErr = InstrProfReader::create(TestFilename);
  181. if (Error E = ReaderOrErr.takeError()) {
  182. // Skip the empty profiles by returning sliently.
  183. instrprof_error IPE = InstrProfError::take(std::move(E));
  184. if (IPE != instrprof_error::empty_raw_profile)
  185. WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename);
  186. return;
  187. }
  188. auto Reader = std::move(ReaderOrErr.get());
  189. for (auto &I : *Reader) {
  190. OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
  191. FuncOverlap.setFuncInfo(I.Name, I.Hash);
  192. WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
  193. FuncOverlap.dump(OS);
  194. }
  195. }
  196. /// Load an input into a writer context.
  197. static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
  198. WriterContext *WC) {
  199. std::unique_lock<std::mutex> CtxGuard{WC->Lock};
  200. // Copy the filename, because llvm::ThreadPool copied the input "const
  201. // WeightedFile &" by value, making a reference to the filename within it
  202. // invalid outside of this packaged task.
  203. std::string Filename = Input.Filename;
  204. auto ReaderOrErr = InstrProfReader::create(Input.Filename);
  205. if (Error E = ReaderOrErr.takeError()) {
  206. // Skip the empty profiles by returning sliently.
  207. instrprof_error IPE = InstrProfError::take(std::move(E));
  208. if (IPE != instrprof_error::empty_raw_profile)
  209. WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
  210. return;
  211. }
  212. auto Reader = std::move(ReaderOrErr.get());
  213. bool IsIRProfile = Reader->isIRLevelProfile();
  214. bool HasCSIRProfile = Reader->hasCSIRLevelProfile();
  215. if (WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) {
  216. WC->Errors.emplace_back(
  217. make_error<StringError>(
  218. "Merge IR generated profile with Clang generated profile.",
  219. std::error_code()),
  220. Filename);
  221. return;
  222. }
  223. for (auto &I : *Reader) {
  224. if (Remapper)
  225. I.Name = (*Remapper)(I.Name);
  226. const StringRef FuncName = I.Name;
  227. bool Reported = false;
  228. WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
  229. if (Reported) {
  230. consumeError(std::move(E));
  231. return;
  232. }
  233. Reported = true;
  234. // Only show hint the first time an error occurs.
  235. instrprof_error IPE = InstrProfError::take(std::move(E));
  236. std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
  237. bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
  238. handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
  239. FuncName, firstTime);
  240. });
  241. }
  242. if (Reader->hasError())
  243. if (Error E = Reader->getError())
  244. WC->Errors.emplace_back(std::move(E), Filename);
  245. }
  246. /// Merge the \p Src writer context into \p Dst.
  247. static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
  248. for (auto &ErrorPair : Src->Errors)
  249. Dst->Errors.push_back(std::move(ErrorPair));
  250. Src->Errors.clear();
  251. Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
  252. instrprof_error IPE = InstrProfError::take(std::move(E));
  253. std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
  254. bool firstTime = Dst->WriterErrorCodes.insert(IPE).second;
  255. if (firstTime)
  256. warn(toString(make_error<InstrProfError>(IPE)));
  257. });
  258. }
  259. static void mergeInstrProfile(const WeightedFileVector &Inputs,
  260. SymbolRemapper *Remapper,
  261. StringRef OutputFilename,
  262. ProfileFormat OutputFormat, bool OutputSparse,
  263. unsigned NumThreads, FailureMode FailMode) {
  264. if (OutputFilename.compare("-") == 0)
  265. exitWithError("Cannot write indexed profdata format to stdout.");
  266. if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
  267. OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text)
  268. exitWithError("Unknown format is specified.");
  269. std::mutex ErrorLock;
  270. SmallSet<instrprof_error, 4> WriterErrorCodes;
  271. // If NumThreads is not specified, auto-detect a good default.
  272. if (NumThreads == 0)
  273. NumThreads =
  274. std::min(hardware_concurrency(), unsigned((Inputs.size() + 1) / 2));
  275. // Initialize the writer contexts.
  276. SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
  277. for (unsigned I = 0; I < NumThreads; ++I)
  278. Contexts.emplace_back(std::make_unique<WriterContext>(
  279. OutputSparse, ErrorLock, WriterErrorCodes));
  280. if (NumThreads == 1) {
  281. for (const auto &Input : Inputs)
  282. loadInput(Input, Remapper, Contexts[0].get());
  283. } else {
  284. ThreadPool Pool(NumThreads);
  285. // Load the inputs in parallel (N/NumThreads serial steps).
  286. unsigned Ctx = 0;
  287. for (const auto &Input : Inputs) {
  288. Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
  289. Ctx = (Ctx + 1) % NumThreads;
  290. }
  291. Pool.wait();
  292. // Merge the writer contexts together (~ lg(NumThreads) serial steps).
  293. unsigned Mid = Contexts.size() / 2;
  294. unsigned End = Contexts.size();
  295. assert(Mid > 0 && "Expected more than one context");
  296. do {
  297. for (unsigned I = 0; I < Mid; ++I)
  298. Pool.async(mergeWriterContexts, Contexts[I].get(),
  299. Contexts[I + Mid].get());
  300. Pool.wait();
  301. if (End & 1) {
  302. Pool.async(mergeWriterContexts, Contexts[0].get(),
  303. Contexts[End - 1].get());
  304. Pool.wait();
  305. }
  306. End = Mid;
  307. Mid /= 2;
  308. } while (Mid > 0);
  309. }
  310. // Handle deferred errors encountered during merging. If the number of errors
  311. // is equal to the number of inputs the merge failed.
  312. unsigned NumErrors = 0;
  313. for (std::unique_ptr<WriterContext> &WC : Contexts) {
  314. for (auto &ErrorPair : WC->Errors) {
  315. ++NumErrors;
  316. warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
  317. }
  318. }
  319. if (NumErrors == Inputs.size() ||
  320. (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
  321. exitWithError("No profiles could be merged.");
  322. std::error_code EC;
  323. raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::OF_None);
  324. if (EC)
  325. exitWithErrorCode(EC, OutputFilename);
  326. InstrProfWriter &Writer = Contexts[0]->Writer;
  327. if (OutputFormat == PF_Text) {
  328. if (Error E = Writer.writeText(Output))
  329. exitWithError(std::move(E));
  330. } else {
  331. Writer.write(Output);
  332. }
  333. }
  334. /// Make a copy of the given function samples with all symbol names remapped
  335. /// by the provided symbol remapper.
  336. static sampleprof::FunctionSamples
  337. remapSamples(const sampleprof::FunctionSamples &Samples,
  338. SymbolRemapper &Remapper, sampleprof_error &Error) {
  339. sampleprof::FunctionSamples Result;
  340. Result.setName(Remapper(Samples.getName()));
  341. Result.addTotalSamples(Samples.getTotalSamples());
  342. Result.addHeadSamples(Samples.getHeadSamples());
  343. for (const auto &BodySample : Samples.getBodySamples()) {
  344. Result.addBodySamples(BodySample.first.LineOffset,
  345. BodySample.first.Discriminator,
  346. BodySample.second.getSamples());
  347. for (const auto &Target : BodySample.second.getCallTargets()) {
  348. Result.addCalledTargetSamples(BodySample.first.LineOffset,
  349. BodySample.first.Discriminator,
  350. Remapper(Target.first()), Target.second);
  351. }
  352. }
  353. for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
  354. sampleprof::FunctionSamplesMap &Target =
  355. Result.functionSamplesAt(CallsiteSamples.first);
  356. for (const auto &Callsite : CallsiteSamples.second) {
  357. sampleprof::FunctionSamples Remapped =
  358. remapSamples(Callsite.second, Remapper, Error);
  359. MergeResult(Error, Target[Remapped.getName()].merge(Remapped));
  360. }
  361. }
  362. return Result;
  363. }
  364. static sampleprof::SampleProfileFormat FormatMap[] = {
  365. sampleprof::SPF_None,
  366. sampleprof::SPF_Text,
  367. sampleprof::SPF_Compact_Binary,
  368. sampleprof::SPF_Ext_Binary,
  369. sampleprof::SPF_GCC,
  370. sampleprof::SPF_Binary};
  371. static std::unique_ptr<MemoryBuffer>
  372. getInputFileBuf(const StringRef &InputFile) {
  373. if (InputFile == "")
  374. return {};
  375. auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
  376. if (!BufOrError)
  377. exitWithErrorCode(BufOrError.getError(), InputFile);
  378. return std::move(*BufOrError);
  379. }
  380. static void populateProfileSymbolList(MemoryBuffer *Buffer,
  381. sampleprof::ProfileSymbolList &PSL) {
  382. if (!Buffer)
  383. return;
  384. SmallVector<StringRef, 32> SymbolVec;
  385. StringRef Data = Buffer->getBuffer();
  386. Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  387. for (StringRef symbol : SymbolVec)
  388. PSL.add(symbol);
  389. }
  390. static void mergeSampleProfile(const WeightedFileVector &Inputs,
  391. SymbolRemapper *Remapper,
  392. StringRef OutputFilename,
  393. ProfileFormat OutputFormat,
  394. StringRef ProfileSymbolListFile,
  395. bool CompressProfSymList, FailureMode FailMode) {
  396. using namespace sampleprof;
  397. StringMap<FunctionSamples> ProfileMap;
  398. SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
  399. LLVMContext Context;
  400. sampleprof::ProfileSymbolList WriterList;
  401. for (const auto &Input : Inputs) {
  402. auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
  403. if (std::error_code EC = ReaderOrErr.getError()) {
  404. warnOrExitGivenError(FailMode, EC, Input.Filename);
  405. continue;
  406. }
  407. // We need to keep the readers around until after all the files are
  408. // read so that we do not lose the function names stored in each
  409. // reader's memory. The function names are needed to write out the
  410. // merged profile map.
  411. Readers.push_back(std::move(ReaderOrErr.get()));
  412. const auto Reader = Readers.back().get();
  413. if (std::error_code EC = Reader->read()) {
  414. warnOrExitGivenError(FailMode, EC, Input.Filename);
  415. Readers.pop_back();
  416. continue;
  417. }
  418. StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
  419. for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
  420. E = Profiles.end();
  421. I != E; ++I) {
  422. sampleprof_error Result = sampleprof_error::success;
  423. FunctionSamples Remapped =
  424. Remapper ? remapSamples(I->second, *Remapper, Result)
  425. : FunctionSamples();
  426. FunctionSamples &Samples = Remapper ? Remapped : I->second;
  427. StringRef FName = Samples.getName();
  428. MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
  429. if (Result != sampleprof_error::success) {
  430. std::error_code EC = make_error_code(Result);
  431. handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
  432. }
  433. }
  434. std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
  435. Reader->getProfileSymbolList();
  436. if (ReaderList)
  437. WriterList.merge(*ReaderList);
  438. }
  439. auto WriterOrErr =
  440. SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
  441. if (std::error_code EC = WriterOrErr.getError())
  442. exitWithErrorCode(EC, OutputFilename);
  443. // WriterList will have StringRef refering to string in Buffer.
  444. // Make sure Buffer lives as long as WriterList.
  445. auto Buffer = getInputFileBuf(ProfileSymbolListFile);
  446. populateProfileSymbolList(Buffer.get(), WriterList);
  447. WriterList.setToCompress(CompressProfSymList);
  448. if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
  449. warn("Profile Symbol list is not empty but the output format is not "
  450. "ExtBinary format. The list will be lost in the output. ");
  451. auto Writer = std::move(WriterOrErr.get());
  452. Writer->setProfileSymbolList(&WriterList);
  453. Writer->write(ProfileMap);
  454. }
  455. static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
  456. StringRef WeightStr, FileName;
  457. std::tie(WeightStr, FileName) = WeightedFilename.split(',');
  458. uint64_t Weight;
  459. if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
  460. exitWithError("Input weight must be a positive integer.");
  461. return {FileName, Weight};
  462. }
  463. static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
  464. StringRef Filename = WF.Filename;
  465. uint64_t Weight = WF.Weight;
  466. // If it's STDIN just pass it on.
  467. if (Filename == "-") {
  468. WNI.push_back({Filename, Weight});
  469. return;
  470. }
  471. llvm::sys::fs::file_status Status;
  472. llvm::sys::fs::status(Filename, Status);
  473. if (!llvm::sys::fs::exists(Status))
  474. exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
  475. Filename);
  476. // If it's a source file, collect it.
  477. if (llvm::sys::fs::is_regular_file(Status)) {
  478. WNI.push_back({Filename, Weight});
  479. return;
  480. }
  481. if (llvm::sys::fs::is_directory(Status)) {
  482. std::error_code EC;
  483. for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
  484. F != E && !EC; F.increment(EC)) {
  485. if (llvm::sys::fs::is_regular_file(F->path())) {
  486. addWeightedInput(WNI, {F->path(), Weight});
  487. }
  488. }
  489. if (EC)
  490. exitWithErrorCode(EC, Filename);
  491. }
  492. }
  493. static void parseInputFilenamesFile(MemoryBuffer *Buffer,
  494. WeightedFileVector &WFV) {
  495. if (!Buffer)
  496. return;
  497. SmallVector<StringRef, 8> Entries;
  498. StringRef Data = Buffer->getBuffer();
  499. Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  500. for (const StringRef &FileWeightEntry : Entries) {
  501. StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
  502. // Skip comments.
  503. if (SanitizedEntry.startswith("#"))
  504. continue;
  505. // If there's no comma, it's an unweighted profile.
  506. else if (SanitizedEntry.find(',') == StringRef::npos)
  507. addWeightedInput(WFV, {SanitizedEntry, 1});
  508. else
  509. addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
  510. }
  511. }
  512. static int merge_main(int argc, const char *argv[]) {
  513. cl::list<std::string> InputFilenames(cl::Positional,
  514. cl::desc("<filename...>"));
  515. cl::list<std::string> WeightedInputFilenames("weighted-input",
  516. cl::desc("<weight>,<filename>"));
  517. cl::opt<std::string> InputFilenamesFile(
  518. "input-files", cl::init(""),
  519. cl::desc("Path to file containing newline-separated "
  520. "[<weight>,]<filename> entries"));
  521. cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
  522. cl::aliasopt(InputFilenamesFile));
  523. cl::opt<bool> DumpInputFileList(
  524. "dump-input-file-list", cl::init(false), cl::Hidden,
  525. cl::desc("Dump the list of input files and their weights, then exit"));
  526. cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
  527. cl::desc("Symbol remapping file"));
  528. cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
  529. cl::aliasopt(RemappingFile));
  530. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  531. cl::init("-"), cl::Required,
  532. cl::desc("Output file"));
  533. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  534. cl::aliasopt(OutputFilename));
  535. cl::opt<ProfileKinds> ProfileKind(
  536. cl::desc("Profile kind:"), cl::init(instr),
  537. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  538. clEnumVal(sample, "Sample profile")));
  539. cl::opt<ProfileFormat> OutputFormat(
  540. cl::desc("Format of output profile"), cl::init(PF_Binary),
  541. cl::values(
  542. clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
  543. clEnumValN(PF_Compact_Binary, "compbinary",
  544. "Compact binary encoding"),
  545. clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"),
  546. clEnumValN(PF_Text, "text", "Text encoding"),
  547. clEnumValN(PF_GCC, "gcc",
  548. "GCC encoding (only meaningful for -sample)")));
  549. cl::opt<FailureMode> FailureMode(
  550. "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"),
  551. cl::values(clEnumValN(failIfAnyAreInvalid, "any",
  552. "Fail if any profile is invalid."),
  553. clEnumValN(failIfAllAreInvalid, "all",
  554. "Fail only if all profiles are invalid.")));
  555. cl::opt<bool> OutputSparse("sparse", cl::init(false),
  556. cl::desc("Generate a sparse profile (only meaningful for -instr)"));
  557. cl::opt<unsigned> NumThreads(
  558. "num-threads", cl::init(0),
  559. cl::desc("Number of merge threads to use (default: autodetect)"));
  560. cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
  561. cl::aliasopt(NumThreads));
  562. cl::opt<std::string> ProfileSymbolListFile(
  563. "prof-sym-list", cl::init(""),
  564. cl::desc("Path to file containing the list of function symbols "
  565. "used to populate profile symbol list"));
  566. cl::opt<bool> CompressProfSymList(
  567. "compress-prof-sym-list", cl::init(false), cl::Hidden,
  568. cl::desc("Compress profile symbol list before write it into profile. "));
  569. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
  570. WeightedFileVector WeightedInputs;
  571. for (StringRef Filename : InputFilenames)
  572. addWeightedInput(WeightedInputs, {Filename, 1});
  573. for (StringRef WeightedFilename : WeightedInputFilenames)
  574. addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
  575. // Make sure that the file buffer stays alive for the duration of the
  576. // weighted input vector's lifetime.
  577. auto Buffer = getInputFileBuf(InputFilenamesFile);
  578. parseInputFilenamesFile(Buffer.get(), WeightedInputs);
  579. if (WeightedInputs.empty())
  580. exitWithError("No input files specified. See " +
  581. sys::path::filename(argv[0]) + " -help");
  582. if (DumpInputFileList) {
  583. for (auto &WF : WeightedInputs)
  584. outs() << WF.Weight << "," << WF.Filename << "\n";
  585. return 0;
  586. }
  587. std::unique_ptr<SymbolRemapper> Remapper;
  588. if (!RemappingFile.empty())
  589. Remapper = SymbolRemapper::create(RemappingFile);
  590. if (ProfileKind == instr)
  591. mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
  592. OutputFormat, OutputSparse, NumThreads, FailureMode);
  593. else
  594. mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
  595. OutputFormat, ProfileSymbolListFile,
  596. CompressProfSymList, FailureMode);
  597. return 0;
  598. }
  599. /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
  600. static void overlapInstrProfile(const std::string &BaseFilename,
  601. const std::string &TestFilename,
  602. const OverlapFuncFilters &FuncFilter,
  603. raw_fd_ostream &OS, bool IsCS) {
  604. std::mutex ErrorLock;
  605. SmallSet<instrprof_error, 4> WriterErrorCodes;
  606. WriterContext Context(false, ErrorLock, WriterErrorCodes);
  607. WeightedFile WeightedInput{BaseFilename, 1};
  608. OverlapStats Overlap;
  609. Error E = Overlap.accumuateCounts(BaseFilename, TestFilename, IsCS);
  610. if (E)
  611. exitWithError(std::move(E), "Error in getting profile count sums");
  612. if (Overlap.Base.CountSum < 1.0f) {
  613. OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
  614. exit(0);
  615. }
  616. if (Overlap.Test.CountSum < 1.0f) {
  617. OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
  618. exit(0);
  619. }
  620. loadInput(WeightedInput, nullptr, &Context);
  621. overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
  622. IsCS);
  623. Overlap.dump(OS);
  624. }
  625. static int overlap_main(int argc, const char *argv[]) {
  626. cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
  627. cl::desc("<base profile file>"));
  628. cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
  629. cl::desc("<test profile file>"));
  630. cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
  631. cl::desc("Output file"));
  632. cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
  633. cl::opt<bool> IsCS("cs", cl::init(false),
  634. cl::desc("For context sensitive counts"));
  635. cl::opt<unsigned long long> ValueCutoff(
  636. "value-cutoff", cl::init(-1),
  637. cl::desc(
  638. "Function level overlap information for every function in test "
  639. "profile with max count value greater then the parameter value"));
  640. cl::opt<std::string> FuncNameFilter(
  641. "function",
  642. cl::desc("Function level overlap information for matching functions"));
  643. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
  644. std::error_code EC;
  645. raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_Text);
  646. if (EC)
  647. exitWithErrorCode(EC, Output);
  648. overlapInstrProfile(BaseFilename, TestFilename,
  649. OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
  650. IsCS);
  651. return 0;
  652. }
  653. typedef struct ValueSitesStats {
  654. ValueSitesStats()
  655. : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
  656. TotalNumValues(0) {}
  657. uint64_t TotalNumValueSites;
  658. uint64_t TotalNumValueSitesWithValueProfile;
  659. uint64_t TotalNumValues;
  660. std::vector<unsigned> ValueSitesHistogram;
  661. } ValueSitesStats;
  662. static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
  663. ValueSitesStats &Stats, raw_fd_ostream &OS,
  664. InstrProfSymtab *Symtab) {
  665. uint32_t NS = Func.getNumValueSites(VK);
  666. Stats.TotalNumValueSites += NS;
  667. for (size_t I = 0; I < NS; ++I) {
  668. uint32_t NV = Func.getNumValueDataForSite(VK, I);
  669. std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
  670. Stats.TotalNumValues += NV;
  671. if (NV) {
  672. Stats.TotalNumValueSitesWithValueProfile++;
  673. if (NV > Stats.ValueSitesHistogram.size())
  674. Stats.ValueSitesHistogram.resize(NV, 0);
  675. Stats.ValueSitesHistogram[NV - 1]++;
  676. }
  677. uint64_t SiteSum = 0;
  678. for (uint32_t V = 0; V < NV; V++)
  679. SiteSum += VD[V].Count;
  680. if (SiteSum == 0)
  681. SiteSum = 1;
  682. for (uint32_t V = 0; V < NV; V++) {
  683. OS << "\t[ " << format("%2u", I) << ", ";
  684. if (Symtab == nullptr)
  685. OS << format("%4" PRIu64, VD[V].Value);
  686. else
  687. OS << Symtab->getFuncName(VD[V].Value);
  688. OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
  689. << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
  690. }
  691. }
  692. }
  693. static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
  694. ValueSitesStats &Stats) {
  695. OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
  696. OS << " Total number of sites with values: "
  697. << Stats.TotalNumValueSitesWithValueProfile << "\n";
  698. OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
  699. OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
  700. for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
  701. if (Stats.ValueSitesHistogram[I] > 0)
  702. OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
  703. }
  704. }
  705. static int showInstrProfile(const std::string &Filename, bool ShowCounts,
  706. uint32_t TopN, bool ShowIndirectCallTargets,
  707. bool ShowMemOPSizes, bool ShowDetailedSummary,
  708. std::vector<uint32_t> DetailedSummaryCutoffs,
  709. bool ShowAllFunctions, bool ShowCS,
  710. uint64_t ValueCutoff, bool OnlyListBelow,
  711. const std::string &ShowFunction, bool TextFormat,
  712. raw_fd_ostream &OS) {
  713. auto ReaderOrErr = InstrProfReader::create(Filename);
  714. std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
  715. if (ShowDetailedSummary && Cutoffs.empty()) {
  716. Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
  717. }
  718. InstrProfSummaryBuilder Builder(std::move(Cutoffs));
  719. if (Error E = ReaderOrErr.takeError())
  720. exitWithError(std::move(E), Filename);
  721. auto Reader = std::move(ReaderOrErr.get());
  722. bool IsIRInstr = Reader->isIRLevelProfile();
  723. size_t ShownFunctions = 0;
  724. size_t BelowCutoffFunctions = 0;
  725. int NumVPKind = IPVK_Last - IPVK_First + 1;
  726. std::vector<ValueSitesStats> VPStats(NumVPKind);
  727. auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
  728. const std::pair<std::string, uint64_t> &v2) {
  729. return v1.second > v2.second;
  730. };
  731. std::priority_queue<std::pair<std::string, uint64_t>,
  732. std::vector<std::pair<std::string, uint64_t>>,
  733. decltype(MinCmp)>
  734. HottestFuncs(MinCmp);
  735. if (!TextFormat && OnlyListBelow) {
  736. OS << "The list of functions with the maximum counter less than "
  737. << ValueCutoff << ":\n";
  738. }
  739. // Add marker so that IR-level instrumentation round-trips properly.
  740. if (TextFormat && IsIRInstr)
  741. OS << ":ir\n";
  742. for (const auto &Func : *Reader) {
  743. if (Reader->isIRLevelProfile()) {
  744. bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
  745. if (FuncIsCS != ShowCS)
  746. continue;
  747. }
  748. bool Show =
  749. ShowAllFunctions || (!ShowFunction.empty() &&
  750. Func.Name.find(ShowFunction) != Func.Name.npos);
  751. bool doTextFormatDump = (Show && TextFormat);
  752. if (doTextFormatDump) {
  753. InstrProfSymtab &Symtab = Reader->getSymtab();
  754. InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
  755. OS);
  756. continue;
  757. }
  758. assert(Func.Counts.size() > 0 && "function missing entry counter");
  759. Builder.addRecord(Func);
  760. uint64_t FuncMax = 0;
  761. uint64_t FuncSum = 0;
  762. for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
  763. FuncMax = std::max(FuncMax, Func.Counts[I]);
  764. FuncSum += Func.Counts[I];
  765. }
  766. if (FuncMax < ValueCutoff) {
  767. ++BelowCutoffFunctions;
  768. if (OnlyListBelow) {
  769. OS << " " << Func.Name << ": (Max = " << FuncMax
  770. << " Sum = " << FuncSum << ")\n";
  771. }
  772. continue;
  773. } else if (OnlyListBelow)
  774. continue;
  775. if (TopN) {
  776. if (HottestFuncs.size() == TopN) {
  777. if (HottestFuncs.top().second < FuncMax) {
  778. HottestFuncs.pop();
  779. HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
  780. }
  781. } else
  782. HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
  783. }
  784. if (Show) {
  785. if (!ShownFunctions)
  786. OS << "Counters:\n";
  787. ++ShownFunctions;
  788. OS << " " << Func.Name << ":\n"
  789. << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
  790. << " Counters: " << Func.Counts.size() << "\n";
  791. if (!IsIRInstr)
  792. OS << " Function count: " << Func.Counts[0] << "\n";
  793. if (ShowIndirectCallTargets)
  794. OS << " Indirect Call Site Count: "
  795. << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
  796. uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
  797. if (ShowMemOPSizes && NumMemOPCalls > 0)
  798. OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
  799. << "\n";
  800. if (ShowCounts) {
  801. OS << " Block counts: [";
  802. size_t Start = (IsIRInstr ? 0 : 1);
  803. for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
  804. OS << (I == Start ? "" : ", ") << Func.Counts[I];
  805. }
  806. OS << "]\n";
  807. }
  808. if (ShowIndirectCallTargets) {
  809. OS << " Indirect Target Results:\n";
  810. traverseAllValueSites(Func, IPVK_IndirectCallTarget,
  811. VPStats[IPVK_IndirectCallTarget], OS,
  812. &(Reader->getSymtab()));
  813. }
  814. if (ShowMemOPSizes && NumMemOPCalls > 0) {
  815. OS << " Memory Intrinsic Size Results:\n";
  816. traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
  817. nullptr);
  818. }
  819. }
  820. }
  821. if (Reader->hasError())
  822. exitWithError(Reader->getError(), Filename);
  823. if (TextFormat)
  824. return 0;
  825. std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
  826. OS << "Instrumentation level: "
  827. << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n";
  828. if (ShowAllFunctions || !ShowFunction.empty())
  829. OS << "Functions shown: " << ShownFunctions << "\n";
  830. OS << "Total functions: " << PS->getNumFunctions() << "\n";
  831. if (ValueCutoff > 0) {
  832. OS << "Number of functions with maximum count (< " << ValueCutoff
  833. << "): " << BelowCutoffFunctions << "\n";
  834. OS << "Number of functions with maximum count (>= " << ValueCutoff
  835. << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
  836. }
  837. OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
  838. OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
  839. if (TopN) {
  840. std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
  841. while (!HottestFuncs.empty()) {
  842. SortedHottestFuncs.emplace_back(HottestFuncs.top());
  843. HottestFuncs.pop();
  844. }
  845. OS << "Top " << TopN
  846. << " functions with the largest internal block counts: \n";
  847. for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
  848. OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
  849. }
  850. if (ShownFunctions && ShowIndirectCallTargets) {
  851. OS << "Statistics for indirect call sites profile:\n";
  852. showValueSitesStats(OS, IPVK_IndirectCallTarget,
  853. VPStats[IPVK_IndirectCallTarget]);
  854. }
  855. if (ShownFunctions && ShowMemOPSizes) {
  856. OS << "Statistics for memory intrinsic calls sizes profile:\n";
  857. showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
  858. }
  859. if (ShowDetailedSummary) {
  860. OS << "Detailed summary:\n";
  861. OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
  862. OS << "Total count: " << PS->getTotalCount() << "\n";
  863. for (auto Entry : PS->getDetailedSummary()) {
  864. OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount
  865. << " account for "
  866. << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100)
  867. << " percentage of the total counts.\n";
  868. }
  869. }
  870. return 0;
  871. }
  872. static int showSampleProfile(const std::string &Filename, bool ShowCounts,
  873. bool ShowAllFunctions,
  874. const std::string &ShowFunction,
  875. bool ShowProfileSymbolList, raw_fd_ostream &OS) {
  876. using namespace sampleprof;
  877. LLVMContext Context;
  878. auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
  879. if (std::error_code EC = ReaderOrErr.getError())
  880. exitWithErrorCode(EC, Filename);
  881. auto Reader = std::move(ReaderOrErr.get());
  882. if (std::error_code EC = Reader->read())
  883. exitWithErrorCode(EC, Filename);
  884. if (ShowAllFunctions || ShowFunction.empty())
  885. Reader->dump(OS);
  886. else
  887. Reader->dumpFunctionProfile(ShowFunction, OS);
  888. if (ShowProfileSymbolList) {
  889. std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
  890. Reader->getProfileSymbolList();
  891. ReaderList->dump(OS);
  892. }
  893. return 0;
  894. }
  895. static int show_main(int argc, const char *argv[]) {
  896. cl::opt<std::string> Filename(cl::Positional, cl::Required,
  897. cl::desc("<profdata-file>"));
  898. cl::opt<bool> ShowCounts("counts", cl::init(false),
  899. cl::desc("Show counter values for shown functions"));
  900. cl::opt<bool> TextFormat(
  901. "text", cl::init(false),
  902. cl::desc("Show instr profile data in text dump format"));
  903. cl::opt<bool> ShowIndirectCallTargets(
  904. "ic-targets", cl::init(false),
  905. cl::desc("Show indirect call site target values for shown functions"));
  906. cl::opt<bool> ShowMemOPSizes(
  907. "memop-sizes", cl::init(false),
  908. cl::desc("Show the profiled sizes of the memory intrinsic calls "
  909. "for shown functions"));
  910. cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
  911. cl::desc("Show detailed profile summary"));
  912. cl::list<uint32_t> DetailedSummaryCutoffs(
  913. cl::CommaSeparated, "detailed-summary-cutoffs",
  914. cl::desc(
  915. "Cutoff percentages (times 10000) for generating detailed summary"),
  916. cl::value_desc("800000,901000,999999"));
  917. cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
  918. cl::desc("Details for every function"));
  919. cl::opt<bool> ShowCS("showcs", cl::init(false),
  920. cl::desc("Show context sensitive counts"));
  921. cl::opt<std::string> ShowFunction("function",
  922. cl::desc("Details for matching functions"));
  923. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  924. cl::init("-"), cl::desc("Output file"));
  925. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  926. cl::aliasopt(OutputFilename));
  927. cl::opt<ProfileKinds> ProfileKind(
  928. cl::desc("Profile kind:"), cl::init(instr),
  929. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  930. clEnumVal(sample, "Sample profile")));
  931. cl::opt<uint32_t> TopNFunctions(
  932. "topn", cl::init(0),
  933. cl::desc("Show the list of functions with the largest internal counts"));
  934. cl::opt<uint32_t> ValueCutoff(
  935. "value-cutoff", cl::init(0),
  936. cl::desc("Set the count value cutoff. Functions with the maximum count "
  937. "less than this value will not be printed out. (Default is 0)"));
  938. cl::opt<bool> OnlyListBelow(
  939. "list-below-cutoff", cl::init(false),
  940. cl::desc("Only output names of functions whose max count values are "
  941. "below the cutoff value"));
  942. cl::opt<bool> ShowProfileSymbolList(
  943. "show-prof-sym-list", cl::init(false),
  944. cl::desc("Show profile symbol list if it exists in the profile. "));
  945. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
  946. if (OutputFilename.empty())
  947. OutputFilename = "-";
  948. if (!Filename.compare(OutputFilename)) {
  949. errs() << sys::path::filename(argv[0])
  950. << ": Input file name cannot be the same as the output file name!\n";
  951. return 1;
  952. }
  953. std::error_code EC;
  954. raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_Text);
  955. if (EC)
  956. exitWithErrorCode(EC, OutputFilename);
  957. if (ShowAllFunctions && !ShowFunction.empty())
  958. WithColor::warning() << "-function argument ignored: showing all functions\n";
  959. if (ProfileKind == instr)
  960. return showInstrProfile(Filename, ShowCounts, TopNFunctions,
  961. ShowIndirectCallTargets, ShowMemOPSizes,
  962. ShowDetailedSummary, DetailedSummaryCutoffs,
  963. ShowAllFunctions, ShowCS, ValueCutoff,
  964. OnlyListBelow, ShowFunction, TextFormat, OS);
  965. else
  966. return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
  967. ShowFunction, ShowProfileSymbolList, OS);
  968. }
  969. int main(int argc, const char *argv[]) {
  970. InitLLVM X(argc, argv);
  971. StringRef ProgName(sys::path::filename(argv[0]));
  972. if (argc > 1) {
  973. int (*func)(int, const char *[]) = nullptr;
  974. if (strcmp(argv[1], "merge") == 0)
  975. func = merge_main;
  976. else if (strcmp(argv[1], "show") == 0)
  977. func = show_main;
  978. else if (strcmp(argv[1], "overlap") == 0)
  979. func = overlap_main;
  980. if (func) {
  981. std::string Invocation(ProgName.str() + " " + argv[1]);
  982. argv[1] = Invocation.c_str();
  983. return func(argc - 1, argv + 1);
  984. }
  985. if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
  986. strcmp(argv[1], "--help") == 0) {
  987. errs() << "OVERVIEW: LLVM profile data tools\n\n"
  988. << "USAGE: " << ProgName << " <command> [args...]\n"
  989. << "USAGE: " << ProgName << " <command> -help\n\n"
  990. << "See each individual command --help for more details.\n"
  991. << "Available commands: merge, show, overlap\n";
  992. return 0;
  993. }
  994. }
  995. if (argc < 2)
  996. errs() << ProgName << ": No command specified!\n";
  997. else
  998. errs() << ProgName << ": Unknown command!\n";
  999. errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
  1000. return 1;
  1001. }