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