llvm-profdata.cpp 118 KB

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