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