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); 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.find(',') == StringRef::npos) 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 const auto Match = BaseFuncProf.find(FuncOverlap.TestName); 1637 if (Match == BaseFuncProf.end()) { 1638 const FuncSampleStats &FuncStats = TestStats[FuncOverlap.TestName]; 1639 ++ProfOverlap.TestUniqueCount; 1640 ProfOverlap.TestUniqueSample += FuncStats.SampleSum; 1641 FuncOverlap.TestUniqueSample = FuncStats.SampleSum; 1642 1643 updateHotBlockOverlap(0, FuncStats.SampleSum, FuncStats.HotBlockCount); 1644 1645 double FuncSimilarity = computeSampleFunctionOverlap( 1646 nullptr, nullptr, nullptr, 0, FuncStats.SampleSum); 1647 ProfOverlap.Similarity += 1648 weightByImportance(FuncSimilarity, 0, FuncStats.SampleSum); 1649 1650 ++ProfOverlap.UnionCount; 1651 ProfOverlap.UnionSample += FuncStats.SampleSum; 1652 } else { 1653 ++ProfOverlap.OverlapCount; 1654 1655 // Two functions match with each other. Compute function-level overlap and 1656 // aggregate them into profile-level overlap. 1657 FuncOverlap.BaseName = Match->second->getContext(); 1658 assert(BaseStats.count(FuncOverlap.BaseName) && 1659 "BaseStats should have records for all functions in base profile " 1660 "except inlinees"); 1661 FuncOverlap.BaseSample = BaseStats[FuncOverlap.BaseName].SampleSum; 1662 1663 FuncOverlap.Similarity = computeSampleFunctionOverlap( 1664 Match->second, &TestFunc.second, &FuncOverlap, FuncOverlap.BaseSample, 1665 FuncOverlap.TestSample); 1666 ProfOverlap.Similarity += 1667 weightByImportance(FuncOverlap.Similarity, FuncOverlap.BaseSample, 1668 FuncOverlap.TestSample); 1669 ProfOverlap.OverlapSample += FuncOverlap.OverlapSample; 1670 ProfOverlap.UnionSample += FuncOverlap.UnionSample; 1671 1672 // Accumulate the percentage of base unique and test unique samples into 1673 // ProfOverlap. 1674 ProfOverlap.BaseUniqueSample += FuncOverlap.BaseUniqueSample; 1675 ProfOverlap.TestUniqueSample += FuncOverlap.TestUniqueSample; 1676 1677 // Remove matched base functions for later reporting functions not found 1678 // in test profile. 1679 BaseFuncProf.erase(Match); 1680 } 1681 1682 // Print function-level similarity information if specified by options. 1683 assert(TestStats.count(FuncOverlap.TestName) && 1684 "TestStats should have records for all functions in test profile " 1685 "except inlinees"); 1686 if (TestStats[FuncOverlap.TestName].MaxSample >= FuncFilter.ValueCutoff || 1687 (Match != BaseFuncProf.end() && 1688 FuncOverlap.Similarity < LowSimilarityThreshold) || 1689 (Match != BaseFuncProf.end() && !FuncFilter.NameFilter.empty() && 1690 FuncOverlap.BaseName.toString().find(FuncFilter.NameFilter) != 1691 std::string::npos)) { 1692 assert(ProfOverlap.BaseSample > 0 && 1693 "Total samples in base profile should be greater than 0"); 1694 FuncOverlap.BaseWeight = 1695 static_cast<double>(FuncOverlap.BaseSample) / ProfOverlap.BaseSample; 1696 assert(ProfOverlap.TestSample > 0 && 1697 "Total samples in test profile should be greater than 0"); 1698 FuncOverlap.TestWeight = 1699 static_cast<double>(FuncOverlap.TestSample) / ProfOverlap.TestSample; 1700 FuncSimilarityDump.emplace(FuncOverlap.BaseWeight, FuncOverlap); 1701 } 1702 } 1703 1704 // Traverse through functions in base profile but not in test profile. 1705 for (const auto &F : BaseFuncProf) { 1706 assert(BaseStats.count(F.second->getContext()) && 1707 "BaseStats should have records for all functions in base profile " 1708 "except inlinees"); 1709 const FuncSampleStats &FuncStats = BaseStats[F.second->getContext()]; 1710 ++ProfOverlap.BaseUniqueCount; 1711 ProfOverlap.BaseUniqueSample += FuncStats.SampleSum; 1712 1713 updateHotBlockOverlap(FuncStats.SampleSum, 0, FuncStats.HotBlockCount); 1714 1715 double FuncSimilarity = computeSampleFunctionOverlap( 1716 nullptr, nullptr, nullptr, FuncStats.SampleSum, 0); 1717 ProfOverlap.Similarity += 1718 weightByImportance(FuncSimilarity, FuncStats.SampleSum, 0); 1719 1720 ProfOverlap.UnionSample += FuncStats.SampleSum; 1721 } 1722 1723 // Now, ProfSimilarity may be a little greater than 1 due to imprecision 1724 // of floating point accumulations. Make it 1.0 if the difference is below 1725 // Epsilon. 1726 ProfOverlap.Similarity = (std::fabs(ProfOverlap.Similarity - 1) < Epsilon) 1727 ? 1 1728 : ProfOverlap.Similarity; 1729 1730 computeHotFuncOverlap(); 1731 } 1732 1733 void SampleOverlapAggregator::initializeSampleProfileOverlap() { 1734 const auto &BaseProf = BaseReader->getProfiles(); 1735 for (const auto &I : BaseProf) { 1736 ++ProfOverlap.BaseCount; 1737 FuncSampleStats FuncStats; 1738 getFuncSampleStats(I.second, FuncStats, BaseHotThreshold); 1739 ProfOverlap.BaseSample += FuncStats.SampleSum; 1740 BaseStats.emplace(I.second.getContext(), FuncStats); 1741 } 1742 1743 const auto &TestProf = TestReader->getProfiles(); 1744 for (const auto &I : TestProf) { 1745 ++ProfOverlap.TestCount; 1746 FuncSampleStats FuncStats; 1747 getFuncSampleStats(I.second, FuncStats, TestHotThreshold); 1748 ProfOverlap.TestSample += FuncStats.SampleSum; 1749 TestStats.emplace(I.second.getContext(), FuncStats); 1750 } 1751 1752 ProfOverlap.BaseName = StringRef(BaseFilename); 1753 ProfOverlap.TestName = StringRef(TestFilename); 1754 } 1755 1756 void SampleOverlapAggregator::dumpFuncSimilarity(raw_fd_ostream &OS) const { 1757 using namespace sampleprof; 1758 1759 if (FuncSimilarityDump.empty()) 1760 return; 1761 1762 formatted_raw_ostream FOS(OS); 1763 FOS << "Function-level details:\n"; 1764 FOS << "Base weight"; 1765 FOS.PadToColumn(TestWeightCol); 1766 FOS << "Test weight"; 1767 FOS.PadToColumn(SimilarityCol); 1768 FOS << "Similarity"; 1769 FOS.PadToColumn(OverlapCol); 1770 FOS << "Overlap"; 1771 FOS.PadToColumn(BaseUniqueCol); 1772 FOS << "Base unique"; 1773 FOS.PadToColumn(TestUniqueCol); 1774 FOS << "Test unique"; 1775 FOS.PadToColumn(BaseSampleCol); 1776 FOS << "Base samples"; 1777 FOS.PadToColumn(TestSampleCol); 1778 FOS << "Test samples"; 1779 FOS.PadToColumn(FuncNameCol); 1780 FOS << "Function name\n"; 1781 for (const auto &F : FuncSimilarityDump) { 1782 double OverlapPercent = 1783 F.second.UnionSample > 0 1784 ? static_cast<double>(F.second.OverlapSample) / F.second.UnionSample 1785 : 0; 1786 double BaseUniquePercent = 1787 F.second.BaseSample > 0 1788 ? static_cast<double>(F.second.BaseUniqueSample) / 1789 F.second.BaseSample 1790 : 0; 1791 double TestUniquePercent = 1792 F.second.TestSample > 0 1793 ? static_cast<double>(F.second.TestUniqueSample) / 1794 F.second.TestSample 1795 : 0; 1796 1797 FOS << format("%.2f%%", F.second.BaseWeight * 100); 1798 FOS.PadToColumn(TestWeightCol); 1799 FOS << format("%.2f%%", F.second.TestWeight * 100); 1800 FOS.PadToColumn(SimilarityCol); 1801 FOS << format("%.2f%%", F.second.Similarity * 100); 1802 FOS.PadToColumn(OverlapCol); 1803 FOS << format("%.2f%%", OverlapPercent * 100); 1804 FOS.PadToColumn(BaseUniqueCol); 1805 FOS << format("%.2f%%", BaseUniquePercent * 100); 1806 FOS.PadToColumn(TestUniqueCol); 1807 FOS << format("%.2f%%", TestUniquePercent * 100); 1808 FOS.PadToColumn(BaseSampleCol); 1809 FOS << F.second.BaseSample; 1810 FOS.PadToColumn(TestSampleCol); 1811 FOS << F.second.TestSample; 1812 FOS.PadToColumn(FuncNameCol); 1813 FOS << F.second.TestName.toString() << "\n"; 1814 } 1815 } 1816 1817 void SampleOverlapAggregator::dumpProgramSummary(raw_fd_ostream &OS) const { 1818 OS << "Profile overlap infomation for base_profile: " 1819 << ProfOverlap.BaseName.toString() 1820 << " and test_profile: " << ProfOverlap.TestName.toString() 1821 << "\nProgram level:\n"; 1822 1823 OS << " Whole program profile similarity: " 1824 << format("%.3f%%", ProfOverlap.Similarity * 100) << "\n"; 1825 1826 assert(ProfOverlap.UnionSample > 0 && 1827 "Total samples in two profile should be greater than 0"); 1828 double OverlapPercent = 1829 static_cast<double>(ProfOverlap.OverlapSample) / ProfOverlap.UnionSample; 1830 assert(ProfOverlap.BaseSample > 0 && 1831 "Total samples in base profile should be greater than 0"); 1832 double BaseUniquePercent = static_cast<double>(ProfOverlap.BaseUniqueSample) / 1833 ProfOverlap.BaseSample; 1834 assert(ProfOverlap.TestSample > 0 && 1835 "Total samples in test profile should be greater than 0"); 1836 double TestUniquePercent = static_cast<double>(ProfOverlap.TestUniqueSample) / 1837 ProfOverlap.TestSample; 1838 1839 OS << " Whole program sample overlap: " 1840 << format("%.3f%%", OverlapPercent * 100) << "\n"; 1841 OS << " percentage of samples unique in base profile: " 1842 << format("%.3f%%", BaseUniquePercent * 100) << "\n"; 1843 OS << " percentage of samples unique in test profile: " 1844 << format("%.3f%%", TestUniquePercent * 100) << "\n"; 1845 OS << " total samples in base profile: " << ProfOverlap.BaseSample << "\n" 1846 << " total samples in test profile: " << ProfOverlap.TestSample << "\n"; 1847 1848 assert(ProfOverlap.UnionCount > 0 && 1849 "There should be at least one function in two input profiles"); 1850 double FuncOverlapPercent = 1851 static_cast<double>(ProfOverlap.OverlapCount) / ProfOverlap.UnionCount; 1852 OS << " Function overlap: " << format("%.3f%%", FuncOverlapPercent * 100) 1853 << "\n"; 1854 OS << " overlap functions: " << ProfOverlap.OverlapCount << "\n"; 1855 OS << " functions unique in base profile: " << ProfOverlap.BaseUniqueCount 1856 << "\n"; 1857 OS << " functions unique in test profile: " << ProfOverlap.TestUniqueCount 1858 << "\n"; 1859 } 1860 1861 void SampleOverlapAggregator::dumpHotFuncAndBlockOverlap( 1862 raw_fd_ostream &OS) const { 1863 assert(HotFuncOverlap.UnionCount > 0 && 1864 "There should be at least one hot function in two input profiles"); 1865 OS << " Hot-function overlap: " 1866 << format("%.3f%%", static_cast<double>(HotFuncOverlap.OverlapCount) / 1867 HotFuncOverlap.UnionCount * 100) 1868 << "\n"; 1869 OS << " overlap hot functions: " << HotFuncOverlap.OverlapCount << "\n"; 1870 OS << " hot functions unique in base profile: " 1871 << HotFuncOverlap.BaseCount - HotFuncOverlap.OverlapCount << "\n"; 1872 OS << " hot functions unique in test profile: " 1873 << HotFuncOverlap.TestCount - HotFuncOverlap.OverlapCount << "\n"; 1874 1875 assert(HotBlockOverlap.UnionCount > 0 && 1876 "There should be at least one hot block in two input profiles"); 1877 OS << " Hot-block overlap: " 1878 << format("%.3f%%", static_cast<double>(HotBlockOverlap.OverlapCount) / 1879 HotBlockOverlap.UnionCount * 100) 1880 << "\n"; 1881 OS << " overlap hot blocks: " << HotBlockOverlap.OverlapCount << "\n"; 1882 OS << " hot blocks unique in base profile: " 1883 << HotBlockOverlap.BaseCount - HotBlockOverlap.OverlapCount << "\n"; 1884 OS << " hot blocks unique in test profile: " 1885 << HotBlockOverlap.TestCount - HotBlockOverlap.OverlapCount << "\n"; 1886 } 1887 1888 std::error_code SampleOverlapAggregator::loadProfiles() { 1889 using namespace sampleprof; 1890 1891 LLVMContext Context; 1892 auto BaseReaderOrErr = SampleProfileReader::create(BaseFilename, Context, 1893 FSDiscriminatorPassOption); 1894 if (std::error_code EC = BaseReaderOrErr.getError()) 1895 exitWithErrorCode(EC, BaseFilename); 1896 1897 auto TestReaderOrErr = SampleProfileReader::create(TestFilename, Context, 1898 FSDiscriminatorPassOption); 1899 if (std::error_code EC = TestReaderOrErr.getError()) 1900 exitWithErrorCode(EC, TestFilename); 1901 1902 BaseReader = std::move(BaseReaderOrErr.get()); 1903 TestReader = std::move(TestReaderOrErr.get()); 1904 1905 if (std::error_code EC = BaseReader->read()) 1906 exitWithErrorCode(EC, BaseFilename); 1907 if (std::error_code EC = TestReader->read()) 1908 exitWithErrorCode(EC, TestFilename); 1909 if (BaseReader->profileIsProbeBased() != TestReader->profileIsProbeBased()) 1910 exitWithError( 1911 "cannot compare probe-based profile with non-probe-based profile"); 1912 if (BaseReader->profileIsCS() != TestReader->profileIsCS()) 1913 exitWithError("cannot compare CS profile with non-CS profile"); 1914 1915 // Load BaseHotThreshold and TestHotThreshold as 99-percentile threshold in 1916 // profile summary. 1917 const uint64_t HotCutoff = 990000; 1918 ProfileSummary &BasePS = BaseReader->getSummary(); 1919 for (const auto &SummaryEntry : BasePS.getDetailedSummary()) { 1920 if (SummaryEntry.Cutoff == HotCutoff) { 1921 BaseHotThreshold = SummaryEntry.MinCount; 1922 break; 1923 } 1924 } 1925 1926 ProfileSummary &TestPS = TestReader->getSummary(); 1927 for (const auto &SummaryEntry : TestPS.getDetailedSummary()) { 1928 if (SummaryEntry.Cutoff == HotCutoff) { 1929 TestHotThreshold = SummaryEntry.MinCount; 1930 break; 1931 } 1932 } 1933 return std::error_code(); 1934 } 1935 1936 void overlapSampleProfile(const std::string &BaseFilename, 1937 const std::string &TestFilename, 1938 const OverlapFuncFilters &FuncFilter, 1939 uint64_t SimilarityCutoff, raw_fd_ostream &OS) { 1940 using namespace sampleprof; 1941 1942 // We use 0.000005 to initialize OverlapAggr.Epsilon because the final metrics 1943 // report 2--3 places after decimal point in percentage numbers. 1944 SampleOverlapAggregator OverlapAggr( 1945 BaseFilename, TestFilename, 1946 static_cast<double>(SimilarityCutoff) / 1000000, 0.000005, FuncFilter); 1947 if (std::error_code EC = OverlapAggr.loadProfiles()) 1948 exitWithErrorCode(EC); 1949 1950 OverlapAggr.initializeSampleProfileOverlap(); 1951 if (OverlapAggr.detectZeroSampleProfile(OS)) 1952 return; 1953 1954 OverlapAggr.computeSampleProfileOverlap(OS); 1955 1956 OverlapAggr.dumpProgramSummary(OS); 1957 OverlapAggr.dumpHotFuncAndBlockOverlap(OS); 1958 OverlapAggr.dumpFuncSimilarity(OS); 1959 } 1960 1961 static int overlap_main(int argc, const char *argv[]) { 1962 cl::opt<std::string> BaseFilename(cl::Positional, cl::Required, 1963 cl::desc("<base profile file>")); 1964 cl::opt<std::string> TestFilename(cl::Positional, cl::Required, 1965 cl::desc("<test profile file>")); 1966 cl::opt<std::string> Output("output", cl::value_desc("output"), cl::init("-"), 1967 cl::desc("Output file")); 1968 cl::alias OutputA("o", cl::desc("Alias for --output"), cl::aliasopt(Output)); 1969 cl::opt<bool> IsCS( 1970 "cs", cl::init(false), 1971 cl::desc("For context sensitive PGO counts. Does not work with CSSPGO.")); 1972 cl::opt<unsigned long long> ValueCutoff( 1973 "value-cutoff", cl::init(-1), 1974 cl::desc( 1975 "Function level overlap information for every function (with calling " 1976 "context for csspgo) in test " 1977 "profile with max count value greater then the parameter value")); 1978 cl::opt<std::string> FuncNameFilter( 1979 "function", 1980 cl::desc("Function level overlap information for matching functions. For " 1981 "CSSPGO this takes a a function name with calling context")); 1982 cl::opt<unsigned long long> SimilarityCutoff( 1983 "similarity-cutoff", cl::init(0), 1984 cl::desc("For sample profiles, list function names (with calling context " 1985 "for csspgo) for overlapped functions " 1986 "with similarities below the cutoff (percentage times 10000).")); 1987 cl::opt<ProfileKinds> ProfileKind( 1988 cl::desc("Profile kind:"), cl::init(instr), 1989 cl::values(clEnumVal(instr, "Instrumentation profile (default)"), 1990 clEnumVal(sample, "Sample profile"))); 1991 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data overlap tool\n"); 1992 1993 std::error_code EC; 1994 raw_fd_ostream OS(Output.data(), EC, sys::fs::OF_TextWithCRLF); 1995 if (EC) 1996 exitWithErrorCode(EC, Output); 1997 1998 if (ProfileKind == instr) 1999 overlapInstrProfile(BaseFilename, TestFilename, 2000 OverlapFuncFilters{ValueCutoff, FuncNameFilter}, OS, 2001 IsCS); 2002 else 2003 overlapSampleProfile(BaseFilename, TestFilename, 2004 OverlapFuncFilters{ValueCutoff, FuncNameFilter}, 2005 SimilarityCutoff, OS); 2006 2007 return 0; 2008 } 2009 2010 namespace { 2011 struct ValueSitesStats { 2012 ValueSitesStats() 2013 : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0), 2014 TotalNumValues(0) {} 2015 uint64_t TotalNumValueSites; 2016 uint64_t TotalNumValueSitesWithValueProfile; 2017 uint64_t TotalNumValues; 2018 std::vector<unsigned> ValueSitesHistogram; 2019 }; 2020 } // namespace 2021 2022 static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK, 2023 ValueSitesStats &Stats, raw_fd_ostream &OS, 2024 InstrProfSymtab *Symtab) { 2025 uint32_t NS = Func.getNumValueSites(VK); 2026 Stats.TotalNumValueSites += NS; 2027 for (size_t I = 0; I < NS; ++I) { 2028 uint32_t NV = Func.getNumValueDataForSite(VK, I); 2029 std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I); 2030 Stats.TotalNumValues += NV; 2031 if (NV) { 2032 Stats.TotalNumValueSitesWithValueProfile++; 2033 if (NV > Stats.ValueSitesHistogram.size()) 2034 Stats.ValueSitesHistogram.resize(NV, 0); 2035 Stats.ValueSitesHistogram[NV - 1]++; 2036 } 2037 2038 uint64_t SiteSum = 0; 2039 for (uint32_t V = 0; V < NV; V++) 2040 SiteSum += VD[V].Count; 2041 if (SiteSum == 0) 2042 SiteSum = 1; 2043 2044 for (uint32_t V = 0; V < NV; V++) { 2045 OS << "\t[ " << format("%2u", I) << ", "; 2046 if (Symtab == nullptr) 2047 OS << format("%4" PRIu64, VD[V].Value); 2048 else 2049 OS << Symtab->getFuncName(VD[V].Value); 2050 OS << ", " << format("%10" PRId64, VD[V].Count) << " ] (" 2051 << format("%.2f%%", (VD[V].Count * 100.0 / SiteSum)) << ")\n"; 2052 } 2053 } 2054 } 2055 2056 static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK, 2057 ValueSitesStats &Stats) { 2058 OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n"; 2059 OS << " Total number of sites with values: " 2060 << Stats.TotalNumValueSitesWithValueProfile << "\n"; 2061 OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n"; 2062 2063 OS << " Value sites histogram:\n\tNumTargets, SiteCount\n"; 2064 for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) { 2065 if (Stats.ValueSitesHistogram[I] > 0) 2066 OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n"; 2067 } 2068 } 2069 2070 static int showInstrProfile(const std::string &Filename, bool ShowCounts, 2071 uint32_t TopN, bool ShowIndirectCallTargets, 2072 bool ShowMemOPSizes, bool ShowDetailedSummary, 2073 std::vector<uint32_t> DetailedSummaryCutoffs, 2074 bool ShowAllFunctions, bool ShowCS, 2075 uint64_t ValueCutoff, bool OnlyListBelow, 2076 const std::string &ShowFunction, bool TextFormat, 2077 bool ShowBinaryIds, raw_fd_ostream &OS) { 2078 auto ReaderOrErr = InstrProfReader::create(Filename); 2079 std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs); 2080 if (ShowDetailedSummary && Cutoffs.empty()) { 2081 Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990}; 2082 } 2083 InstrProfSummaryBuilder Builder(std::move(Cutoffs)); 2084 if (Error E = ReaderOrErr.takeError()) 2085 exitWithError(std::move(E), Filename); 2086 2087 auto Reader = std::move(ReaderOrErr.get()); 2088 bool IsIRInstr = Reader->isIRLevelProfile(); 2089 size_t ShownFunctions = 0; 2090 size_t BelowCutoffFunctions = 0; 2091 int NumVPKind = IPVK_Last - IPVK_First + 1; 2092 std::vector<ValueSitesStats> VPStats(NumVPKind); 2093 2094 auto MinCmp = [](const std::pair<std::string, uint64_t> &v1, 2095 const std::pair<std::string, uint64_t> &v2) { 2096 return v1.second > v2.second; 2097 }; 2098 2099 std::priority_queue<std::pair<std::string, uint64_t>, 2100 std::vector<std::pair<std::string, uint64_t>>, 2101 decltype(MinCmp)> 2102 HottestFuncs(MinCmp); 2103 2104 if (!TextFormat && OnlyListBelow) { 2105 OS << "The list of functions with the maximum counter less than " 2106 << ValueCutoff << ":\n"; 2107 } 2108 2109 // Add marker so that IR-level instrumentation round-trips properly. 2110 if (TextFormat && IsIRInstr) 2111 OS << ":ir\n"; 2112 2113 for (const auto &Func : *Reader) { 2114 if (Reader->isIRLevelProfile()) { 2115 bool FuncIsCS = NamedInstrProfRecord::hasCSFlagInHash(Func.Hash); 2116 if (FuncIsCS != ShowCS) 2117 continue; 2118 } 2119 bool Show = 2120 ShowAllFunctions || (!ShowFunction.empty() && 2121 Func.Name.find(ShowFunction) != Func.Name.npos); 2122 2123 bool doTextFormatDump = (Show && TextFormat); 2124 2125 if (doTextFormatDump) { 2126 InstrProfSymtab &Symtab = Reader->getSymtab(); 2127 InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab, 2128 OS); 2129 continue; 2130 } 2131 2132 assert(Func.Counts.size() > 0 && "function missing entry counter"); 2133 Builder.addRecord(Func); 2134 2135 uint64_t FuncMax = 0; 2136 uint64_t FuncSum = 0; 2137 for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) { 2138 if (Func.Counts[I] == (uint64_t)-1) 2139 continue; 2140 FuncMax = std::max(FuncMax, Func.Counts[I]); 2141 FuncSum += Func.Counts[I]; 2142 } 2143 2144 if (FuncMax < ValueCutoff) { 2145 ++BelowCutoffFunctions; 2146 if (OnlyListBelow) { 2147 OS << " " << Func.Name << ": (Max = " << FuncMax 2148 << " Sum = " << FuncSum << ")\n"; 2149 } 2150 continue; 2151 } else if (OnlyListBelow) 2152 continue; 2153 2154 if (TopN) { 2155 if (HottestFuncs.size() == TopN) { 2156 if (HottestFuncs.top().second < FuncMax) { 2157 HottestFuncs.pop(); 2158 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax)); 2159 } 2160 } else 2161 HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax)); 2162 } 2163 2164 if (Show) { 2165 if (!ShownFunctions) 2166 OS << "Counters:\n"; 2167 2168 ++ShownFunctions; 2169 2170 OS << " " << Func.Name << ":\n" 2171 << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n" 2172 << " Counters: " << Func.Counts.size() << "\n"; 2173 if (!IsIRInstr) 2174 OS << " Function count: " << Func.Counts[0] << "\n"; 2175 2176 if (ShowIndirectCallTargets) 2177 OS << " Indirect Call Site Count: " 2178 << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n"; 2179 2180 uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize); 2181 if (ShowMemOPSizes && NumMemOPCalls > 0) 2182 OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls 2183 << "\n"; 2184 2185 if (ShowCounts) { 2186 OS << " Block counts: ["; 2187 size_t Start = (IsIRInstr ? 0 : 1); 2188 for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) { 2189 OS << (I == Start ? "" : ", ") << Func.Counts[I]; 2190 } 2191 OS << "]\n"; 2192 } 2193 2194 if (ShowIndirectCallTargets) { 2195 OS << " Indirect Target Results:\n"; 2196 traverseAllValueSites(Func, IPVK_IndirectCallTarget, 2197 VPStats[IPVK_IndirectCallTarget], OS, 2198 &(Reader->getSymtab())); 2199 } 2200 2201 if (ShowMemOPSizes && NumMemOPCalls > 0) { 2202 OS << " Memory Intrinsic Size Results:\n"; 2203 traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS, 2204 nullptr); 2205 } 2206 } 2207 } 2208 if (Reader->hasError()) 2209 exitWithError(Reader->getError(), Filename); 2210 2211 if (TextFormat) 2212 return 0; 2213 std::unique_ptr<ProfileSummary> PS(Builder.getSummary()); 2214 bool IsIR = Reader->isIRLevelProfile(); 2215 OS << "Instrumentation level: " << (IsIR ? "IR" : "Front-end"); 2216 if (IsIR) 2217 OS << " entry_first = " << Reader->instrEntryBBEnabled(); 2218 OS << "\n"; 2219 if (ShowAllFunctions || !ShowFunction.empty()) 2220 OS << "Functions shown: " << ShownFunctions << "\n"; 2221 OS << "Total functions: " << PS->getNumFunctions() << "\n"; 2222 if (ValueCutoff > 0) { 2223 OS << "Number of functions with maximum count (< " << ValueCutoff 2224 << "): " << BelowCutoffFunctions << "\n"; 2225 OS << "Number of functions with maximum count (>= " << ValueCutoff 2226 << "): " << PS->getNumFunctions() - BelowCutoffFunctions << "\n"; 2227 } 2228 OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n"; 2229 OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n"; 2230 2231 if (TopN) { 2232 std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs; 2233 while (!HottestFuncs.empty()) { 2234 SortedHottestFuncs.emplace_back(HottestFuncs.top()); 2235 HottestFuncs.pop(); 2236 } 2237 OS << "Top " << TopN 2238 << " functions with the largest internal block counts: \n"; 2239 for (auto &hotfunc : llvm::reverse(SortedHottestFuncs)) 2240 OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n"; 2241 } 2242 2243 if (ShownFunctions && ShowIndirectCallTargets) { 2244 OS << "Statistics for indirect call sites profile:\n"; 2245 showValueSitesStats(OS, IPVK_IndirectCallTarget, 2246 VPStats[IPVK_IndirectCallTarget]); 2247 } 2248 2249 if (ShownFunctions && ShowMemOPSizes) { 2250 OS << "Statistics for memory intrinsic calls sizes profile:\n"; 2251 showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]); 2252 } 2253 2254 if (ShowDetailedSummary) { 2255 OS << "Total number of blocks: " << PS->getNumCounts() << "\n"; 2256 OS << "Total count: " << PS->getTotalCount() << "\n"; 2257 PS->printDetailedSummary(OS); 2258 } 2259 2260 if (ShowBinaryIds) 2261 if (Error E = Reader->printBinaryIds(OS)) 2262 exitWithError(std::move(E), Filename); 2263 2264 return 0; 2265 } 2266 2267 static void showSectionInfo(sampleprof::SampleProfileReader *Reader, 2268 raw_fd_ostream &OS) { 2269 if (!Reader->dumpSectionInfo(OS)) { 2270 WithColor::warning() << "-show-sec-info-only is only supported for " 2271 << "sample profile in extbinary format and is " 2272 << "ignored for other formats.\n"; 2273 return; 2274 } 2275 } 2276 2277 namespace { 2278 struct HotFuncInfo { 2279 std::string FuncName; 2280 uint64_t TotalCount; 2281 double TotalCountPercent; 2282 uint64_t MaxCount; 2283 uint64_t EntryCount; 2284 2285 HotFuncInfo() 2286 : FuncName(), TotalCount(0), TotalCountPercent(0.0f), MaxCount(0), 2287 EntryCount(0) {} 2288 2289 HotFuncInfo(StringRef FN, uint64_t TS, double TSP, uint64_t MS, uint64_t ES) 2290 : FuncName(FN.begin(), FN.end()), TotalCount(TS), TotalCountPercent(TSP), 2291 MaxCount(MS), EntryCount(ES) {} 2292 }; 2293 } // namespace 2294 2295 // Print out detailed information about hot functions in PrintValues vector. 2296 // Users specify titles and offset of every columns through ColumnTitle and 2297 // ColumnOffset. The size of ColumnTitle and ColumnOffset need to be the same 2298 // and at least 4. Besides, users can optionally give a HotFuncMetric string to 2299 // print out or let it be an empty string. 2300 static void dumpHotFunctionList(const std::vector<std::string> &ColumnTitle, 2301 const std::vector<int> &ColumnOffset, 2302 const std::vector<HotFuncInfo> &PrintValues, 2303 uint64_t HotFuncCount, uint64_t TotalFuncCount, 2304 uint64_t HotProfCount, uint64_t TotalProfCount, 2305 const std::string &HotFuncMetric, 2306 raw_fd_ostream &OS) { 2307 assert(ColumnOffset.size() == ColumnTitle.size() && 2308 "ColumnOffset and ColumnTitle should have the same size"); 2309 assert(ColumnTitle.size() >= 4 && 2310 "ColumnTitle should have at least 4 elements"); 2311 assert(TotalFuncCount > 0 && 2312 "There should be at least one function in the profile"); 2313 double TotalProfPercent = 0; 2314 if (TotalProfCount > 0) 2315 TotalProfPercent = static_cast<double>(HotProfCount) / TotalProfCount * 100; 2316 2317 formatted_raw_ostream FOS(OS); 2318 FOS << HotFuncCount << " out of " << TotalFuncCount 2319 << " functions with profile (" 2320 << format("%.2f%%", 2321 (static_cast<double>(HotFuncCount) / TotalFuncCount * 100)) 2322 << ") are considered hot functions"; 2323 if (!HotFuncMetric.empty()) 2324 FOS << " (" << HotFuncMetric << ")"; 2325 FOS << ".\n"; 2326 FOS << HotProfCount << " out of " << TotalProfCount << " profile counts (" 2327 << format("%.2f%%", TotalProfPercent) << ") are from hot functions.\n"; 2328 2329 for (size_t I = 0; I < ColumnTitle.size(); ++I) { 2330 FOS.PadToColumn(ColumnOffset[I]); 2331 FOS << ColumnTitle[I]; 2332 } 2333 FOS << "\n"; 2334 2335 for (const HotFuncInfo &R : PrintValues) { 2336 FOS.PadToColumn(ColumnOffset[0]); 2337 FOS << R.TotalCount << " (" << format("%.2f%%", R.TotalCountPercent) << ")"; 2338 FOS.PadToColumn(ColumnOffset[1]); 2339 FOS << R.MaxCount; 2340 FOS.PadToColumn(ColumnOffset[2]); 2341 FOS << R.EntryCount; 2342 FOS.PadToColumn(ColumnOffset[3]); 2343 FOS << R.FuncName << "\n"; 2344 } 2345 } 2346 2347 static int showHotFunctionList(const sampleprof::SampleProfileMap &Profiles, 2348 ProfileSummary &PS, raw_fd_ostream &OS) { 2349 using namespace sampleprof; 2350 2351 const uint32_t HotFuncCutoff = 990000; 2352 auto &SummaryVector = PS.getDetailedSummary(); 2353 uint64_t MinCountThreshold = 0; 2354 for (const ProfileSummaryEntry &SummaryEntry : SummaryVector) { 2355 if (SummaryEntry.Cutoff == HotFuncCutoff) { 2356 MinCountThreshold = SummaryEntry.MinCount; 2357 break; 2358 } 2359 } 2360 2361 // Traverse all functions in the profile and keep only hot functions. 2362 // The following loop also calculates the sum of total samples of all 2363 // functions. 2364 std::multimap<uint64_t, std::pair<const FunctionSamples *, const uint64_t>, 2365 std::greater<uint64_t>> 2366 HotFunc; 2367 uint64_t ProfileTotalSample = 0; 2368 uint64_t HotFuncSample = 0; 2369 uint64_t HotFuncCount = 0; 2370 2371 for (const auto &I : Profiles) { 2372 FuncSampleStats FuncStats; 2373 const FunctionSamples &FuncProf = I.second; 2374 ProfileTotalSample += FuncProf.getTotalSamples(); 2375 getFuncSampleStats(FuncProf, FuncStats, MinCountThreshold); 2376 2377 if (isFunctionHot(FuncStats, MinCountThreshold)) { 2378 HotFunc.emplace(FuncProf.getTotalSamples(), 2379 std::make_pair(&(I.second), FuncStats.MaxSample)); 2380 HotFuncSample += FuncProf.getTotalSamples(); 2381 ++HotFuncCount; 2382 } 2383 } 2384 2385 std::vector<std::string> ColumnTitle{"Total sample (%)", "Max sample", 2386 "Entry sample", "Function name"}; 2387 std::vector<int> ColumnOffset{0, 24, 42, 58}; 2388 std::string Metric = 2389 std::string("max sample >= ") + std::to_string(MinCountThreshold); 2390 std::vector<HotFuncInfo> PrintValues; 2391 for (const auto &FuncPair : HotFunc) { 2392 const FunctionSamples &Func = *FuncPair.second.first; 2393 double TotalSamplePercent = 2394 (ProfileTotalSample > 0) 2395 ? (Func.getTotalSamples() * 100.0) / ProfileTotalSample 2396 : 0; 2397 PrintValues.emplace_back(HotFuncInfo( 2398 Func.getContext().toString(), Func.getTotalSamples(), 2399 TotalSamplePercent, FuncPair.second.second, Func.getEntrySamples())); 2400 } 2401 dumpHotFunctionList(ColumnTitle, ColumnOffset, PrintValues, HotFuncCount, 2402 Profiles.size(), HotFuncSample, ProfileTotalSample, 2403 Metric, OS); 2404 2405 return 0; 2406 } 2407 2408 static int showSampleProfile(const std::string &Filename, bool ShowCounts, 2409 bool ShowAllFunctions, bool ShowDetailedSummary, 2410 const std::string &ShowFunction, 2411 bool ShowProfileSymbolList, 2412 bool ShowSectionInfoOnly, bool ShowHotFuncList, 2413 raw_fd_ostream &OS) { 2414 using namespace sampleprof; 2415 LLVMContext Context; 2416 auto ReaderOrErr = 2417 SampleProfileReader::create(Filename, Context, FSDiscriminatorPassOption); 2418 if (std::error_code EC = ReaderOrErr.getError()) 2419 exitWithErrorCode(EC, Filename); 2420 2421 auto Reader = std::move(ReaderOrErr.get()); 2422 if (ShowSectionInfoOnly) { 2423 showSectionInfo(Reader.get(), OS); 2424 return 0; 2425 } 2426 2427 if (std::error_code EC = Reader->read()) 2428 exitWithErrorCode(EC, Filename); 2429 2430 if (ShowAllFunctions || ShowFunction.empty()) 2431 Reader->dump(OS); 2432 else 2433 // TODO: parse context string to support filtering by contexts. 2434 Reader->dumpFunctionProfile(StringRef(ShowFunction), OS); 2435 2436 if (ShowProfileSymbolList) { 2437 std::unique_ptr<sampleprof::ProfileSymbolList> ReaderList = 2438 Reader->getProfileSymbolList(); 2439 ReaderList->dump(OS); 2440 } 2441 2442 if (ShowDetailedSummary) { 2443 auto &PS = Reader->getSummary(); 2444 PS.printSummary(OS); 2445 PS.printDetailedSummary(OS); 2446 } 2447 2448 if (ShowHotFuncList) 2449 showHotFunctionList(Reader->getProfiles(), Reader->getSummary(), OS); 2450 2451 return 0; 2452 } 2453 2454 static int show_main(int argc, const char *argv[]) { 2455 cl::opt<std::string> Filename(cl::Positional, cl::Required, 2456 cl::desc("<profdata-file>")); 2457 2458 cl::opt<bool> ShowCounts("counts", cl::init(false), 2459 cl::desc("Show counter values for shown functions")); 2460 cl::opt<bool> TextFormat( 2461 "text", cl::init(false), 2462 cl::desc("Show instr profile data in text dump format")); 2463 cl::opt<bool> ShowIndirectCallTargets( 2464 "ic-targets", cl::init(false), 2465 cl::desc("Show indirect call site target values for shown functions")); 2466 cl::opt<bool> ShowMemOPSizes( 2467 "memop-sizes", cl::init(false), 2468 cl::desc("Show the profiled sizes of the memory intrinsic calls " 2469 "for shown functions")); 2470 cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false), 2471 cl::desc("Show detailed profile summary")); 2472 cl::list<uint32_t> DetailedSummaryCutoffs( 2473 cl::CommaSeparated, "detailed-summary-cutoffs", 2474 cl::desc( 2475 "Cutoff percentages (times 10000) for generating detailed summary"), 2476 cl::value_desc("800000,901000,999999")); 2477 cl::opt<bool> ShowHotFuncList( 2478 "hot-func-list", cl::init(false), 2479 cl::desc("Show profile summary of a list of hot functions")); 2480 cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false), 2481 cl::desc("Details for every function")); 2482 cl::opt<bool> ShowCS("showcs", cl::init(false), 2483 cl::desc("Show context sensitive counts")); 2484 cl::opt<std::string> ShowFunction("function", 2485 cl::desc("Details for matching functions")); 2486 2487 cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), 2488 cl::init("-"), cl::desc("Output file")); 2489 cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), 2490 cl::aliasopt(OutputFilename)); 2491 cl::opt<ProfileKinds> ProfileKind( 2492 cl::desc("Profile kind:"), cl::init(instr), 2493 cl::values(clEnumVal(instr, "Instrumentation profile (default)"), 2494 clEnumVal(sample, "Sample profile"))); 2495 cl::opt<uint32_t> TopNFunctions( 2496 "topn", cl::init(0), 2497 cl::desc("Show the list of functions with the largest internal counts")); 2498 cl::opt<uint32_t> ValueCutoff( 2499 "value-cutoff", cl::init(0), 2500 cl::desc("Set the count value cutoff. Functions with the maximum count " 2501 "less than this value will not be printed out. (Default is 0)")); 2502 cl::opt<bool> OnlyListBelow( 2503 "list-below-cutoff", cl::init(false), 2504 cl::desc("Only output names of functions whose max count values are " 2505 "below the cutoff value")); 2506 cl::opt<bool> ShowProfileSymbolList( 2507 "show-prof-sym-list", cl::init(false), 2508 cl::desc("Show profile symbol list if it exists in the profile. ")); 2509 cl::opt<bool> ShowSectionInfoOnly( 2510 "show-sec-info-only", cl::init(false), 2511 cl::desc("Show the information of each section in the sample profile. " 2512 "The flag is only usable when the sample profile is in " 2513 "extbinary format")); 2514 cl::opt<bool> ShowBinaryIds("binary-ids", cl::init(false), 2515 cl::desc("Show binary ids in the profile. ")); 2516 2517 cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n"); 2518 2519 if (Filename == OutputFilename) { 2520 errs() << sys::path::filename(argv[0]) 2521 << ": Input file name cannot be the same as the output file name!\n"; 2522 return 1; 2523 } 2524 2525 std::error_code EC; 2526 raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::OF_TextWithCRLF); 2527 if (EC) 2528 exitWithErrorCode(EC, OutputFilename); 2529 2530 if (ShowAllFunctions && !ShowFunction.empty()) 2531 WithColor::warning() << "-function argument ignored: showing all functions\n"; 2532 2533 if (ProfileKind == instr) 2534 return showInstrProfile( 2535 Filename, ShowCounts, TopNFunctions, ShowIndirectCallTargets, 2536 ShowMemOPSizes, ShowDetailedSummary, DetailedSummaryCutoffs, 2537 ShowAllFunctions, ShowCS, ValueCutoff, OnlyListBelow, ShowFunction, 2538 TextFormat, ShowBinaryIds, OS); 2539 else 2540 return showSampleProfile(Filename, ShowCounts, ShowAllFunctions, 2541 ShowDetailedSummary, ShowFunction, 2542 ShowProfileSymbolList, ShowSectionInfoOnly, 2543 ShowHotFuncList, OS); 2544 } 2545 2546 int main(int argc, const char *argv[]) { 2547 InitLLVM X(argc, argv); 2548 2549 StringRef ProgName(sys::path::filename(argv[0])); 2550 if (argc > 1) { 2551 int (*func)(int, const char *[]) = nullptr; 2552 2553 if (strcmp(argv[1], "merge") == 0) 2554 func = merge_main; 2555 else if (strcmp(argv[1], "show") == 0) 2556 func = show_main; 2557 else if (strcmp(argv[1], "overlap") == 0) 2558 func = overlap_main; 2559 2560 if (func) { 2561 std::string Invocation(ProgName.str() + " " + argv[1]); 2562 argv[1] = Invocation.c_str(); 2563 return func(argc - 1, argv + 1); 2564 } 2565 2566 if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 || 2567 strcmp(argv[1], "--help") == 0) { 2568 2569 errs() << "OVERVIEW: LLVM profile data tools\n\n" 2570 << "USAGE: " << ProgName << " <command> [args...]\n" 2571 << "USAGE: " << ProgName << " <command> -help\n\n" 2572 << "See each individual command --help for more details.\n" 2573 << "Available commands: merge, show, overlap\n"; 2574 return 0; 2575 } 2576 } 2577 2578 if (argc < 2) 2579 errs() << ProgName << ": No command specified!\n"; 2580 else 2581 errs() << ProgName << ": Unknown command!\n"; 2582 2583 errs() << "USAGE: " << ProgName << " <merge|show|overlap> [args...]\n"; 2584 return 1; 2585 } 2586