llvm-profdata.cpp 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498
  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/FormattedStream.h"
  26. #include "llvm/Support/InitLLVM.h"
  27. #include "llvm/Support/MemoryBuffer.h"
  28. #include "llvm/Support/Path.h"
  29. #include "llvm/Support/ThreadPool.h"
  30. #include "llvm/Support/Threading.h"
  31. #include "llvm/Support/WithColor.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include <algorithm>
  34. using namespace llvm;
  35. enum ProfileFormat {
  36. PF_None = 0,
  37. PF_Text,
  38. PF_Compact_Binary,
  39. PF_Ext_Binary,
  40. PF_GCC,
  41. PF_Binary
  42. };
  43. static void warn(Twine Message, std::string Whence = "",
  44. std::string Hint = "") {
  45. WithColor::warning();
  46. if (!Whence.empty())
  47. errs() << Whence << ": ";
  48. errs() << Message << "\n";
  49. if (!Hint.empty())
  50. WithColor::note() << Hint << "\n";
  51. }
  52. static void exitWithError(Twine Message, std::string Whence = "",
  53. std::string Hint = "") {
  54. WithColor::error();
  55. if (!Whence.empty())
  56. errs() << Whence << ": ";
  57. errs() << Message << "\n";
  58. if (!Hint.empty())
  59. WithColor::note() << Hint << "\n";
  60. ::exit(1);
  61. }
  62. static void exitWithError(Error E, StringRef Whence = "") {
  63. if (E.isA<InstrProfError>()) {
  64. handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
  65. instrprof_error instrError = IPE.get();
  66. StringRef Hint = "";
  67. if (instrError == instrprof_error::unrecognized_format) {
  68. // Hint for common error of forgetting --sample for sample profiles.
  69. Hint = "Perhaps you forgot to use the --sample option?";
  70. }
  71. exitWithError(IPE.message(), std::string(Whence), std::string(Hint));
  72. });
  73. }
  74. exitWithError(toString(std::move(E)), std::string(Whence));
  75. }
  76. static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") {
  77. exitWithError(EC.message(), std::string(Whence));
  78. }
  79. namespace {
  80. enum ProfileKinds { instr, sample };
  81. enum FailureMode { failIfAnyAreInvalid, failIfAllAreInvalid };
  82. }
  83. static void warnOrExitGivenError(FailureMode FailMode, std::error_code EC,
  84. StringRef Whence = "") {
  85. if (FailMode == failIfAnyAreInvalid)
  86. exitWithErrorCode(EC, Whence);
  87. else
  88. warn(EC.message(), std::string(Whence));
  89. }
  90. static void handleMergeWriterError(Error E, StringRef WhenceFile = "",
  91. StringRef WhenceFunction = "",
  92. bool ShowHint = true) {
  93. if (!WhenceFile.empty())
  94. errs() << WhenceFile << ": ";
  95. if (!WhenceFunction.empty())
  96. errs() << WhenceFunction << ": ";
  97. auto IPE = instrprof_error::success;
  98. E = handleErrors(std::move(E),
  99. [&IPE](std::unique_ptr<InstrProfError> E) -> Error {
  100. IPE = E->get();
  101. return Error(std::move(E));
  102. });
  103. errs() << toString(std::move(E)) << "\n";
  104. if (ShowHint) {
  105. StringRef Hint = "";
  106. if (IPE != instrprof_error::success) {
  107. switch (IPE) {
  108. case instrprof_error::hash_mismatch:
  109. case instrprof_error::count_mismatch:
  110. case instrprof_error::value_site_count_mismatch:
  111. Hint = "Make sure that all profile data to be merged is generated "
  112. "from the same binary.";
  113. break;
  114. default:
  115. break;
  116. }
  117. }
  118. if (!Hint.empty())
  119. errs() << Hint << "\n";
  120. }
  121. }
  122. namespace {
  123. /// A remapper from original symbol names to new symbol names based on a file
  124. /// containing a list of mappings from old name to new name.
  125. class SymbolRemapper {
  126. std::unique_ptr<MemoryBuffer> File;
  127. DenseMap<StringRef, StringRef> RemappingTable;
  128. public:
  129. /// Build a SymbolRemapper from a file containing a list of old/new symbols.
  130. static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) {
  131. auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
  132. if (!BufOrError)
  133. exitWithErrorCode(BufOrError.getError(), InputFile);
  134. auto Remapper = std::make_unique<SymbolRemapper>();
  135. Remapper->File = std::move(BufOrError.get());
  136. for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#');
  137. !LineIt.is_at_eof(); ++LineIt) {
  138. std::pair<StringRef, StringRef> Parts = LineIt->split(' ');
  139. if (Parts.first.empty() || Parts.second.empty() ||
  140. Parts.second.count(' ')) {
  141. exitWithError("unexpected line in remapping file",
  142. (InputFile + ":" + Twine(LineIt.line_number())).str(),
  143. "expected 'old_symbol new_symbol'");
  144. }
  145. Remapper->RemappingTable.insert(Parts);
  146. }
  147. return Remapper;
  148. }
  149. /// Attempt to map the given old symbol into a new symbol.
  150. ///
  151. /// \return The new symbol, or \p Name if no such symbol was found.
  152. StringRef operator()(StringRef Name) {
  153. StringRef New = RemappingTable.lookup(Name);
  154. return New.empty() ? Name : New;
  155. }
  156. };
  157. }
  158. struct WeightedFile {
  159. std::string Filename;
  160. uint64_t Weight;
  161. };
  162. typedef SmallVector<WeightedFile, 5> WeightedFileVector;
  163. /// Keep track of merged data and reported errors.
  164. struct WriterContext {
  165. std::mutex Lock;
  166. InstrProfWriter Writer;
  167. std::vector<std::pair<Error, std::string>> Errors;
  168. std::mutex &ErrLock;
  169. SmallSet<instrprof_error, 4> &WriterErrorCodes;
  170. WriterContext(bool IsSparse, std::mutex &ErrLock,
  171. SmallSet<instrprof_error, 4> &WriterErrorCodes)
  172. : Lock(), Writer(IsSparse), Errors(), ErrLock(ErrLock),
  173. WriterErrorCodes(WriterErrorCodes) {}
  174. };
  175. /// Computer the overlap b/w profile BaseFilename and TestFileName,
  176. /// and store the program level result to Overlap.
  177. static void overlapInput(const std::string &BaseFilename,
  178. const std::string &TestFilename, WriterContext *WC,
  179. OverlapStats &Overlap,
  180. const OverlapFuncFilters &FuncFilter,
  181. raw_fd_ostream &OS, bool IsCS) {
  182. auto ReaderOrErr = InstrProfReader::create(TestFilename);
  183. if (Error E = ReaderOrErr.takeError()) {
  184. // Skip the empty profiles by returning sliently.
  185. instrprof_error IPE = InstrProfError::take(std::move(E));
  186. if (IPE != instrprof_error::empty_raw_profile)
  187. WC->Errors.emplace_back(make_error<InstrProfError>(IPE), TestFilename);
  188. return;
  189. }
  190. auto Reader = std::move(ReaderOrErr.get());
  191. for (auto &I : *Reader) {
  192. OverlapStats FuncOverlap(OverlapStats::FunctionLevel);
  193. FuncOverlap.setFuncInfo(I.Name, I.Hash);
  194. WC->Writer.overlapRecord(std::move(I), Overlap, FuncOverlap, FuncFilter);
  195. FuncOverlap.dump(OS);
  196. }
  197. }
  198. /// Load an input into a writer context.
  199. static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper,
  200. WriterContext *WC) {
  201. std::unique_lock<std::mutex> CtxGuard{WC->Lock};
  202. // Copy the filename, because llvm::ThreadPool copied the input "const
  203. // WeightedFile &" by value, making a reference to the filename within it
  204. // invalid outside of this packaged task.
  205. std::string Filename = Input.Filename;
  206. auto ReaderOrErr = InstrProfReader::create(Input.Filename);
  207. if (Error E = ReaderOrErr.takeError()) {
  208. // Skip the empty profiles by returning sliently.
  209. instrprof_error IPE = InstrProfError::take(std::move(E));
  210. if (IPE != instrprof_error::empty_raw_profile)
  211. WC->Errors.emplace_back(make_error<InstrProfError>(IPE), Filename);
  212. return;
  213. }
  214. auto Reader = std::move(ReaderOrErr.get());
  215. bool IsIRProfile = Reader->isIRLevelProfile();
  216. bool HasCSIRProfile = Reader->hasCSIRLevelProfile();
  217. if (WC->Writer.setIsIRLevelProfile(IsIRProfile, HasCSIRProfile)) {
  218. WC->Errors.emplace_back(
  219. make_error<StringError>(
  220. "Merge IR generated profile with Clang generated profile.",
  221. std::error_code()),
  222. Filename);
  223. return;
  224. }
  225. WC->Writer.setInstrEntryBBEnabled(Reader->instrEntryBBEnabled());
  226. for (auto &I : *Reader) {
  227. if (Remapper)
  228. I.Name = (*Remapper)(I.Name);
  229. const StringRef FuncName = I.Name;
  230. bool Reported = false;
  231. WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) {
  232. if (Reported) {
  233. consumeError(std::move(E));
  234. return;
  235. }
  236. Reported = true;
  237. // Only show hint the first time an error occurs.
  238. instrprof_error IPE = InstrProfError::take(std::move(E));
  239. std::unique_lock<std::mutex> ErrGuard{WC->ErrLock};
  240. bool firstTime = WC->WriterErrorCodes.insert(IPE).second;
  241. handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename,
  242. FuncName, firstTime);
  243. });
  244. }
  245. if (Reader->hasError())
  246. if (Error E = Reader->getError())
  247. WC->Errors.emplace_back(std::move(E), Filename);
  248. }
  249. /// Merge the \p Src writer context into \p Dst.
  250. static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) {
  251. for (auto &ErrorPair : Src->Errors)
  252. Dst->Errors.push_back(std::move(ErrorPair));
  253. Src->Errors.clear();
  254. Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) {
  255. instrprof_error IPE = InstrProfError::take(std::move(E));
  256. std::unique_lock<std::mutex> ErrGuard{Dst->ErrLock};
  257. bool firstTime = Dst->WriterErrorCodes.insert(IPE).second;
  258. if (firstTime)
  259. warn(toString(make_error<InstrProfError>(IPE)));
  260. });
  261. }
  262. static void writeInstrProfile(StringRef OutputFilename,
  263. ProfileFormat OutputFormat,
  264. InstrProfWriter &Writer) {
  265. std::error_code EC;
  266. raw_fd_ostream Output(OutputFilename.data(), EC,
  267. OutputFormat == PF_Text ? sys::fs::OF_Text
  268. : sys::fs::OF_None);
  269. if (EC)
  270. exitWithErrorCode(EC, OutputFilename);
  271. if (OutputFormat == PF_Text) {
  272. if (Error E = Writer.writeText(Output))
  273. exitWithError(std::move(E));
  274. } else {
  275. Writer.write(Output);
  276. }
  277. }
  278. static void mergeInstrProfile(const WeightedFileVector &Inputs,
  279. SymbolRemapper *Remapper,
  280. StringRef OutputFilename,
  281. ProfileFormat OutputFormat, bool OutputSparse,
  282. unsigned NumThreads, FailureMode FailMode) {
  283. if (OutputFilename.compare("-") == 0)
  284. exitWithError("Cannot write indexed profdata format to stdout.");
  285. if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary &&
  286. OutputFormat != PF_Ext_Binary && OutputFormat != PF_Text)
  287. exitWithError("Unknown format is specified.");
  288. std::mutex ErrorLock;
  289. SmallSet<instrprof_error, 4> WriterErrorCodes;
  290. // If NumThreads is not specified, auto-detect a good default.
  291. if (NumThreads == 0)
  292. NumThreads = std::min(hardware_concurrency().compute_thread_count(),
  293. unsigned((Inputs.size() + 1) / 2));
  294. // FIXME: There's a bug here, where setting NumThreads = Inputs.size() fails
  295. // the merge_empty_profile.test because the InstrProfWriter.ProfileKind isn't
  296. // merged, thus the emitted file ends up with a PF_Unknown kind.
  297. // Initialize the writer contexts.
  298. SmallVector<std::unique_ptr<WriterContext>, 4> Contexts;
  299. for (unsigned I = 0; I < NumThreads; ++I)
  300. Contexts.emplace_back(std::make_unique<WriterContext>(
  301. OutputSparse, ErrorLock, WriterErrorCodes));
  302. if (NumThreads == 1) {
  303. for (const auto &Input : Inputs)
  304. loadInput(Input, Remapper, Contexts[0].get());
  305. } else {
  306. ThreadPool Pool(hardware_concurrency(NumThreads));
  307. // Load the inputs in parallel (N/NumThreads serial steps).
  308. unsigned Ctx = 0;
  309. for (const auto &Input : Inputs) {
  310. Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get());
  311. Ctx = (Ctx + 1) % NumThreads;
  312. }
  313. Pool.wait();
  314. // Merge the writer contexts together (~ lg(NumThreads) serial steps).
  315. unsigned Mid = Contexts.size() / 2;
  316. unsigned End = Contexts.size();
  317. assert(Mid > 0 && "Expected more than one context");
  318. do {
  319. for (unsigned I = 0; I < Mid; ++I)
  320. Pool.async(mergeWriterContexts, Contexts[I].get(),
  321. Contexts[I + Mid].get());
  322. Pool.wait();
  323. if (End & 1) {
  324. Pool.async(mergeWriterContexts, Contexts[0].get(),
  325. Contexts[End - 1].get());
  326. Pool.wait();
  327. }
  328. End = Mid;
  329. Mid /= 2;
  330. } while (Mid > 0);
  331. }
  332. // Handle deferred errors encountered during merging. If the number of errors
  333. // is equal to the number of inputs the merge failed.
  334. unsigned NumErrors = 0;
  335. for (std::unique_ptr<WriterContext> &WC : Contexts) {
  336. for (auto &ErrorPair : WC->Errors) {
  337. ++NumErrors;
  338. warn(toString(std::move(ErrorPair.first)), ErrorPair.second);
  339. }
  340. }
  341. if (NumErrors == Inputs.size() ||
  342. (NumErrors > 0 && FailMode == failIfAnyAreInvalid))
  343. exitWithError("No profiles could be merged.");
  344. writeInstrProfile(OutputFilename, OutputFormat, Contexts[0]->Writer);
  345. }
  346. /// The profile entry for a function in instrumentation profile.
  347. struct InstrProfileEntry {
  348. uint64_t MaxCount = 0;
  349. float ZeroCounterRatio = 0.0;
  350. InstrProfRecord *ProfRecord;
  351. InstrProfileEntry(InstrProfRecord *Record);
  352. InstrProfileEntry() = default;
  353. };
  354. InstrProfileEntry::InstrProfileEntry(InstrProfRecord *Record) {
  355. ProfRecord = Record;
  356. uint64_t CntNum = Record->Counts.size();
  357. uint64_t ZeroCntNum = 0;
  358. for (size_t I = 0; I < CntNum; ++I) {
  359. MaxCount = std::max(MaxCount, Record->Counts[I]);
  360. ZeroCntNum += !Record->Counts[I];
  361. }
  362. ZeroCounterRatio = (float)ZeroCntNum / CntNum;
  363. }
  364. /// Either set all the counters in the instr profile entry \p IFE to -1
  365. /// in order to drop the profile or scale up the counters in \p IFP to
  366. /// be above hot threshold. We use the ratio of zero counters in the
  367. /// profile of a function to decide the profile is helpful or harmful
  368. /// for performance, and to choose whether to scale up or drop it.
  369. static void updateInstrProfileEntry(InstrProfileEntry &IFE,
  370. uint64_t HotInstrThreshold,
  371. float ZeroCounterThreshold) {
  372. InstrProfRecord *ProfRecord = IFE.ProfRecord;
  373. if (!IFE.MaxCount || IFE.ZeroCounterRatio > ZeroCounterThreshold) {
  374. // If all or most of the counters of the function are zero, the
  375. // profile is unaccountable and shuld be dropped. Reset all the
  376. // counters to be -1 and PGO profile-use will drop the profile.
  377. // All counters being -1 also implies that the function is hot so
  378. // PGO profile-use will also set the entry count metadata to be
  379. // above hot threshold.
  380. for (size_t I = 0; I < ProfRecord->Counts.size(); ++I)
  381. ProfRecord->Counts[I] = -1;
  382. return;
  383. }
  384. // Scale up the MaxCount to be multiple times above hot threshold.
  385. const unsigned MultiplyFactor = 3;
  386. uint64_t Numerator = HotInstrThreshold * MultiplyFactor;
  387. uint64_t Denominator = IFE.MaxCount;
  388. ProfRecord->scale(Numerator, Denominator, [&](instrprof_error E) {
  389. warn(toString(make_error<InstrProfError>(E)));
  390. });
  391. }
  392. const uint64_t ColdPercentileIdx = 15;
  393. const uint64_t HotPercentileIdx = 11;
  394. /// Adjust the instr profile in \p WC based on the sample profile in
  395. /// \p Reader.
  396. static void
  397. adjustInstrProfile(std::unique_ptr<WriterContext> &WC,
  398. std::unique_ptr<sampleprof::SampleProfileReader> &Reader,
  399. unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
  400. unsigned InstrProfColdThreshold) {
  401. // Function to its entry in instr profile.
  402. StringMap<InstrProfileEntry> InstrProfileMap;
  403. InstrProfSummaryBuilder IPBuilder(ProfileSummaryBuilder::DefaultCutoffs);
  404. for (auto &PD : WC->Writer.getProfileData()) {
  405. // Populate IPBuilder.
  406. for (const auto &PDV : PD.getValue()) {
  407. InstrProfRecord Record = PDV.second;
  408. IPBuilder.addRecord(Record);
  409. }
  410. // If a function has multiple entries in instr profile, skip it.
  411. if (PD.getValue().size() != 1)
  412. continue;
  413. // Initialize InstrProfileMap.
  414. InstrProfRecord *R = &PD.getValue().begin()->second;
  415. InstrProfileMap[PD.getKey()] = InstrProfileEntry(R);
  416. }
  417. ProfileSummary InstrPS = *IPBuilder.getSummary();
  418. ProfileSummary SamplePS = Reader->getSummary();
  419. // Compute cold thresholds for instr profile and sample profile.
  420. uint64_t ColdSampleThreshold =
  421. ProfileSummaryBuilder::getEntryForPercentile(
  422. SamplePS.getDetailedSummary(),
  423. ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
  424. .MinCount;
  425. uint64_t HotInstrThreshold =
  426. ProfileSummaryBuilder::getEntryForPercentile(
  427. InstrPS.getDetailedSummary(),
  428. ProfileSummaryBuilder::DefaultCutoffs[HotPercentileIdx])
  429. .MinCount;
  430. uint64_t ColdInstrThreshold =
  431. InstrProfColdThreshold
  432. ? InstrProfColdThreshold
  433. : ProfileSummaryBuilder::getEntryForPercentile(
  434. InstrPS.getDetailedSummary(),
  435. ProfileSummaryBuilder::DefaultCutoffs[ColdPercentileIdx])
  436. .MinCount;
  437. // Find hot/warm functions in sample profile which is cold in instr profile
  438. // and adjust the profiles of those functions in the instr profile.
  439. for (const auto &PD : Reader->getProfiles()) {
  440. StringRef FName = PD.getKey();
  441. const sampleprof::FunctionSamples &FS = PD.getValue();
  442. auto It = InstrProfileMap.find(FName);
  443. if (FS.getHeadSamples() > ColdSampleThreshold &&
  444. It != InstrProfileMap.end() &&
  445. It->second.MaxCount <= ColdInstrThreshold &&
  446. FS.getBodySamples().size() >= SupplMinSizeThreshold) {
  447. updateInstrProfileEntry(It->second, HotInstrThreshold,
  448. ZeroCounterThreshold);
  449. }
  450. }
  451. }
  452. /// The main function to supplement instr profile with sample profile.
  453. /// \Inputs contains the instr profile. \p SampleFilename specifies the
  454. /// sample profile. \p OutputFilename specifies the output profile name.
  455. /// \p OutputFormat specifies the output profile format. \p OutputSparse
  456. /// specifies whether to generate sparse profile. \p SupplMinSizeThreshold
  457. /// specifies the minimal size for the functions whose profile will be
  458. /// adjusted. \p ZeroCounterThreshold is the threshold to check whether
  459. /// a function contains too many zero counters and whether its profile
  460. /// should be dropped. \p InstrProfColdThreshold is the user specified
  461. /// cold threshold which will override the cold threshold got from the
  462. /// instr profile summary.
  463. static void supplementInstrProfile(
  464. const WeightedFileVector &Inputs, StringRef SampleFilename,
  465. StringRef OutputFilename, ProfileFormat OutputFormat, bool OutputSparse,
  466. unsigned SupplMinSizeThreshold, float ZeroCounterThreshold,
  467. unsigned InstrProfColdThreshold) {
  468. if (OutputFilename.compare("-") == 0)
  469. exitWithError("Cannot write indexed profdata format to stdout.");
  470. if (Inputs.size() != 1)
  471. exitWithError("Expect one input to be an instr profile.");
  472. if (Inputs[0].Weight != 1)
  473. exitWithError("Expect instr profile doesn't have weight.");
  474. StringRef InstrFilename = Inputs[0].Filename;
  475. // Read sample profile.
  476. LLVMContext Context;
  477. auto ReaderOrErr =
  478. sampleprof::SampleProfileReader::create(SampleFilename.str(), Context);
  479. if (std::error_code EC = ReaderOrErr.getError())
  480. exitWithErrorCode(EC, SampleFilename);
  481. auto Reader = std::move(ReaderOrErr.get());
  482. if (std::error_code EC = Reader->read())
  483. exitWithErrorCode(EC, SampleFilename);
  484. // Read instr profile.
  485. std::mutex ErrorLock;
  486. SmallSet<instrprof_error, 4> WriterErrorCodes;
  487. auto WC = std::make_unique<WriterContext>(OutputSparse, ErrorLock,
  488. WriterErrorCodes);
  489. loadInput(Inputs[0], nullptr, WC.get());
  490. if (WC->Errors.size() > 0)
  491. exitWithError(std::move(WC->Errors[0].first), InstrFilename);
  492. adjustInstrProfile(WC, Reader, SupplMinSizeThreshold, ZeroCounterThreshold,
  493. InstrProfColdThreshold);
  494. writeInstrProfile(OutputFilename, OutputFormat, WC->Writer);
  495. }
  496. /// Make a copy of the given function samples with all symbol names remapped
  497. /// by the provided symbol remapper.
  498. static sampleprof::FunctionSamples
  499. remapSamples(const sampleprof::FunctionSamples &Samples,
  500. SymbolRemapper &Remapper, sampleprof_error &Error) {
  501. sampleprof::FunctionSamples Result;
  502. Result.setName(Remapper(Samples.getName()));
  503. Result.addTotalSamples(Samples.getTotalSamples());
  504. Result.addHeadSamples(Samples.getHeadSamples());
  505. for (const auto &BodySample : Samples.getBodySamples()) {
  506. Result.addBodySamples(BodySample.first.LineOffset,
  507. BodySample.first.Discriminator,
  508. BodySample.second.getSamples());
  509. for (const auto &Target : BodySample.second.getCallTargets()) {
  510. Result.addCalledTargetSamples(BodySample.first.LineOffset,
  511. BodySample.first.Discriminator,
  512. Remapper(Target.first()), Target.second);
  513. }
  514. }
  515. for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
  516. sampleprof::FunctionSamplesMap &Target =
  517. Result.functionSamplesAt(CallsiteSamples.first);
  518. for (const auto &Callsite : CallsiteSamples.second) {
  519. sampleprof::FunctionSamples Remapped =
  520. remapSamples(Callsite.second, Remapper, Error);
  521. MergeResult(Error,
  522. Target[std::string(Remapped.getName())].merge(Remapped));
  523. }
  524. }
  525. return Result;
  526. }
  527. static sampleprof::SampleProfileFormat FormatMap[] = {
  528. sampleprof::SPF_None,
  529. sampleprof::SPF_Text,
  530. sampleprof::SPF_Compact_Binary,
  531. sampleprof::SPF_Ext_Binary,
  532. sampleprof::SPF_GCC,
  533. sampleprof::SPF_Binary};
  534. static std::unique_ptr<MemoryBuffer>
  535. getInputFileBuf(const StringRef &InputFile) {
  536. if (InputFile == "")
  537. return {};
  538. auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile);
  539. if (!BufOrError)
  540. exitWithErrorCode(BufOrError.getError(), InputFile);
  541. return std::move(*BufOrError);
  542. }
  543. static void populateProfileSymbolList(MemoryBuffer *Buffer,
  544. sampleprof::ProfileSymbolList &PSL) {
  545. if (!Buffer)
  546. return;
  547. SmallVector<StringRef, 32> SymbolVec;
  548. StringRef Data = Buffer->getBuffer();
  549. Data.split(SymbolVec, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  550. for (StringRef symbol : SymbolVec)
  551. PSL.add(symbol);
  552. }
  553. static void handleExtBinaryWriter(sampleprof::SampleProfileWriter &Writer,
  554. ProfileFormat OutputFormat,
  555. MemoryBuffer *Buffer,
  556. sampleprof::ProfileSymbolList &WriterList,
  557. bool CompressAllSections, bool UseMD5,
  558. bool GenPartialProfile) {
  559. populateProfileSymbolList(Buffer, WriterList);
  560. if (WriterList.size() > 0 && OutputFormat != PF_Ext_Binary)
  561. warn("Profile Symbol list is not empty but the output format is not "
  562. "ExtBinary format. The list will be lost in the output. ");
  563. Writer.setProfileSymbolList(&WriterList);
  564. if (CompressAllSections) {
  565. if (OutputFormat != PF_Ext_Binary)
  566. warn("-compress-all-section is ignored. Specify -extbinary to enable it");
  567. else
  568. Writer.setToCompressAllSections();
  569. }
  570. if (UseMD5) {
  571. if (OutputFormat != PF_Ext_Binary)
  572. warn("-use-md5 is ignored. Specify -extbinary to enable it");
  573. else
  574. Writer.setUseMD5();
  575. }
  576. if (GenPartialProfile) {
  577. if (OutputFormat != PF_Ext_Binary)
  578. warn("-gen-partial-profile is ignored. Specify -extbinary to enable it");
  579. else
  580. Writer.setPartialProfile();
  581. }
  582. }
  583. static void
  584. mergeSampleProfile(const WeightedFileVector &Inputs, SymbolRemapper *Remapper,
  585. StringRef OutputFilename, ProfileFormat OutputFormat,
  586. StringRef ProfileSymbolListFile, bool CompressAllSections,
  587. bool UseMD5, bool GenPartialProfile, FailureMode FailMode) {
  588. using namespace sampleprof;
  589. StringMap<FunctionSamples> ProfileMap;
  590. SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers;
  591. LLVMContext Context;
  592. sampleprof::ProfileSymbolList WriterList;
  593. Optional<bool> ProfileIsProbeBased;
  594. for (const auto &Input : Inputs) {
  595. auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context);
  596. if (std::error_code EC = ReaderOrErr.getError()) {
  597. warnOrExitGivenError(FailMode, EC, Input.Filename);
  598. continue;
  599. }
  600. // We need to keep the readers around until after all the files are
  601. // read so that we do not lose the function names stored in each
  602. // reader's memory. The function names are needed to write out the
  603. // merged profile map.
  604. Readers.push_back(std::move(ReaderOrErr.get()));
  605. const auto Reader = Readers.back().get();
  606. if (std::error_code EC = Reader->read()) {
  607. warnOrExitGivenError(FailMode, EC, Input.Filename);
  608. Readers.pop_back();
  609. continue;
  610. }
  611. StringMap<FunctionSamples> &Profiles = Reader->getProfiles();
  612. if (ProfileIsProbeBased &&
  613. ProfileIsProbeBased != FunctionSamples::ProfileIsProbeBased)
  614. exitWithError(
  615. "cannot merge probe-based profile with non-probe-based profile");
  616. ProfileIsProbeBased = FunctionSamples::ProfileIsProbeBased;
  617. for (StringMap<FunctionSamples>::iterator I = Profiles.begin(),
  618. E = Profiles.end();
  619. I != E; ++I) {
  620. sampleprof_error Result = sampleprof_error::success;
  621. FunctionSamples Remapped =
  622. Remapper ? remapSamples(I->second, *Remapper, Result)
  623. : FunctionSamples();
  624. FunctionSamples &Samples = Remapper ? Remapped : I->second;
  625. StringRef FName = Samples.getNameWithContext(true);
  626. MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight));
  627. if (Result != sampleprof_error::success) {
  628. std::error_code EC = make_error_code(Result);
  629. handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName);
  630. }
  631. }
  632. std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
  633. Reader->getProfileSymbolList();
  634. if (ReaderList)
  635. WriterList.merge(*ReaderList);
  636. }
  637. auto WriterOrErr =
  638. SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]);
  639. if (std::error_code EC = WriterOrErr.getError())
  640. exitWithErrorCode(EC, OutputFilename);
  641. auto Writer = std::move(WriterOrErr.get());
  642. // WriterList will have StringRef refering to string in Buffer.
  643. // Make sure Buffer lives as long as WriterList.
  644. auto Buffer = getInputFileBuf(ProfileSymbolListFile);
  645. handleExtBinaryWriter(*Writer, OutputFormat, Buffer.get(), WriterList,
  646. CompressAllSections, UseMD5, GenPartialProfile);
  647. Writer->write(ProfileMap);
  648. }
  649. static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) {
  650. StringRef WeightStr, FileName;
  651. std::tie(WeightStr, FileName) = WeightedFilename.split(',');
  652. uint64_t Weight;
  653. if (WeightStr.getAsInteger(10, Weight) || Weight < 1)
  654. exitWithError("Input weight must be a positive integer.");
  655. return {std::string(FileName), Weight};
  656. }
  657. static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) {
  658. StringRef Filename = WF.Filename;
  659. uint64_t Weight = WF.Weight;
  660. // If it's STDIN just pass it on.
  661. if (Filename == "-") {
  662. WNI.push_back({std::string(Filename), Weight});
  663. return;
  664. }
  665. llvm::sys::fs::file_status Status;
  666. llvm::sys::fs::status(Filename, Status);
  667. if (!llvm::sys::fs::exists(Status))
  668. exitWithErrorCode(make_error_code(errc::no_such_file_or_directory),
  669. Filename);
  670. // If it's a source file, collect it.
  671. if (llvm::sys::fs::is_regular_file(Status)) {
  672. WNI.push_back({std::string(Filename), Weight});
  673. return;
  674. }
  675. if (llvm::sys::fs::is_directory(Status)) {
  676. std::error_code EC;
  677. for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E;
  678. F != E && !EC; F.increment(EC)) {
  679. if (llvm::sys::fs::is_regular_file(F->path())) {
  680. addWeightedInput(WNI, {F->path(), Weight});
  681. }
  682. }
  683. if (EC)
  684. exitWithErrorCode(EC, Filename);
  685. }
  686. }
  687. static void parseInputFilenamesFile(MemoryBuffer *Buffer,
  688. WeightedFileVector &WFV) {
  689. if (!Buffer)
  690. return;
  691. SmallVector<StringRef, 8> Entries;
  692. StringRef Data = Buffer->getBuffer();
  693. Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
  694. for (const StringRef &FileWeightEntry : Entries) {
  695. StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r");
  696. // Skip comments.
  697. if (SanitizedEntry.startswith("#"))
  698. continue;
  699. // If there's no comma, it's an unweighted profile.
  700. else if (SanitizedEntry.find(',') == StringRef::npos)
  701. addWeightedInput(WFV, {std::string(SanitizedEntry), 1});
  702. else
  703. addWeightedInput(WFV, parseWeightedFile(SanitizedEntry));
  704. }
  705. }
  706. static int merge_main(int argc, const char *argv[]) {
  707. cl::list<std::string> InputFilenames(cl::Positional,
  708. cl::desc("<filename...>"));
  709. cl::list<std::string> WeightedInputFilenames("weighted-input",
  710. cl::desc("<weight>,<filename>"));
  711. cl::opt<std::string> InputFilenamesFile(
  712. "input-files", cl::init(""),
  713. cl::desc("Path to file containing newline-separated "
  714. "[<weight>,]<filename> entries"));
  715. cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"),
  716. cl::aliasopt(InputFilenamesFile));
  717. cl::opt<bool> DumpInputFileList(
  718. "dump-input-file-list", cl::init(false), cl::Hidden,
  719. cl::desc("Dump the list of input files and their weights, then exit"));
  720. cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"),
  721. cl::desc("Symbol remapping file"));
  722. cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"),
  723. cl::aliasopt(RemappingFile));
  724. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  725. cl::init("-"), cl::Required,
  726. cl::desc("Output file"));
  727. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  728. cl::aliasopt(OutputFilename));
  729. cl::opt<ProfileKinds> ProfileKind(
  730. cl::desc("Profile kind:"), cl::init(instr),
  731. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  732. clEnumVal(sample, "Sample profile")));
  733. cl::opt<ProfileFormat> OutputFormat(
  734. cl::desc("Format of output profile"), cl::init(PF_Binary),
  735. cl::values(
  736. clEnumValN(PF_Binary, "binary", "Binary encoding (default)"),
  737. clEnumValN(PF_Compact_Binary, "compbinary",
  738. "Compact binary encoding"),
  739. clEnumValN(PF_Ext_Binary, "extbinary", "Extensible binary encoding"),
  740. clEnumValN(PF_Text, "text", "Text encoding"),
  741. clEnumValN(PF_GCC, "gcc",
  742. "GCC encoding (only meaningful for -sample)")));
  743. cl::opt<FailureMode> FailureMode(
  744. "failure-mode", cl::init(failIfAnyAreInvalid), cl::desc("Failure mode:"),
  745. cl::values(clEnumValN(failIfAnyAreInvalid, "any",
  746. "Fail if any profile is invalid."),
  747. clEnumValN(failIfAllAreInvalid, "all",
  748. "Fail only if all profiles are invalid.")));
  749. cl::opt<bool> OutputSparse("sparse", cl::init(false),
  750. cl::desc("Generate a sparse profile (only meaningful for -instr)"));
  751. cl::opt<unsigned> NumThreads(
  752. "num-threads", cl::init(0),
  753. cl::desc("Number of merge threads to use (default: autodetect)"));
  754. cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"),
  755. cl::aliasopt(NumThreads));
  756. cl::opt<std::string> ProfileSymbolListFile(
  757. "prof-sym-list", cl::init(""),
  758. cl::desc("Path to file containing the list of function symbols "
  759. "used to populate profile symbol list"));
  760. cl::opt<bool> CompressAllSections(
  761. "compress-all-sections", cl::init(false), cl::Hidden,
  762. cl::desc("Compress all sections when writing the profile (only "
  763. "meaningful for -extbinary)"));
  764. cl::opt<bool> UseMD5(
  765. "use-md5", cl::init(false), cl::Hidden,
  766. cl::desc("Choose to use MD5 to represent string in name table (only "
  767. "meaningful for -extbinary)"));
  768. cl::opt<bool> GenPartialProfile(
  769. "gen-partial-profile", cl::init(false), cl::Hidden,
  770. cl::desc("Generate a partial profile (only meaningful for -extbinary)"));
  771. cl::opt<std::string> SupplInstrWithSample(
  772. "supplement-instr-with-sample", cl::init(""), cl::Hidden,
  773. cl::desc("Supplement an instr profile with sample profile, to correct "
  774. "the profile unrepresentativeness issue. The sample "
  775. "profile is the input of the flag. Output will be in instr "
  776. "format (The flag only works with -instr)"));
  777. cl::opt<float> ZeroCounterThreshold(
  778. "zero-counter-threshold", cl::init(0.7), cl::Hidden,
  779. cl::desc("For the function which is cold in instr profile but hot in "
  780. "sample profile, if the ratio of the number of zero counters "
  781. "divided by the the total number of counters is above the "
  782. "threshold, the profile of the function will be regarded as "
  783. "being harmful for performance and will be dropped. "));
  784. cl::opt<unsigned> SupplMinSizeThreshold(
  785. "suppl-min-size-threshold", cl::init(10), cl::Hidden,
  786. cl::desc("If the size of a function is smaller than the threshold, "
  787. "assume it can be inlined by PGO early inliner and it won't "
  788. "be adjusted based on sample profile. "));
  789. cl::opt<unsigned> InstrProfColdThreshold(
  790. "instr-prof-cold-threshold", cl::init(0), cl::Hidden,
  791. cl::desc("User specified cold threshold for instr profile which will "
  792. "override the cold threshold got from profile summary. "));
  793. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
  794. WeightedFileVector WeightedInputs;
  795. for (StringRef Filename : InputFilenames)
  796. addWeightedInput(WeightedInputs, {std::string(Filename), 1});
  797. for (StringRef WeightedFilename : WeightedInputFilenames)
  798. addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename));
  799. // Make sure that the file buffer stays alive for the duration of the
  800. // weighted input vector's lifetime.
  801. auto Buffer = getInputFileBuf(InputFilenamesFile);
  802. parseInputFilenamesFile(Buffer.get(), WeightedInputs);
  803. if (WeightedInputs.empty())
  804. exitWithError("No input files specified. See " +
  805. sys::path::filename(argv[0]) + " -help");
  806. if (DumpInputFileList) {
  807. for (auto &WF : WeightedInputs)
  808. outs() << WF.Weight << "," << WF.Filename << "\n";
  809. return 0;
  810. }
  811. std::unique_ptr<SymbolRemapper> Remapper;
  812. if (!RemappingFile.empty())
  813. Remapper = SymbolRemapper::create(RemappingFile);
  814. if (!SupplInstrWithSample.empty()) {
  815. if (ProfileKind != instr)
  816. exitWithError(
  817. "-supplement-instr-with-sample can only work with -instr. ");
  818. supplementInstrProfile(WeightedInputs, SupplInstrWithSample, OutputFilename,
  819. OutputFormat, OutputSparse, SupplMinSizeThreshold,
  820. ZeroCounterThreshold, InstrProfColdThreshold);
  821. return 0;
  822. }
  823. if (ProfileKind == instr)
  824. mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename,
  825. OutputFormat, OutputSparse, NumThreads, FailureMode);
  826. else
  827. mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename,
  828. OutputFormat, ProfileSymbolListFile, CompressAllSections,
  829. UseMD5, GenPartialProfile, FailureMode);
  830. return 0;
  831. }
  832. /// Computer the overlap b/w profile BaseFilename and profile TestFilename.
  833. static void overlapInstrProfile(const std::string &BaseFilename,
  834. const std::string &TestFilename,
  835. const OverlapFuncFilters &FuncFilter,
  836. raw_fd_ostream &OS, bool IsCS) {
  837. std::mutex ErrorLock;
  838. SmallSet<instrprof_error, 4> WriterErrorCodes;
  839. WriterContext Context(false, ErrorLock, WriterErrorCodes);
  840. WeightedFile WeightedInput{BaseFilename, 1};
  841. OverlapStats Overlap;
  842. Error E = Overlap.accumulateCounts(BaseFilename, TestFilename, IsCS);
  843. if (E)
  844. exitWithError(std::move(E), "Error in getting profile count sums");
  845. if (Overlap.Base.CountSum < 1.0f) {
  846. OS << "Sum of edge counts for profile " << BaseFilename << " is 0.\n";
  847. exit(0);
  848. }
  849. if (Overlap.Test.CountSum < 1.0f) {
  850. OS << "Sum of edge counts for profile " << TestFilename << " is 0.\n";
  851. exit(0);
  852. }
  853. loadInput(WeightedInput, nullptr, &Context);
  854. overlapInput(BaseFilename, TestFilename, &Context, Overlap, FuncFilter, OS,
  855. IsCS);
  856. Overlap.dump(OS);
  857. }
  858. namespace {
  859. struct SampleOverlapStats {
  860. StringRef BaseName;
  861. StringRef TestName;
  862. // Number of overlap units
  863. uint64_t OverlapCount;
  864. // Total samples of overlap units
  865. uint64_t OverlapSample;
  866. // Number of and total samples of units that only present in base or test
  867. // profile
  868. uint64_t BaseUniqueCount;
  869. uint64_t BaseUniqueSample;
  870. uint64_t TestUniqueCount;
  871. uint64_t TestUniqueSample;
  872. // Number of units and total samples in base or test profile
  873. uint64_t BaseCount;
  874. uint64_t BaseSample;
  875. uint64_t TestCount;
  876. uint64_t TestSample;
  877. // Number of and total samples of units that present in at least one profile
  878. uint64_t UnionCount;
  879. uint64_t UnionSample;
  880. // Weighted similarity
  881. double Similarity;
  882. // For SampleOverlapStats instances representing functions, weights of the
  883. // function in base and test profiles
  884. double BaseWeight;
  885. double TestWeight;
  886. SampleOverlapStats()
  887. : OverlapCount(0), OverlapSample(0), BaseUniqueCount(0),
  888. BaseUniqueSample(0), TestUniqueCount(0), TestUniqueSample(0),
  889. BaseCount(0), BaseSample(0), TestCount(0), TestSample(0), UnionCount(0),
  890. UnionSample(0), Similarity(0.0), BaseWeight(0.0), TestWeight(0.0) {}
  891. };
  892. } // end anonymous namespace
  893. namespace {
  894. struct FuncSampleStats {
  895. uint64_t SampleSum;
  896. uint64_t MaxSample;
  897. uint64_t HotBlockCount;
  898. FuncSampleStats() : SampleSum(0), MaxSample(0), HotBlockCount(0) {}
  899. FuncSampleStats(uint64_t SampleSum, uint64_t MaxSample,
  900. uint64_t HotBlockCount)
  901. : SampleSum(SampleSum), MaxSample(MaxSample),
  902. HotBlockCount(HotBlockCount) {}
  903. };
  904. } // end anonymous namespace
  905. namespace {
  906. enum MatchStatus { MS_Match, MS_FirstUnique, MS_SecondUnique, MS_None };
  907. // Class for updating merging steps for two sorted maps. The class should be
  908. // instantiated with a map iterator type.
  909. template <class T> class MatchStep {
  910. public:
  911. MatchStep() = delete;
  912. MatchStep(T FirstIter, T FirstEnd, T SecondIter, T SecondEnd)
  913. : FirstIter(FirstIter), FirstEnd(FirstEnd), SecondIter(SecondIter),
  914. SecondEnd(SecondEnd), Status(MS_None) {}
  915. bool areBothFinished() const {
  916. return (FirstIter == FirstEnd && SecondIter == SecondEnd);
  917. }
  918. bool isFirstFinished() const { return FirstIter == FirstEnd; }
  919. bool isSecondFinished() const { return SecondIter == SecondEnd; }
  920. /// Advance one step based on the previous match status unless the previous
  921. /// status is MS_None. Then update Status based on the comparison between two
  922. /// container iterators at the current step. If the previous status is
  923. /// MS_None, it means two iterators are at the beginning and no comparison has
  924. /// been made, so we simply update Status without advancing the iterators.
  925. void updateOneStep();
  926. T getFirstIter() const { return FirstIter; }
  927. T getSecondIter() const { return SecondIter; }
  928. MatchStatus getMatchStatus() const { return Status; }
  929. private:
  930. // Current iterator and end iterator of the first container.
  931. T FirstIter;
  932. T FirstEnd;
  933. // Current iterator and end iterator of the second container.
  934. T SecondIter;
  935. T SecondEnd;
  936. // Match status of the current step.
  937. MatchStatus Status;
  938. };
  939. } // end anonymous namespace
  940. template <class T> void MatchStep<T>::updateOneStep() {
  941. switch (Status) {
  942. case MS_Match:
  943. ++FirstIter;
  944. ++SecondIter;
  945. break;
  946. case MS_FirstUnique:
  947. ++FirstIter;
  948. break;
  949. case MS_SecondUnique:
  950. ++SecondIter;
  951. break;
  952. case MS_None:
  953. break;
  954. }
  955. // Update Status according to iterators at the current step.
  956. if (areBothFinished())
  957. return;
  958. if (FirstIter != FirstEnd &&
  959. (SecondIter == SecondEnd || FirstIter->first < SecondIter->first))
  960. Status = MS_FirstUnique;
  961. else if (SecondIter != SecondEnd &&
  962. (FirstIter == FirstEnd || SecondIter->first < FirstIter->first))
  963. Status = MS_SecondUnique;
  964. else
  965. Status = MS_Match;
  966. }
  967. // Return the sum of line/block samples, the max line/block sample, and the
  968. // number of line/block samples above the given threshold in a function
  969. // including its inlinees.
  970. static void getFuncSampleStats(const sampleprof::FunctionSamples &Func,
  971. FuncSampleStats &FuncStats,
  972. uint64_t HotThreshold) {
  973. for (const auto &L : Func.getBodySamples()) {
  974. uint64_t Sample = L.second.getSamples();
  975. FuncStats.SampleSum += Sample;
  976. FuncStats.MaxSample = std::max(FuncStats.MaxSample, Sample);
  977. if (Sample >= HotThreshold)
  978. ++FuncStats.HotBlockCount;
  979. }
  980. for (const auto &C : Func.getCallsiteSamples()) {
  981. for (const auto &F : C.second)
  982. getFuncSampleStats(F.second, FuncStats, HotThreshold);
  983. }
  984. }
  985. /// Predicate that determines if a function is hot with a given threshold. We
  986. /// keep it separate from its callsites for possible extension in the future.
  987. static bool isFunctionHot(const FuncSampleStats &FuncStats,
  988. uint64_t HotThreshold) {
  989. // We intentionally compare the maximum sample count in a function with the
  990. // HotThreshold to get an approximate determination on hot functions.
  991. return (FuncStats.MaxSample >= HotThreshold);
  992. }
  993. namespace {
  994. class SampleOverlapAggregator {
  995. public:
  996. SampleOverlapAggregator(const std::string &BaseFilename,
  997. const std::string &TestFilename,
  998. double LowSimilarityThreshold, double Epsilon,
  999. const OverlapFuncFilters &FuncFilter)
  1000. : BaseFilename(BaseFilename), TestFilename(TestFilename),
  1001. LowSimilarityThreshold(LowSimilarityThreshold), Epsilon(Epsilon),
  1002. FuncFilter(FuncFilter) {}
  1003. /// Detect 0-sample input profile and report to output stream. This interface
  1004. /// should be called after loadProfiles().
  1005. bool detectZeroSampleProfile(raw_fd_ostream &OS) const;
  1006. /// Write out function-level similarity statistics for functions specified by
  1007. /// options --function, --value-cutoff, and --similarity-cutoff.
  1008. void dumpFuncSimilarity(raw_fd_ostream &OS) const;
  1009. /// Write out program-level similarity and overlap statistics.
  1010. void dumpProgramSummary(raw_fd_ostream &OS) const;
  1011. /// Write out hot-function and hot-block statistics for base_profile,
  1012. /// test_profile, and their overlap. For both cases, the overlap HO is
  1013. /// calculated as follows:
  1014. /// Given the number of functions (or blocks) that are hot in both profiles
  1015. /// HCommon and the number of functions (or blocks) that are hot in at
  1016. /// least one profile HUnion, HO = HCommon / HUnion.
  1017. void dumpHotFuncAndBlockOverlap(raw_fd_ostream &OS) const;
  1018. /// This function tries matching functions in base and test profiles. For each
  1019. /// pair of matched functions, it aggregates the function-level
  1020. /// similarity into a profile-level similarity. It also dump function-level
  1021. /// similarity information of functions specified by --function,
  1022. /// --value-cutoff, and --similarity-cutoff options. The program-level
  1023. /// similarity PS is computed as follows:
  1024. /// Given function-level similarity FS(A) for all function A, the
  1025. /// weight of function A in base profile WB(A), and the weight of function
  1026. /// A in test profile WT(A), compute PS(base_profile, test_profile) =
  1027. /// sum_A(FS(A) * avg(WB(A), WT(A))) ranging in [0.0f to 1.0f] with 0.0
  1028. /// meaning no-overlap.
  1029. void computeSampleProfileOverlap(raw_fd_ostream &OS);
  1030. /// Initialize ProfOverlap with the sum of samples in base and test
  1031. /// profiles. This function also computes and keeps the sum of samples and
  1032. /// max sample counts of each function in BaseStats and TestStats for later
  1033. /// use to avoid re-computations.
  1034. void initializeSampleProfileOverlap();
  1035. /// Load profiles specified by BaseFilename and TestFilename.
  1036. std::error_code loadProfiles();
  1037. private:
  1038. SampleOverlapStats ProfOverlap;
  1039. SampleOverlapStats HotFuncOverlap;
  1040. SampleOverlapStats HotBlockOverlap;
  1041. std::string BaseFilename;
  1042. std::string TestFilename;
  1043. std::unique_ptr<sampleprof::SampleProfileReader> BaseReader;
  1044. std::unique_ptr<sampleprof::SampleProfileReader> TestReader;
  1045. // BaseStats and TestStats hold FuncSampleStats for each function, with
  1046. // function name as the key.
  1047. StringMap<FuncSampleStats> BaseStats;
  1048. StringMap<FuncSampleStats> TestStats;
  1049. // Low similarity threshold in floating point number
  1050. double LowSimilarityThreshold;
  1051. // Block samples above BaseHotThreshold or TestHotThreshold are considered hot
  1052. // for tracking hot blocks.
  1053. uint64_t BaseHotThreshold;
  1054. uint64_t TestHotThreshold;
  1055. // A small threshold used to round the results of floating point accumulations
  1056. // to resolve imprecision.
  1057. const double Epsilon;
  1058. std::multimap<double, SampleOverlapStats, std::greater<double>>
  1059. FuncSimilarityDump;
  1060. // FuncFilter carries specifications in options --value-cutoff and
  1061. // --function.
  1062. OverlapFuncFilters FuncFilter;
  1063. // Column offsets for printing the function-level details table.
  1064. static const unsigned int TestWeightCol = 15;
  1065. static const unsigned int SimilarityCol = 30;
  1066. static const unsigned int OverlapCol = 43;
  1067. static const unsigned int BaseUniqueCol = 53;
  1068. static const unsigned int TestUniqueCol = 67;
  1069. static const unsigned int BaseSampleCol = 81;
  1070. static const unsigned int TestSampleCol = 96;
  1071. static const unsigned int FuncNameCol = 111;
  1072. /// Return a similarity of two line/block sample counters in the same
  1073. /// function in base and test profiles. The line/block-similarity BS(i) is
  1074. /// computed as follows:
  1075. /// For an offsets i, given the sample count at i in base profile BB(i),
  1076. /// the sample count at i in test profile BT(i), the sum of sample counts
  1077. /// in this function in base profile SB, and the sum of sample counts in
  1078. /// this function in test profile ST, compute BS(i) = 1.0 - fabs(BB(i)/SB -
  1079. /// BT(i)/ST), ranging in [0.0f to 1.0f] with 0.0 meaning no-overlap.
  1080. double computeBlockSimilarity(uint64_t BaseSample, uint64_t TestSample,
  1081. const SampleOverlapStats &FuncOverlap) const;
  1082. void updateHotBlockOverlap(uint64_t BaseSample, uint64_t TestSample,
  1083. uint64_t HotBlockCount);
  1084. void getHotFunctions(const StringMap<FuncSampleStats> &ProfStats,
  1085. StringMap<FuncSampleStats> &HotFunc,
  1086. uint64_t HotThreshold) const;
  1087. void computeHotFuncOverlap();
  1088. /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
  1089. /// Difference for two sample units in a matched function according to the
  1090. /// given match status.
  1091. void updateOverlapStatsForFunction(uint64_t BaseSample, uint64_t TestSample,
  1092. uint64_t HotBlockCount,
  1093. SampleOverlapStats &FuncOverlap,
  1094. double &Difference, MatchStatus Status);
  1095. /// This function updates statistics in FuncOverlap, HotBlockOverlap, and
  1096. /// Difference for unmatched callees that only present in one profile in a
  1097. /// matched caller function.
  1098. void updateForUnmatchedCallee(const sampleprof::FunctionSamples &Func,
  1099. SampleOverlapStats &FuncOverlap,
  1100. double &Difference, MatchStatus Status);
  1101. /// This function updates sample overlap statistics of an overlap function in
  1102. /// base and test profile. It also calculates a function-internal similarity
  1103. /// FIS as follows:
  1104. /// For offsets i that have samples in at least one profile in this
  1105. /// function A, given BS(i) returned by computeBlockSimilarity(), compute
  1106. /// FIS(A) = (2.0 - sum_i(1.0 - BS(i))) / 2, ranging in [0.0f to 1.0f] with
  1107. /// 0.0 meaning no overlap.
  1108. double computeSampleFunctionInternalOverlap(
  1109. const sampleprof::FunctionSamples &BaseFunc,
  1110. const sampleprof::FunctionSamples &TestFunc,
  1111. SampleOverlapStats &FuncOverlap);
  1112. /// Function-level similarity (FS) is a weighted value over function internal
  1113. /// similarity (FIS). This function computes a function's FS from its FIS by
  1114. /// applying the weight.
  1115. double weightForFuncSimilarity(double FuncSimilarity, uint64_t BaseFuncSample,
  1116. uint64_t TestFuncSample) const;
  1117. /// The function-level similarity FS(A) for a function A is computed as
  1118. /// follows:
  1119. /// Compute a function-internal similarity FIS(A) by
  1120. /// computeSampleFunctionInternalOverlap(). Then, with the weight of
  1121. /// function A in base profile WB(A), and the weight of function A in test
  1122. /// profile WT(A), compute FS(A) = FIS(A) * (1.0 - fabs(WB(A) - WT(A)))
  1123. /// ranging in [0.0f to 1.0f] with 0.0 meaning no overlap.
  1124. double
  1125. computeSampleFunctionOverlap(const sampleprof::FunctionSamples *BaseFunc,
  1126. const sampleprof::FunctionSamples *TestFunc,
  1127. SampleOverlapStats *FuncOverlap,
  1128. uint64_t BaseFuncSample,
  1129. uint64_t TestFuncSample);
  1130. /// Profile-level similarity (PS) is a weighted aggregate over function-level
  1131. /// similarities (FS). This method weights the FS value by the function
  1132. /// weights in the base and test profiles for the aggregation.
  1133. double weightByImportance(double FuncSimilarity, uint64_t BaseFuncSample,
  1134. uint64_t TestFuncSample) const;
  1135. };
  1136. } // end anonymous namespace
  1137. bool SampleOverlapAggregator::detectZeroSampleProfile(
  1138. raw_fd_ostream &OS) const {
  1139. bool HaveZeroSample = false;
  1140. if (ProfOverlap.BaseSample == 0) {
  1141. OS << "Sum of sample counts for profile " << BaseFilename << " is 0.\n";
  1142. HaveZeroSample = true;
  1143. }
  1144. if (ProfOverlap.TestSample == 0) {
  1145. OS << "Sum of sample counts for profile " << TestFilename << " is 0.\n";
  1146. HaveZeroSample = true;
  1147. }
  1148. return HaveZeroSample;
  1149. }
  1150. double SampleOverlapAggregator::computeBlockSimilarity(
  1151. uint64_t BaseSample, uint64_t TestSample,
  1152. const SampleOverlapStats &FuncOverlap) const {
  1153. double BaseFrac = 0.0;
  1154. double TestFrac = 0.0;
  1155. if (FuncOverlap.BaseSample > 0)
  1156. BaseFrac = static_cast<double>(BaseSample) / FuncOverlap.BaseSample;
  1157. if (FuncOverlap.TestSample > 0)
  1158. TestFrac = static_cast<double>(TestSample) / FuncOverlap.TestSample;
  1159. return 1.0 - std::fabs(BaseFrac - TestFrac);
  1160. }
  1161. void SampleOverlapAggregator::updateHotBlockOverlap(uint64_t BaseSample,
  1162. uint64_t TestSample,
  1163. uint64_t HotBlockCount) {
  1164. bool IsBaseHot = (BaseSample >= BaseHotThreshold);
  1165. bool IsTestHot = (TestSample >= TestHotThreshold);
  1166. if (!IsBaseHot && !IsTestHot)
  1167. return;
  1168. HotBlockOverlap.UnionCount += HotBlockCount;
  1169. if (IsBaseHot)
  1170. HotBlockOverlap.BaseCount += HotBlockCount;
  1171. if (IsTestHot)
  1172. HotBlockOverlap.TestCount += HotBlockCount;
  1173. if (IsBaseHot && IsTestHot)
  1174. HotBlockOverlap.OverlapCount += HotBlockCount;
  1175. }
  1176. void SampleOverlapAggregator::getHotFunctions(
  1177. const StringMap<FuncSampleStats> &ProfStats,
  1178. StringMap<FuncSampleStats> &HotFunc, uint64_t HotThreshold) const {
  1179. for (const auto &F : ProfStats) {
  1180. if (isFunctionHot(F.second, HotThreshold))
  1181. HotFunc.try_emplace(F.first(), F.second);
  1182. }
  1183. }
  1184. void SampleOverlapAggregator::computeHotFuncOverlap() {
  1185. StringMap<FuncSampleStats> BaseHotFunc;
  1186. getHotFunctions(BaseStats, BaseHotFunc, BaseHotThreshold);
  1187. HotFuncOverlap.BaseCount = BaseHotFunc.size();
  1188. StringMap<FuncSampleStats> TestHotFunc;
  1189. getHotFunctions(TestStats, TestHotFunc, TestHotThreshold);
  1190. HotFuncOverlap.TestCount = TestHotFunc.size();
  1191. HotFuncOverlap.UnionCount = HotFuncOverlap.TestCount;
  1192. for (const auto &F : BaseHotFunc) {
  1193. if (TestHotFunc.count(F.first()))
  1194. ++HotFuncOverlap.OverlapCount;
  1195. else
  1196. ++HotFuncOverlap.UnionCount;
  1197. }
  1198. }
  1199. void SampleOverlapAggregator::updateOverlapStatsForFunction(
  1200. uint64_t BaseSample, uint64_t TestSample, uint64_t HotBlockCount,
  1201. SampleOverlapStats &FuncOverlap, double &Difference, MatchStatus Status) {
  1202. assert(Status != MS_None &&
  1203. "Match status should be updated before updating overlap statistics");
  1204. if (Status == MS_FirstUnique) {
  1205. TestSample = 0;
  1206. FuncOverlap.BaseUniqueSample += BaseSample;
  1207. } else if (Status == MS_SecondUnique) {
  1208. BaseSample = 0;
  1209. FuncOverlap.TestUniqueSample += TestSample;
  1210. } else {
  1211. ++FuncOverlap.OverlapCount;
  1212. }
  1213. FuncOverlap.UnionSample += std::max(BaseSample, TestSample);
  1214. FuncOverlap.OverlapSample += std::min(BaseSample, TestSample);
  1215. Difference +=
  1216. 1.0 - computeBlockSimilarity(BaseSample, TestSample, FuncOverlap);
  1217. updateHotBlockOverlap(BaseSample, TestSample, HotBlockCount);
  1218. }
  1219. void SampleOverlapAggregator::updateForUnmatchedCallee(
  1220. const sampleprof::FunctionSamples &Func, SampleOverlapStats &FuncOverlap,
  1221. double &Difference, MatchStatus Status) {
  1222. assert((Status == MS_FirstUnique || Status == MS_SecondUnique) &&
  1223. "Status must be either of the two unmatched cases");
  1224. FuncSampleStats FuncStats;
  1225. if (Status == MS_FirstUnique) {
  1226. getFuncSampleStats(Func, FuncStats, BaseHotThreshold);
  1227. updateOverlapStatsForFunction(FuncStats.SampleSum, 0,
  1228. FuncStats.HotBlockCount, FuncOverlap,
  1229. Difference, Status);
  1230. } else {
  1231. getFuncSampleStats(Func, FuncStats, TestHotThreshold);
  1232. updateOverlapStatsForFunction(0, FuncStats.SampleSum,
  1233. FuncStats.HotBlockCount, FuncOverlap,
  1234. Difference, Status);
  1235. }
  1236. }
  1237. double SampleOverlapAggregator::computeSampleFunctionInternalOverlap(
  1238. const sampleprof::FunctionSamples &BaseFunc,
  1239. const sampleprof::FunctionSamples &TestFunc,
  1240. SampleOverlapStats &FuncOverlap) {
  1241. using namespace sampleprof;
  1242. double Difference = 0;
  1243. // Accumulate Difference for regular line/block samples in the function.
  1244. // We match them through sort-merge join algorithm because
  1245. // FunctionSamples::getBodySamples() returns a map of sample counters ordered
  1246. // by their offsets.
  1247. MatchStep<BodySampleMap::const_iterator> BlockIterStep(
  1248. BaseFunc.getBodySamples().cbegin(), BaseFunc.getBodySamples().cend(),
  1249. TestFunc.getBodySamples().cbegin(), TestFunc.getBodySamples().cend());
  1250. BlockIterStep.updateOneStep();
  1251. while (!BlockIterStep.areBothFinished()) {
  1252. uint64_t BaseSample =
  1253. BlockIterStep.isFirstFinished()
  1254. ? 0
  1255. : BlockIterStep.getFirstIter()->second.getSamples();
  1256. uint64_t TestSample =
  1257. BlockIterStep.isSecondFinished()
  1258. ? 0
  1259. : BlockIterStep.getSecondIter()->second.getSamples();
  1260. updateOverlapStatsForFunction(BaseSample, TestSample, 1, FuncOverlap,
  1261. Difference, BlockIterStep.getMatchStatus());
  1262. BlockIterStep.updateOneStep();
  1263. }
  1264. // Accumulate Difference for callsite lines in the function. We match
  1265. // them through sort-merge algorithm because
  1266. // FunctionSamples::getCallsiteSamples() returns a map of callsite records
  1267. // ordered by their offsets.
  1268. MatchStep<CallsiteSampleMap::const_iterator> CallsiteIterStep(
  1269. BaseFunc.getCallsiteSamples().cbegin(),
  1270. BaseFunc.getCallsiteSamples().cend(),
  1271. TestFunc.getCallsiteSamples().cbegin(),
  1272. TestFunc.getCallsiteSamples().cend());
  1273. CallsiteIterStep.updateOneStep();
  1274. while (!CallsiteIterStep.areBothFinished()) {
  1275. MatchStatus CallsiteStepStatus = CallsiteIterStep.getMatchStatus();
  1276. assert(CallsiteStepStatus != MS_None &&
  1277. "Match status should be updated before entering loop body");
  1278. if (CallsiteStepStatus != MS_Match) {
  1279. auto Callsite = (CallsiteStepStatus == MS_FirstUnique)
  1280. ? CallsiteIterStep.getFirstIter()
  1281. : CallsiteIterStep.getSecondIter();
  1282. for (const auto &F : Callsite->second)
  1283. updateForUnmatchedCallee(F.second, FuncOverlap, Difference,
  1284. CallsiteStepStatus);
  1285. } else {
  1286. // There may be multiple inlinees at the same offset, so we need to try
  1287. // matching all of them. This match is implemented through sort-merge
  1288. // algorithm because callsite records at the same offset are ordered by
  1289. // function names.
  1290. MatchStep<FunctionSamplesMap::const_iterator> CalleeIterStep(
  1291. CallsiteIterStep.getFirstIter()->second.cbegin(),
  1292. CallsiteIterStep.getFirstIter()->second.cend(),
  1293. CallsiteIterStep.getSecondIter()->second.cbegin(),
  1294. CallsiteIterStep.getSecondIter()->second.cend());
  1295. CalleeIterStep.updateOneStep();
  1296. while (!CalleeIterStep.areBothFinished()) {
  1297. MatchStatus CalleeStepStatus = CalleeIterStep.getMatchStatus();
  1298. if (CalleeStepStatus != MS_Match) {
  1299. auto Callee = (CalleeStepStatus == MS_FirstUnique)
  1300. ? CalleeIterStep.getFirstIter()
  1301. : CalleeIterStep.getSecondIter();
  1302. updateForUnmatchedCallee(Callee->second, FuncOverlap, Difference,
  1303. CalleeStepStatus);
  1304. } else {
  1305. // An inlined function can contain other inlinees inside, so compute
  1306. // the Difference recursively.
  1307. Difference += 2.0 - 2 * computeSampleFunctionInternalOverlap(
  1308. CalleeIterStep.getFirstIter()->second,
  1309. CalleeIterStep.getSecondIter()->second,
  1310. FuncOverlap);
  1311. }
  1312. CalleeIterStep.updateOneStep();
  1313. }
  1314. }
  1315. CallsiteIterStep.updateOneStep();
  1316. }
  1317. // Difference reflects the total differences of line/block samples in this
  1318. // function and ranges in [0.0f to 2.0f]. Take (2.0 - Difference) / 2 to
  1319. // reflect the similarity between function profiles in [0.0f to 1.0f].
  1320. return (2.0 - Difference) / 2;
  1321. }
  1322. double SampleOverlapAggregator::weightForFuncSimilarity(
  1323. double FuncInternalSimilarity, uint64_t BaseFuncSample,
  1324. uint64_t TestFuncSample) const {
  1325. // Compute the weight as the distance between the function weights in two
  1326. // profiles.
  1327. double BaseFrac = 0.0;
  1328. double TestFrac = 0.0;
  1329. assert(ProfOverlap.BaseSample > 0 &&
  1330. "Total samples in base profile should be greater than 0");
  1331. BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample;
  1332. assert(ProfOverlap.TestSample > 0 &&
  1333. "Total samples in test profile should be greater than 0");
  1334. TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample;
  1335. double WeightDistance = std::fabs(BaseFrac - TestFrac);
  1336. // Take WeightDistance into the similarity.
  1337. return FuncInternalSimilarity * (1 - WeightDistance);
  1338. }
  1339. double
  1340. SampleOverlapAggregator::weightByImportance(double FuncSimilarity,
  1341. uint64_t BaseFuncSample,
  1342. uint64_t TestFuncSample) const {
  1343. double BaseFrac = 0.0;
  1344. double TestFrac = 0.0;
  1345. assert(ProfOverlap.BaseSample > 0 &&
  1346. "Total samples in base profile should be greater than 0");
  1347. BaseFrac = static_cast<double>(BaseFuncSample) / ProfOverlap.BaseSample / 2.0;
  1348. assert(ProfOverlap.TestSample > 0 &&
  1349. "Total samples in test profile should be greater than 0");
  1350. TestFrac = static_cast<double>(TestFuncSample) / ProfOverlap.TestSample / 2.0;
  1351. return FuncSimilarity * (BaseFrac + TestFrac);
  1352. }
  1353. double SampleOverlapAggregator::computeSampleFunctionOverlap(
  1354. const sampleprof::FunctionSamples *BaseFunc,
  1355. const sampleprof::FunctionSamples *TestFunc,
  1356. SampleOverlapStats *FuncOverlap, uint64_t BaseFuncSample,
  1357. uint64_t TestFuncSample) {
  1358. // Default function internal similarity before weighted, meaning two functions
  1359. // has no overlap.
  1360. const double DefaultFuncInternalSimilarity = 0;
  1361. double FuncSimilarity;
  1362. double FuncInternalSimilarity;
  1363. // If BaseFunc or TestFunc is nullptr, it means the functions do not overlap.
  1364. // In this case, we use DefaultFuncInternalSimilarity as the function internal
  1365. // similarity.
  1366. if (!BaseFunc || !TestFunc) {
  1367. FuncInternalSimilarity = DefaultFuncInternalSimilarity;
  1368. } else {
  1369. assert(FuncOverlap != nullptr &&
  1370. "FuncOverlap should be provided in this case");
  1371. FuncInternalSimilarity = computeSampleFunctionInternalOverlap(
  1372. *BaseFunc, *TestFunc, *FuncOverlap);
  1373. // Now, FuncInternalSimilarity may be a little less than 0 due to
  1374. // imprecision of floating point accumulations. Make it zero if the
  1375. // difference is below Epsilon.
  1376. FuncInternalSimilarity = (std::fabs(FuncInternalSimilarity - 0) < Epsilon)
  1377. ? 0
  1378. : FuncInternalSimilarity;
  1379. }
  1380. FuncSimilarity = weightForFuncSimilarity(FuncInternalSimilarity,
  1381. BaseFuncSample, TestFuncSample);
  1382. return FuncSimilarity;
  1383. }
  1384. void SampleOverlapAggregator::computeSampleProfileOverlap(raw_fd_ostream &OS) {
  1385. using namespace sampleprof;
  1386. StringMap<const FunctionSamples *> BaseFuncProf;
  1387. const auto &BaseProfiles = BaseReader->getProfiles();
  1388. for (const auto &BaseFunc : BaseProfiles) {
  1389. BaseFuncProf.try_emplace(BaseFunc.second.getName(), &(BaseFunc.second));
  1390. }
  1391. ProfOverlap.UnionCount = BaseFuncProf.size();
  1392. const auto &TestProfiles = TestReader->getProfiles();
  1393. for (const auto &TestFunc : TestProfiles) {
  1394. SampleOverlapStats FuncOverlap;
  1395. FuncOverlap.TestName = TestFunc.second.getName();
  1396. assert(TestStats.count(FuncOverlap.TestName) &&
  1397. "TestStats should have records for all functions in test profile "
  1398. "except inlinees");
  1399. FuncOverlap.TestSample = TestStats[FuncOverlap.TestName].SampleSum;
  1400. const auto Match = BaseFuncProf.find(FuncOverlap.TestName);
  1401. if (Match == BaseFuncProf.end()) {
  1402. const FuncSampleStats &FuncStats = TestStats[FuncOverlap.TestName];
  1403. ++ProfOverlap.TestUniqueCount;
  1404. ProfOverlap.TestUniqueSample += FuncStats.SampleSum;
  1405. FuncOverlap.TestUniqueSample = FuncStats.SampleSum;
  1406. updateHotBlockOverlap(0, FuncStats.SampleSum, FuncStats.HotBlockCount);
  1407. double FuncSimilarity = computeSampleFunctionOverlap(
  1408. nullptr, nullptr, nullptr, 0, FuncStats.SampleSum);
  1409. ProfOverlap.Similarity +=
  1410. weightByImportance(FuncSimilarity, 0, FuncStats.SampleSum);
  1411. ++ProfOverlap.UnionCount;
  1412. ProfOverlap.UnionSample += FuncStats.SampleSum;
  1413. } else {
  1414. ++ProfOverlap.OverlapCount;
  1415. // Two functions match with each other. Compute function-level overlap and
  1416. // aggregate them into profile-level overlap.
  1417. FuncOverlap.BaseName = Match->second->getName();
  1418. assert(BaseStats.count(FuncOverlap.BaseName) &&
  1419. "BaseStats should have records for all functions in base profile "
  1420. "except inlinees");
  1421. FuncOverlap.BaseSample = BaseStats[FuncOverlap.BaseName].SampleSum;
  1422. FuncOverlap.Similarity = computeSampleFunctionOverlap(
  1423. Match->second, &TestFunc.second, &FuncOverlap, FuncOverlap.BaseSample,
  1424. FuncOverlap.TestSample);
  1425. ProfOverlap.Similarity +=
  1426. weightByImportance(FuncOverlap.Similarity, FuncOverlap.BaseSample,
  1427. FuncOverlap.TestSample);
  1428. ProfOverlap.OverlapSample += FuncOverlap.OverlapSample;
  1429. ProfOverlap.UnionSample += FuncOverlap.UnionSample;
  1430. // Accumulate the percentage of base unique and test unique samples into
  1431. // ProfOverlap.
  1432. ProfOverlap.BaseUniqueSample += FuncOverlap.BaseUniqueSample;
  1433. ProfOverlap.TestUniqueSample += FuncOverlap.TestUniqueSample;
  1434. // Remove matched base functions for later reporting functions not found
  1435. // in test profile.
  1436. BaseFuncProf.erase(Match);
  1437. }
  1438. // Print function-level similarity information if specified by options.
  1439. assert(TestStats.count(FuncOverlap.TestName) &&
  1440. "TestStats should have records for all functions in test profile "
  1441. "except inlinees");
  1442. if (TestStats[FuncOverlap.TestName].MaxSample >= FuncFilter.ValueCutoff ||
  1443. (Match != BaseFuncProf.end() &&
  1444. FuncOverlap.Similarity < LowSimilarityThreshold) ||
  1445. (Match != BaseFuncProf.end() && !FuncFilter.NameFilter.empty() &&
  1446. FuncOverlap.BaseName.find(FuncFilter.NameFilter) !=
  1447. FuncOverlap.BaseName.npos)) {
  1448. assert(ProfOverlap.BaseSample > 0 &&
  1449. "Total samples in base profile should be greater than 0");
  1450. FuncOverlap.BaseWeight =
  1451. static_cast<double>(FuncOverlap.BaseSample) / ProfOverlap.BaseSample;
  1452. assert(ProfOverlap.TestSample > 0 &&
  1453. "Total samples in test profile should be greater than 0");
  1454. FuncOverlap.TestWeight =
  1455. static_cast<double>(FuncOverlap.TestSample) / ProfOverlap.TestSample;
  1456. FuncSimilarityDump.emplace(FuncOverlap.BaseWeight, FuncOverlap);
  1457. }
  1458. }
  1459. // Traverse through functions in base profile but not in test profile.
  1460. for (const auto &F : BaseFuncProf) {
  1461. assert(BaseStats.count(F.second->getName()) &&
  1462. "BaseStats should have records for all functions in base profile "
  1463. "except inlinees");
  1464. const FuncSampleStats &FuncStats = BaseStats[F.second->getName()];
  1465. ++ProfOverlap.BaseUniqueCount;
  1466. ProfOverlap.BaseUniqueSample += FuncStats.SampleSum;
  1467. updateHotBlockOverlap(FuncStats.SampleSum, 0, FuncStats.HotBlockCount);
  1468. double FuncSimilarity = computeSampleFunctionOverlap(
  1469. nullptr, nullptr, nullptr, FuncStats.SampleSum, 0);
  1470. ProfOverlap.Similarity +=
  1471. weightByImportance(FuncSimilarity, FuncStats.SampleSum, 0);
  1472. ProfOverlap.UnionSample += FuncStats.SampleSum;
  1473. }
  1474. // Now, ProfSimilarity may be a little greater than 1 due to imprecision
  1475. // of floating point accumulations. Make it 1.0 if the difference is below
  1476. // Epsilon.
  1477. ProfOverlap.Similarity = (std::fabs(ProfOverlap.Similarity - 1) < Epsilon)
  1478. ? 1
  1479. : ProfOverlap.Similarity;
  1480. computeHotFuncOverlap();
  1481. }
  1482. void SampleOverlapAggregator::initializeSampleProfileOverlap() {
  1483. const auto &BaseProf = BaseReader->getProfiles();
  1484. for (const auto &I : BaseProf) {
  1485. ++ProfOverlap.BaseCount;
  1486. FuncSampleStats FuncStats;
  1487. getFuncSampleStats(I.second, FuncStats, BaseHotThreshold);
  1488. ProfOverlap.BaseSample += FuncStats.SampleSum;
  1489. BaseStats.try_emplace(I.second.getName(), FuncStats);
  1490. }
  1491. const auto &TestProf = TestReader->getProfiles();
  1492. for (const auto &I : TestProf) {
  1493. ++ProfOverlap.TestCount;
  1494. FuncSampleStats FuncStats;
  1495. getFuncSampleStats(I.second, FuncStats, TestHotThreshold);
  1496. ProfOverlap.TestSample += FuncStats.SampleSum;
  1497. TestStats.try_emplace(I.second.getName(), FuncStats);
  1498. }
  1499. ProfOverlap.BaseName = StringRef(BaseFilename);
  1500. ProfOverlap.TestName = StringRef(TestFilename);
  1501. }
  1502. void SampleOverlapAggregator::dumpFuncSimilarity(raw_fd_ostream &OS) const {
  1503. using namespace sampleprof;
  1504. if (FuncSimilarityDump.empty())
  1505. return;
  1506. formatted_raw_ostream FOS(OS);
  1507. FOS << "Function-level details:\n";
  1508. FOS << "Base weight";
  1509. FOS.PadToColumn(TestWeightCol);
  1510. FOS << "Test weight";
  1511. FOS.PadToColumn(SimilarityCol);
  1512. FOS << "Similarity";
  1513. FOS.PadToColumn(OverlapCol);
  1514. FOS << "Overlap";
  1515. FOS.PadToColumn(BaseUniqueCol);
  1516. FOS << "Base unique";
  1517. FOS.PadToColumn(TestUniqueCol);
  1518. FOS << "Test unique";
  1519. FOS.PadToColumn(BaseSampleCol);
  1520. FOS << "Base samples";
  1521. FOS.PadToColumn(TestSampleCol);
  1522. FOS << "Test samples";
  1523. FOS.PadToColumn(FuncNameCol);
  1524. FOS << "Function name\n";
  1525. for (const auto &F : FuncSimilarityDump) {
  1526. double OverlapPercent =
  1527. F.second.UnionSample > 0
  1528. ? static_cast<double>(F.second.OverlapSample) / F.second.UnionSample
  1529. : 0;
  1530. double BaseUniquePercent =
  1531. F.second.BaseSample > 0
  1532. ? static_cast<double>(F.second.BaseUniqueSample) /
  1533. F.second.BaseSample
  1534. : 0;
  1535. double TestUniquePercent =
  1536. F.second.TestSample > 0
  1537. ? static_cast<double>(F.second.TestUniqueSample) /
  1538. F.second.TestSample
  1539. : 0;
  1540. FOS << format("%.2f%%", F.second.BaseWeight * 100);
  1541. FOS.PadToColumn(TestWeightCol);
  1542. FOS << format("%.2f%%", F.second.TestWeight * 100);
  1543. FOS.PadToColumn(SimilarityCol);
  1544. FOS << format("%.2f%%", F.second.Similarity * 100);
  1545. FOS.PadToColumn(OverlapCol);
  1546. FOS << format("%.2f%%", OverlapPercent * 100);
  1547. FOS.PadToColumn(BaseUniqueCol);
  1548. FOS << format("%.2f%%", BaseUniquePercent * 100);
  1549. FOS.PadToColumn(TestUniqueCol);
  1550. FOS << format("%.2f%%", TestUniquePercent * 100);
  1551. FOS.PadToColumn(BaseSampleCol);
  1552. FOS << F.second.BaseSample;
  1553. FOS.PadToColumn(TestSampleCol);
  1554. FOS << F.second.TestSample;
  1555. FOS.PadToColumn(FuncNameCol);
  1556. FOS << F.second.TestName << "\n";
  1557. }
  1558. }
  1559. void SampleOverlapAggregator::dumpProgramSummary(raw_fd_ostream &OS) const {
  1560. OS << "Profile overlap infomation for base_profile: " << ProfOverlap.BaseName
  1561. << " and test_profile: " << ProfOverlap.TestName << "\nProgram level:\n";
  1562. OS << " Whole program profile similarity: "
  1563. << format("%.3f%%", ProfOverlap.Similarity * 100) << "\n";
  1564. assert(ProfOverlap.UnionSample > 0 &&
  1565. "Total samples in two profile should be greater than 0");
  1566. double OverlapPercent =
  1567. static_cast<double>(ProfOverlap.OverlapSample) / ProfOverlap.UnionSample;
  1568. assert(ProfOverlap.BaseSample > 0 &&
  1569. "Total samples in base profile should be greater than 0");
  1570. double BaseUniquePercent = static_cast<double>(ProfOverlap.BaseUniqueSample) /
  1571. ProfOverlap.BaseSample;
  1572. assert(ProfOverlap.TestSample > 0 &&
  1573. "Total samples in test profile should be greater than 0");
  1574. double TestUniquePercent = static_cast<double>(ProfOverlap.TestUniqueSample) /
  1575. ProfOverlap.TestSample;
  1576. OS << " Whole program sample overlap: "
  1577. << format("%.3f%%", OverlapPercent * 100) << "\n";
  1578. OS << " percentage of samples unique in base profile: "
  1579. << format("%.3f%%", BaseUniquePercent * 100) << "\n";
  1580. OS << " percentage of samples unique in test profile: "
  1581. << format("%.3f%%", TestUniquePercent * 100) << "\n";
  1582. OS << " total samples in base profile: " << ProfOverlap.BaseSample << "\n"
  1583. << " total samples in test profile: " << ProfOverlap.TestSample << "\n";
  1584. assert(ProfOverlap.UnionCount > 0 &&
  1585. "There should be at least one function in two input profiles");
  1586. double FuncOverlapPercent =
  1587. static_cast<double>(ProfOverlap.OverlapCount) / ProfOverlap.UnionCount;
  1588. OS << " Function overlap: " << format("%.3f%%", FuncOverlapPercent * 100)
  1589. << "\n";
  1590. OS << " overlap functions: " << ProfOverlap.OverlapCount << "\n";
  1591. OS << " functions unique in base profile: " << ProfOverlap.BaseUniqueCount
  1592. << "\n";
  1593. OS << " functions unique in test profile: " << ProfOverlap.TestUniqueCount
  1594. << "\n";
  1595. }
  1596. void SampleOverlapAggregator::dumpHotFuncAndBlockOverlap(
  1597. raw_fd_ostream &OS) const {
  1598. assert(HotFuncOverlap.UnionCount > 0 &&
  1599. "There should be at least one hot function in two input profiles");
  1600. OS << " Hot-function overlap: "
  1601. << format("%.3f%%", static_cast<double>(HotFuncOverlap.OverlapCount) /
  1602. HotFuncOverlap.UnionCount * 100)
  1603. << "\n";
  1604. OS << " overlap hot functions: " << HotFuncOverlap.OverlapCount << "\n";
  1605. OS << " hot functions unique in base profile: "
  1606. << HotFuncOverlap.BaseCount - HotFuncOverlap.OverlapCount << "\n";
  1607. OS << " hot functions unique in test profile: "
  1608. << HotFuncOverlap.TestCount - HotFuncOverlap.OverlapCount << "\n";
  1609. assert(HotBlockOverlap.UnionCount > 0 &&
  1610. "There should be at least one hot block in two input profiles");
  1611. OS << " Hot-block overlap: "
  1612. << format("%.3f%%", static_cast<double>(HotBlockOverlap.OverlapCount) /
  1613. HotBlockOverlap.UnionCount * 100)
  1614. << "\n";
  1615. OS << " overlap hot blocks: " << HotBlockOverlap.OverlapCount << "\n";
  1616. OS << " hot blocks unique in base profile: "
  1617. << HotBlockOverlap.BaseCount - HotBlockOverlap.OverlapCount << "\n";
  1618. OS << " hot blocks unique in test profile: "
  1619. << HotBlockOverlap.TestCount - HotBlockOverlap.OverlapCount << "\n";
  1620. }
  1621. std::error_code SampleOverlapAggregator::loadProfiles() {
  1622. using namespace sampleprof;
  1623. LLVMContext Context;
  1624. auto BaseReaderOrErr = SampleProfileReader::create(BaseFilename, Context);
  1625. if (std::error_code EC = BaseReaderOrErr.getError())
  1626. exitWithErrorCode(EC, BaseFilename);
  1627. auto TestReaderOrErr = SampleProfileReader::create(TestFilename, Context);
  1628. if (std::error_code EC = TestReaderOrErr.getError())
  1629. exitWithErrorCode(EC, TestFilename);
  1630. BaseReader = std::move(BaseReaderOrErr.get());
  1631. TestReader = std::move(TestReaderOrErr.get());
  1632. if (std::error_code EC = BaseReader->read())
  1633. exitWithErrorCode(EC, BaseFilename);
  1634. if (std::error_code EC = TestReader->read())
  1635. exitWithErrorCode(EC, TestFilename);
  1636. if (BaseReader->profileIsProbeBased() != TestReader->profileIsProbeBased())
  1637. exitWithError(
  1638. "cannot compare probe-based profile with non-probe-based profile");
  1639. // Load BaseHotThreshold and TestHotThreshold as 99-percentile threshold in
  1640. // profile summary.
  1641. const uint64_t HotCutoff = 990000;
  1642. ProfileSummary &BasePS = BaseReader->getSummary();
  1643. for (const auto &SummaryEntry : BasePS.getDetailedSummary()) {
  1644. if (SummaryEntry.Cutoff == HotCutoff) {
  1645. BaseHotThreshold = SummaryEntry.MinCount;
  1646. break;
  1647. }
  1648. }
  1649. ProfileSummary &TestPS = TestReader->getSummary();
  1650. for (const auto &SummaryEntry : TestPS.getDetailedSummary()) {
  1651. if (SummaryEntry.Cutoff == HotCutoff) {
  1652. TestHotThreshold = SummaryEntry.MinCount;
  1653. break;
  1654. }
  1655. }
  1656. return std::error_code();
  1657. }
  1658. void overlapSampleProfile(const std::string &BaseFilename,
  1659. const std::string &TestFilename,
  1660. const OverlapFuncFilters &FuncFilter,
  1661. uint64_t SimilarityCutoff, raw_fd_ostream &OS) {
  1662. using namespace sampleprof;
  1663. // We use 0.000005 to initialize OverlapAggr.Epsilon because the final metrics
  1664. // report 2--3 places after decimal point in percentage numbers.
  1665. SampleOverlapAggregator OverlapAggr(
  1666. BaseFilename, TestFilename,
  1667. static_cast<double>(SimilarityCutoff) / 1000000, 0.000005, FuncFilter);
  1668. if (std::error_code EC = OverlapAggr.loadProfiles())
  1669. exitWithErrorCode(EC);
  1670. OverlapAggr.initializeSampleProfileOverlap();
  1671. if (OverlapAggr.detectZeroSampleProfile(OS))
  1672. return;
  1673. OverlapAggr.computeSampleProfileOverlap(OS);
  1674. OverlapAggr.dumpProgramSummary(OS);
  1675. OverlapAggr.dumpHotFuncAndBlockOverlap(OS);
  1676. OverlapAggr.dumpFuncSimilarity(OS);
  1677. }
  1678. static int overlap_main(int argc, const char *argv[]) {
  1679. cl::opt<std::string> BaseFilename(cl::Positional, cl::Required,
  1680. cl::desc("<base profile file>"));
  1681. cl::opt<std::string> TestFilename(cl::Positional, cl::Required,
  1682. cl::desc("<test profile file>"));
  1683. cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"),
  1684. cl::desc("Output file"));
  1685. cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output));
  1686. cl::opt<bool> IsCS("cs", cl::init(false),
  1687. cl::desc("For context sensitive counts"));
  1688. cl::opt<unsigned long long> ValueCutoff(
  1689. "value-cutoff", cl::init(-1),
  1690. cl::desc(
  1691. "Function level overlap information for every function in test "
  1692. "profile with max count value greater then the parameter value"));
  1693. cl::opt<std::string> FuncNameFilter(
  1694. "function",
  1695. cl::desc("Function level overlap information for matching functions"));
  1696. cl::opt<unsigned long long> SimilarityCutoff(
  1697. "similarity-cutoff", cl::init(0),
  1698. cl::desc(
  1699. "For sample profiles, list function names for overlapped functions "
  1700. "with similarities below the cutoff (percentage times 10000)."));
  1701. cl::opt<ProfileKinds> ProfileKind(
  1702. cl::desc("Profile kind:"), cl::init(instr),
  1703. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  1704. clEnumVal(sample, "Sample profile")));
  1705. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n");
  1706. std::error_code EC;
  1707. raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_Text);
  1708. if (EC)
  1709. exitWithErrorCode(EC, Output);
  1710. if (ProfileKind == instr)
  1711. overlapInstrProfile(BaseFilename, TestFilename,
  1712. OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS,
  1713. IsCS);
  1714. else
  1715. overlapSampleProfile(BaseFilename, TestFilename,
  1716. OverlapFuncFilters{ValueCutoff, FuncNameFilter},
  1717. SimilarityCutoff, OS);
  1718. return 0;
  1719. }
  1720. typedef struct ValueSitesStats {
  1721. ValueSitesStats()
  1722. : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0),
  1723. TotalNumValues(0) {}
  1724. uint64_t TotalNumValueSites;
  1725. uint64_t TotalNumValueSitesWithValueProfile;
  1726. uint64_t TotalNumValues;
  1727. std::vector<unsigned> ValueSitesHistogram;
  1728. } ValueSitesStats;
  1729. static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK,
  1730. ValueSitesStats &Stats, raw_fd_ostream &OS,
  1731. InstrProfSymtab *Symtab) {
  1732. uint32_t NS = Func.getNumValueSites(VK);
  1733. Stats.TotalNumValueSites += NS;
  1734. for (size_t I = 0; I < NS; ++I) {
  1735. uint32_t NV = Func.getNumValueDataForSite(VK, I);
  1736. std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I);
  1737. Stats.TotalNumValues += NV;
  1738. if (NV) {
  1739. Stats.TotalNumValueSitesWithValueProfile++;
  1740. if (NV > Stats.ValueSitesHistogram.size())
  1741. Stats.ValueSitesHistogram.resize(NV, 0);
  1742. Stats.ValueSitesHistogram[NV - 1]++;
  1743. }
  1744. uint64_t SiteSum = 0;
  1745. for (uint32_t V = 0; V < NV; V++)
  1746. SiteSum += VD[V].Count;
  1747. if (SiteSum == 0)
  1748. SiteSum = 1;
  1749. for (uint32_t V = 0; V < NV; V++) {
  1750. OS << "\t[ " << format("%2u", I) << ", ";
  1751. if (Symtab == nullptr)
  1752. OS << format("%4" PRIu64, VD[V].Value);
  1753. else
  1754. OS << Symtab->getFuncName(VD[V].Value);
  1755. OS << ", " << format("%10" PRId64, VD[V].Count) << " ] ("
  1756. << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n";
  1757. }
  1758. }
  1759. }
  1760. static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK,
  1761. ValueSitesStats &Stats) {
  1762. OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n";
  1763. OS << " Total number of sites with values: "
  1764. << Stats.TotalNumValueSitesWithValueProfile << "\n";
  1765. OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n";
  1766. OS << " Value sites histogram:\n\tNumTargets, SiteCount\n";
  1767. for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) {
  1768. if (Stats.ValueSitesHistogram[I] > 0)
  1769. OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n";
  1770. }
  1771. }
  1772. static int showInstrProfile(const std::string &Filename, bool ShowCounts,
  1773. uint32_t TopN, bool ShowIndirectCallTargets,
  1774. bool ShowMemOPSizes, bool ShowDetailedSummary,
  1775. std::vector<uint32_t> DetailedSummaryCutoffs,
  1776. bool ShowAllFunctions, bool ShowCS,
  1777. uint64_t ValueCutoff, bool OnlyListBelow,
  1778. const std::string &ShowFunction, bool TextFormat,
  1779. raw_fd_ostream &OS) {
  1780. auto ReaderOrErr = InstrProfReader::create(Filename);
  1781. std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs);
  1782. if (ShowDetailedSummary && Cutoffs.empty()) {
  1783. Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990};
  1784. }
  1785. InstrProfSummaryBuilder Builder(std::move(Cutoffs));
  1786. if (Error E = ReaderOrErr.takeError())
  1787. exitWithError(std::move(E), Filename);
  1788. auto Reader = std::move(ReaderOrErr.get());
  1789. bool IsIRInstr = Reader->isIRLevelProfile();
  1790. size_t ShownFunctions = 0;
  1791. size_t BelowCutoffFunctions = 0;
  1792. int NumVPKind = IPVK_Last - IPVK_First + 1;
  1793. std::vector<ValueSitesStats> VPStats(NumVPKind);
  1794. auto MinCmp = [](const std::pair<std::string, uint64_t> &v1,
  1795. const std::pair<std::string, uint64_t> &v2) {
  1796. return v1.second > v2.second;
  1797. };
  1798. std::priority_queue<std::pair<std::string, uint64_t>,
  1799. std::vector<std::pair<std::string, uint64_t>>,
  1800. decltype(MinCmp)>
  1801. HottestFuncs(MinCmp);
  1802. if (!TextFormat && OnlyListBelow) {
  1803. OS << "The list of functions with the maximum counter less than "
  1804. << ValueCutoff << ":\n";
  1805. }
  1806. // Add marker so that IR-level instrumentation round-trips properly.
  1807. if (TextFormat && IsIRInstr)
  1808. OS << ":ir\n";
  1809. for (const auto &Func : *Reader) {
  1810. if (Reader->isIRLevelProfile()) {
  1811. bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash);
  1812. if (FuncIsCS != ShowCS)
  1813. continue;
  1814. }
  1815. bool Show =
  1816. ShowAllFunctions || (!ShowFunction.empty() &&
  1817. Func.Name.find(ShowFunction) != Func.Name.npos);
  1818. bool doTextFormatDump = (Show && TextFormat);
  1819. if (doTextFormatDump) {
  1820. InstrProfSymtab &Symtab = Reader->getSymtab();
  1821. InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab,
  1822. OS);
  1823. continue;
  1824. }
  1825. assert(Func.Counts.size() > 0 && "function missing entry counter");
  1826. Builder.addRecord(Func);
  1827. uint64_t FuncMax = 0;
  1828. uint64_t FuncSum = 0;
  1829. for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) {
  1830. if (Func.Counts[I] == (uint64_t)-1)
  1831. continue;
  1832. FuncMax = std::max(FuncMax, Func.Counts[I]);
  1833. FuncSum += Func.Counts[I];
  1834. }
  1835. if (FuncMax < ValueCutoff) {
  1836. ++BelowCutoffFunctions;
  1837. if (OnlyListBelow) {
  1838. OS << " " << Func.Name << ": (Max = " << FuncMax
  1839. << " Sum = " << FuncSum << ")\n";
  1840. }
  1841. continue;
  1842. } else if (OnlyListBelow)
  1843. continue;
  1844. if (TopN) {
  1845. if (HottestFuncs.size() == TopN) {
  1846. if (HottestFuncs.top().second < FuncMax) {
  1847. HottestFuncs.pop();
  1848. HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
  1849. }
  1850. } else
  1851. HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax));
  1852. }
  1853. if (Show) {
  1854. if (!ShownFunctions)
  1855. OS << "Counters:\n";
  1856. ++ShownFunctions;
  1857. OS << " " << Func.Name << ":\n"
  1858. << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n"
  1859. << " Counters: " << Func.Counts.size() << "\n";
  1860. if (!IsIRInstr)
  1861. OS << " Function count: " << Func.Counts[0] << "\n";
  1862. if (ShowIndirectCallTargets)
  1863. OS << " Indirect Call Site Count: "
  1864. << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n";
  1865. uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize);
  1866. if (ShowMemOPSizes && NumMemOPCalls > 0)
  1867. OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls
  1868. << "\n";
  1869. if (ShowCounts) {
  1870. OS << " Block counts: [";
  1871. size_t Start = (IsIRInstr ? 0 : 1);
  1872. for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) {
  1873. OS << (I == Start ? "" : ", ") << Func.Counts[I];
  1874. }
  1875. OS << "]\n";
  1876. }
  1877. if (ShowIndirectCallTargets) {
  1878. OS << " Indirect Target Results:\n";
  1879. traverseAllValueSites(Func, IPVK_IndirectCallTarget,
  1880. VPStats[IPVK_IndirectCallTarget], OS,
  1881. &(Reader->getSymtab()));
  1882. }
  1883. if (ShowMemOPSizes && NumMemOPCalls > 0) {
  1884. OS << " Memory Intrinsic Size Results:\n";
  1885. traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS,
  1886. nullptr);
  1887. }
  1888. }
  1889. }
  1890. if (Reader->hasError())
  1891. exitWithError(Reader->getError(), Filename);
  1892. if (TextFormat)
  1893. return 0;
  1894. std::unique_ptr<ProfileSummary> PS(Builder.getSummary());
  1895. bool IsIR = Reader->isIRLevelProfile();
  1896. OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end");
  1897. if (IsIR)
  1898. OS << " entry_first = " << Reader->instrEntryBBEnabled();
  1899. OS << "\n";
  1900. if (ShowAllFunctions || !ShowFunction.empty())
  1901. OS << "Functions shown: " << ShownFunctions << "\n";
  1902. OS << "Total functions: " << PS->getNumFunctions() << "\n";
  1903. if (ValueCutoff > 0) {
  1904. OS << "Number of functions with maximum count (< " << ValueCutoff
  1905. << "): " << BelowCutoffFunctions << "\n";
  1906. OS << "Number of functions with maximum count (>= " << ValueCutoff
  1907. << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n";
  1908. }
  1909. OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n";
  1910. OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n";
  1911. if (TopN) {
  1912. std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs;
  1913. while (!HottestFuncs.empty()) {
  1914. SortedHottestFuncs.emplace_back(HottestFuncs.top());
  1915. HottestFuncs.pop();
  1916. }
  1917. OS << "Top " << TopN
  1918. << " functions with the largest internal block counts: \n";
  1919. for (auto &hotfunc : llvm::reverse(SortedHottestFuncs))
  1920. OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n";
  1921. }
  1922. if (ShownFunctions && ShowIndirectCallTargets) {
  1923. OS << "Statistics for indirect call sites profile:\n";
  1924. showValueSitesStats(OS, IPVK_IndirectCallTarget,
  1925. VPStats[IPVK_IndirectCallTarget]);
  1926. }
  1927. if (ShownFunctions && ShowMemOPSizes) {
  1928. OS << "Statistics for memory intrinsic calls sizes profile:\n";
  1929. showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]);
  1930. }
  1931. if (ShowDetailedSummary) {
  1932. OS << "Total number of blocks: " << PS->getNumCounts() << "\n";
  1933. OS << "Total count: " << PS->getTotalCount() << "\n";
  1934. PS->printDetailedSummary(OS);
  1935. }
  1936. return 0;
  1937. }
  1938. static void showSectionInfo(sampleprof::SampleProfileReader *Reader,
  1939. raw_fd_ostream &OS) {
  1940. if (!Reader->dumpSectionInfo(OS)) {
  1941. WithColor::warning() << "-show-sec-info-only is only supported for "
  1942. << "sample profile in extbinary format and is "
  1943. << "ignored for other formats.\n";
  1944. return;
  1945. }
  1946. }
  1947. namespace {
  1948. struct HotFuncInfo {
  1949. StringRef FuncName;
  1950. uint64_t TotalCount;
  1951. double TotalCountPercent;
  1952. uint64_t MaxCount;
  1953. uint64_t EntryCount;
  1954. HotFuncInfo()
  1955. : FuncName(), TotalCount(0), TotalCountPercent(0.0f), MaxCount(0),
  1956. EntryCount(0) {}
  1957. HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES)
  1958. : FuncName(FN), TotalCount(TS), TotalCountPercent(TSP), MaxCount(MS),
  1959. EntryCount(ES) {}
  1960. };
  1961. } // namespace
  1962. // Print out detailed information about hot functions in PrintValues vector.
  1963. // Users specify titles and offset of every columns through ColumnTitle and
  1964. // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same
  1965. // and at least 4. Besides, users can optionally give a HotFuncMetric string to
  1966. // print out or let it be an empty string.
  1967. static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle,
  1968. const std::vector<int> &ColumnOffset,
  1969. const std::vector<HotFuncInfo> &PrintValues,
  1970. uint64_t HotFuncCount, uint64_t TotalFuncCount,
  1971. uint64_t HotProfCount, uint64_t TotalProfCount,
  1972. const std::string &HotFuncMetric,
  1973. raw_fd_ostream &OS) {
  1974. assert(ColumnOffset.size() == ColumnTitle.size() &&
  1975. "ColumnOffset and ColumnTitle should have the same size");
  1976. assert(ColumnTitle.size() >= 4 &&
  1977. "ColumnTitle should have at least 4 elements");
  1978. assert(TotalFuncCount > 0 &&
  1979. "There should be at least one function in the profile");
  1980. double TotalProfPercent = 0;
  1981. if (TotalProfCount > 0)
  1982. TotalProfPercent = static_cast<double>(HotProfCount) / TotalProfCount * 100;
  1983. formatted_raw_ostream FOS(OS);
  1984. FOS << HotFuncCount << " out of " << TotalFuncCount
  1985. << " functions with profile ("
  1986. << format("%.2f%%",
  1987. (static_cast<double>(HotFuncCount) / TotalFuncCount * 100))
  1988. << ") are considered hot functions";
  1989. if (!HotFuncMetric.empty())
  1990. FOS << " (" << HotFuncMetric << ")";
  1991. FOS << ".\n";
  1992. FOS << HotProfCount << " out of " << TotalProfCount << " profile counts ("
  1993. << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n";
  1994. for (size_t I = 0; I < ColumnTitle.size(); ++I) {
  1995. FOS.PadToColumn(ColumnOffset[I]);
  1996. FOS << ColumnTitle[I];
  1997. }
  1998. FOS << "\n";
  1999. for (const HotFuncInfo &R : PrintValues) {
  2000. FOS.PadToColumn(ColumnOffset[0]);
  2001. FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")";
  2002. FOS.PadToColumn(ColumnOffset[1]);
  2003. FOS << R.MaxCount;
  2004. FOS.PadToColumn(ColumnOffset[2]);
  2005. FOS << R.EntryCount;
  2006. FOS.PadToColumn(ColumnOffset[3]);
  2007. FOS << R.FuncName << "\n";
  2008. }
  2009. }
  2010. static int
  2011. showHotFunctionList(const StringMap<sampleprof::FunctionSamples> &Profiles,
  2012. ProfileSummary &PS, raw_fd_ostream &OS) {
  2013. using namespace sampleprof;
  2014. const uint32_t HotFuncCutoff = 990000;
  2015. auto &SummaryVector = PS.getDetailedSummary();
  2016. uint64_t MinCountThreshold = 0;
  2017. for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) {
  2018. if (SummaryEntry.Cutoff == HotFuncCutoff) {
  2019. MinCountThreshold = SummaryEntry.MinCount;
  2020. break;
  2021. }
  2022. }
  2023. // Traverse all functions in the profile and keep only hot functions.
  2024. // The following loop also calculates the sum of total samples of all
  2025. // functions.
  2026. std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>,
  2027. std::greater<uint64_t>>
  2028. HotFunc;
  2029. uint64_t ProfileTotalSample = 0;
  2030. uint64_t HotFuncSample = 0;
  2031. uint64_t HotFuncCount = 0;
  2032. for (const auto &I : Profiles) {
  2033. FuncSampleStats FuncStats;
  2034. const FunctionSamples &FuncProf = I.second;
  2035. ProfileTotalSample += FuncProf.getTotalSamples();
  2036. getFuncSampleStats(FuncProf, FuncStats, MinCountThreshold);
  2037. if (isFunctionHot(FuncStats, MinCountThreshold)) {
  2038. HotFunc.emplace(FuncProf.getTotalSamples(),
  2039. std::make_pair(&(I.second), FuncStats.MaxSample));
  2040. HotFuncSample += FuncProf.getTotalSamples();
  2041. ++HotFuncCount;
  2042. }
  2043. }
  2044. std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample",
  2045. "Entry sample", "Function name"};
  2046. std::vector<int> ColumnOffset{0, 24, 42, 58};
  2047. std::string Metric =
  2048. std::string("max sample >= ") + std::to_string(MinCountThreshold);
  2049. std::vector<HotFuncInfo> PrintValues;
  2050. for (const auto &FuncPair : HotFunc) {
  2051. const FunctionSamples &Func = *FuncPair.second.first;
  2052. double TotalSamplePercent =
  2053. (ProfileTotalSample > 0)
  2054. ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample
  2055. : 0;
  2056. PrintValues.emplace_back(
  2057. HotFuncInfo(Func.getName(), Func.getTotalSamples(), TotalSamplePercent,
  2058. FuncPair.second.second, Func.getEntrySamples()));
  2059. }
  2060. dumpHotFunctionList(ColumnTitle, ColumnOffset, PrintValues, HotFuncCount,
  2061. Profiles.size(), HotFuncSample, ProfileTotalSample,
  2062. Metric, OS);
  2063. return 0;
  2064. }
  2065. static int showSampleProfile(const std::string &Filename, bool ShowCounts,
  2066. bool ShowAllFunctions, bool ShowDetailedSummary,
  2067. const std::string &ShowFunction,
  2068. bool ShowProfileSymbolList,
  2069. bool ShowSectionInfoOnly, bool ShowHotFuncList,
  2070. raw_fd_ostream &OS) {
  2071. using namespace sampleprof;
  2072. LLVMContext Context;
  2073. auto ReaderOrErr = SampleProfileReader::create(Filename, Context);
  2074. if (std::error_code EC = ReaderOrErr.getError())
  2075. exitWithErrorCode(EC, Filename);
  2076. auto Reader = std::move(ReaderOrErr.get());
  2077. if (ShowSectionInfoOnly) {
  2078. showSectionInfo(Reader.get(), OS);
  2079. return 0;
  2080. }
  2081. if (std::error_code EC = Reader->read())
  2082. exitWithErrorCode(EC, Filename);
  2083. if (ShowAllFunctions || ShowFunction.empty())
  2084. Reader->dump(OS);
  2085. else
  2086. Reader->dumpFunctionProfile(ShowFunction, OS);
  2087. if (ShowProfileSymbolList) {
  2088. std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList =
  2089. Reader->getProfileSymbolList();
  2090. ReaderList->dump(OS);
  2091. }
  2092. if (ShowDetailedSummary) {
  2093. auto &PS = Reader->getSummary();
  2094. PS.printSummary(OS);
  2095. PS.printDetailedSummary(OS);
  2096. }
  2097. if (ShowHotFuncList)
  2098. showHotFunctionList(Reader->getProfiles(), Reader->getSummary(), OS);
  2099. return 0;
  2100. }
  2101. static int show_main(int argc, const char *argv[]) {
  2102. cl::opt<std::string> Filename(cl::Positional, cl::Required,
  2103. cl::desc("<profdata-file>"));
  2104. cl::opt<bool> ShowCounts("counts", cl::init(false),
  2105. cl::desc("Show counter values for shown functions"));
  2106. cl::opt<bool> TextFormat(
  2107. "text", cl::init(false),
  2108. cl::desc("Show instr profile data in text dump format"));
  2109. cl::opt<bool> ShowIndirectCallTargets(
  2110. "ic-targets", cl::init(false),
  2111. cl::desc("Show indirect call site target values for shown functions"));
  2112. cl::opt<bool> ShowMemOPSizes(
  2113. "memop-sizes", cl::init(false),
  2114. cl::desc("Show the profiled sizes of the memory intrinsic calls "
  2115. "for shown functions"));
  2116. cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false),
  2117. cl::desc("Show detailed profile summary"));
  2118. cl::list<uint32_t> DetailedSummaryCutoffs(
  2119. cl::CommaSeparated, "detailed-summary-cutoffs",
  2120. cl::desc(
  2121. "Cutoff percentages (times 10000) for generating detailed summary"),
  2122. cl::value_desc("800000,901000,999999"));
  2123. cl::opt<bool> ShowHotFuncList(
  2124. "hot-func-list", cl::init(false),
  2125. cl::desc("Show profile summary of a list of hot functions"));
  2126. cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false),
  2127. cl::desc("Details for every function"));
  2128. cl::opt<bool> ShowCS("showcs", cl::init(false),
  2129. cl::desc("Show context sensitive counts"));
  2130. cl::opt<std::string> ShowFunction("function",
  2131. cl::desc("Details for matching functions"));
  2132. cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
  2133. cl::init("-"), cl::desc("Output file"));
  2134. cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
  2135. cl::aliasopt(OutputFilename));
  2136. cl::opt<ProfileKinds> ProfileKind(
  2137. cl::desc("Profile kind:"), cl::init(instr),
  2138. cl::values(clEnumVal(instr, "Instrumentation profile (default)"),
  2139. clEnumVal(sample, "Sample profile")));
  2140. cl::opt<uint32_t> TopNFunctions(
  2141. "topn", cl::init(0),
  2142. cl::desc("Show the list of functions with the largest internal counts"));
  2143. cl::opt<uint32_t> ValueCutoff(
  2144. "value-cutoff", cl::init(0),
  2145. cl::desc("Set the count value cutoff. Functions with the maximum count "
  2146. "less than this value will not be printed out. (Default is 0)"));
  2147. cl::opt<bool> OnlyListBelow(
  2148. "list-below-cutoff", cl::init(false),
  2149. cl::desc("Only output names of functions whose max count values are "
  2150. "below the cutoff value"));
  2151. cl::opt<bool> ShowProfileSymbolList(
  2152. "show-prof-sym-list", cl::init(false),
  2153. cl::desc("Show profile symbol list if it exists in the profile. "));
  2154. cl::opt<bool> ShowSectionInfoOnly(
  2155. "show-sec-info-only", cl::init(false),
  2156. cl::desc("Show the information of each section in the sample profile. "
  2157. "The flag is only usable when the sample profile is in "
  2158. "extbinary format"));
  2159. cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n");
  2160. if (OutputFilename.empty())
  2161. OutputFilename = "-";
  2162. if (Filename == OutputFilename) {
  2163. errs() << sys::path::filename(argv[0])
  2164. << ": Input file name cannot be the same as the output file name!\n";
  2165. return 1;
  2166. }
  2167. std::error_code EC;
  2168. raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_Text);
  2169. if (EC)
  2170. exitWithErrorCode(EC, OutputFilename);
  2171. if (ShowAllFunctions && !ShowFunction.empty())
  2172. WithColor::warning() << "-function argument ignored: showing all functions\n";
  2173. if (ProfileKind == instr)
  2174. return showInstrProfile(Filename, ShowCounts, TopNFunctions,
  2175. ShowIndirectCallTargets, ShowMemOPSizes,
  2176. ShowDetailedSummary, DetailedSummaryCutoffs,
  2177. ShowAllFunctions, ShowCS, ValueCutoff,
  2178. OnlyListBelow, ShowFunction, TextFormat, OS);
  2179. else
  2180. return showSampleProfile(Filename, ShowCounts, ShowAllFunctions,
  2181. ShowDetailedSummary, ShowFunction,
  2182. ShowProfileSymbolList, ShowSectionInfoOnly,
  2183. ShowHotFuncList, OS);
  2184. }
  2185. int main(int argc, const char *argv[]) {
  2186. InitLLVM X(argc, argv);
  2187. StringRef ProgName(sys::path::filename(argv[0]));
  2188. if (argc > 1) {
  2189. int (*func)(int, const char *[]) = nullptr;
  2190. if (strcmp(argv[1], "merge") == 0)
  2191. func = merge_main;
  2192. else if (strcmp(argv[1], "show") == 0)
  2193. func = show_main;
  2194. else if (strcmp(argv[1], "overlap") == 0)
  2195. func = overlap_main;
  2196. if (func) {
  2197. std::string Invocation(ProgName.str() + " " + argv[1]);
  2198. argv[1] = Invocation.c_str();
  2199. return func(argc - 1, argv + 1);
  2200. }
  2201. if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 ||
  2202. strcmp(argv[1], "--help") == 0) {
  2203. errs() << "OVERVIEW: LLVM profile data tools\n\n"
  2204. << "USAGE: " << ProgName << " <command> [args...]\n"
  2205. << "USAGE: " << ProgName << " <command> -help\n\n"
  2206. << "See each individual command --help for more details.\n"
  2207. << "Available commands: merge, show, overlap\n";
  2208. return 0;
  2209. }
  2210. }
  2211. if (argc < 2)
  2212. errs() << ProgName << ": No command specified!\n";
  2213. else
  2214. errs() << ProgName << ": Unknown command!\n";
  2215. errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n";
  2216. return 1;
  2217. }