1 //=-- SampleProf.cpp - Sample profiling format support --------------------===// 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 // This file contains common definitions used in the reading and writing of 10 // sample profile data. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ProfileData/SampleProf.h" 15 #include "llvm/Config/llvm-config.h" 16 #include "llvm/IR/DebugInfoMetadata.h" 17 #include "llvm/IR/PseudoProbe.h" 18 #include "llvm/ProfileData/SampleProfReader.h" 19 #include "llvm/Support/CommandLine.h" 20 #include "llvm/Support/Compiler.h" 21 #include "llvm/Support/Debug.h" 22 #include "llvm/Support/Error.h" 23 #include "llvm/Support/ErrorHandling.h" 24 #include "llvm/Support/LEB128.h" 25 #include "llvm/Support/ManagedStatic.h" 26 #include "llvm/Support/raw_ostream.h" 27 #include <string> 28 #include <system_error> 29 30 using namespace llvm; 31 using namespace sampleprof; 32 33 static cl::opt<uint64_t> ProfileSymbolListCutOff( 34 "profile-symbol-list-cutoff", cl::Hidden, cl::init(-1), cl::ZeroOrMore, 35 cl::desc("Cutoff value about how many symbols in profile symbol list " 36 "will be used. This is very useful for performance debugging")); 37 38 cl::opt<bool> GenerateMergedBaseProfiles( 39 "generate-merged-base-profiles", cl::init(true), cl::ZeroOrMore, 40 cl::desc("When generating nested context-sensitive profiles, always " 41 "generate extra base profile for function with all its context " 42 "profiles merged into it.")); 43 44 namespace llvm { 45 namespace sampleprof { 46 bool FunctionSamples::ProfileIsProbeBased = false; 47 bool FunctionSamples::ProfileIsCSFlat = false; 48 bool FunctionSamples::ProfileIsCSNested = false; 49 bool FunctionSamples::UseMD5 = false; 50 bool FunctionSamples::HasUniqSuffix = true; 51 bool FunctionSamples::ProfileIsFS = false; 52 } // namespace sampleprof 53 } // namespace llvm 54 55 namespace { 56 57 // FIXME: This class is only here to support the transition to llvm::Error. It 58 // will be removed once this transition is complete. Clients should prefer to 59 // deal with the Error value directly, rather than converting to error_code. 60 class SampleProfErrorCategoryType : public std::error_category { 61 const char *name() const noexcept override { return "llvm.sampleprof"; } 62 63 std::string message(int IE) const override { 64 sampleprof_error E = static_cast<sampleprof_error>(IE); 65 switch (E) { 66 case sampleprof_error::success: 67 return "Success"; 68 case sampleprof_error::bad_magic: 69 return "Invalid sample profile data (bad magic)"; 70 case sampleprof_error::unsupported_version: 71 return "Unsupported sample profile format version"; 72 case sampleprof_error::too_large: 73 return "Too much profile data"; 74 case sampleprof_error::truncated: 75 return "Truncated profile data"; 76 case sampleprof_error::malformed: 77 return "Malformed sample profile data"; 78 case sampleprof_error::unrecognized_format: 79 return "Unrecognized sample profile encoding format"; 80 case sampleprof_error::unsupported_writing_format: 81 return "Profile encoding format unsupported for writing operations"; 82 case sampleprof_error::truncated_name_table: 83 return "Truncated function name table"; 84 case sampleprof_error::not_implemented: 85 return "Unimplemented feature"; 86 case sampleprof_error::counter_overflow: 87 return "Counter overflow"; 88 case sampleprof_error::ostream_seek_unsupported: 89 return "Ostream does not support seek"; 90 case sampleprof_error::compress_failed: 91 return "Compress failure"; 92 case sampleprof_error::uncompress_failed: 93 return "Uncompress failure"; 94 case sampleprof_error::zlib_unavailable: 95 return "Zlib is unavailable"; 96 case sampleprof_error::hash_mismatch: 97 return "Function hash mismatch"; 98 } 99 llvm_unreachable("A value of sampleprof_error has no message."); 100 } 101 }; 102 103 } // end anonymous namespace 104 105 static ManagedStatic<SampleProfErrorCategoryType> ErrorCategory; 106 107 const std::error_category &llvm::sampleprof_category() { 108 return *ErrorCategory; 109 } 110 111 void LineLocation::print(raw_ostream &OS) const { 112 OS << LineOffset; 113 if (Discriminator > 0) 114 OS << "." << Discriminator; 115 } 116 117 raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS, 118 const LineLocation &Loc) { 119 Loc.print(OS); 120 return OS; 121 } 122 123 /// Merge the samples in \p Other into this record. 124 /// Optionally scale sample counts by \p Weight. 125 sampleprof_error SampleRecord::merge(const SampleRecord &Other, 126 uint64_t Weight) { 127 sampleprof_error Result; 128 Result = addSamples(Other.getSamples(), Weight); 129 for (const auto &I : Other.getCallTargets()) { 130 MergeResult(Result, addCalledTarget(I.first(), I.second, Weight)); 131 } 132 return Result; 133 } 134 135 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 136 LLVM_DUMP_METHOD void LineLocation::dump() const { print(dbgs()); } 137 #endif 138 139 /// Print the sample record to the stream \p OS indented by \p Indent. 140 void SampleRecord::print(raw_ostream &OS, unsigned Indent) const { 141 OS << NumSamples; 142 if (hasCalls()) { 143 OS << ", calls:"; 144 for (const auto &I : getSortedCallTargets()) 145 OS << " " << I.first << ":" << I.second; 146 } 147 OS << "\n"; 148 } 149 150 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 151 LLVM_DUMP_METHOD void SampleRecord::dump() const { print(dbgs(), 0); } 152 #endif 153 154 raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS, 155 const SampleRecord &Sample) { 156 Sample.print(OS, 0); 157 return OS; 158 } 159 160 /// Print the samples collected for a function on stream \p OS. 161 void FunctionSamples::print(raw_ostream &OS, unsigned Indent) const { 162 if (getFunctionHash()) 163 OS << "CFG checksum " << getFunctionHash() << "\n"; 164 165 OS << TotalSamples << ", " << TotalHeadSamples << ", " << BodySamples.size() 166 << " sampled lines\n"; 167 168 OS.indent(Indent); 169 if (!BodySamples.empty()) { 170 OS << "Samples collected in the function's body {\n"; 171 SampleSorter<LineLocation, SampleRecord> SortedBodySamples(BodySamples); 172 for (const auto &SI : SortedBodySamples.get()) { 173 OS.indent(Indent + 2); 174 OS << SI->first << ": " << SI->second; 175 } 176 OS.indent(Indent); 177 OS << "}\n"; 178 } else { 179 OS << "No samples collected in the function's body\n"; 180 } 181 182 OS.indent(Indent); 183 if (!CallsiteSamples.empty()) { 184 OS << "Samples collected in inlined callsites {\n"; 185 SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples( 186 CallsiteSamples); 187 for (const auto &CS : SortedCallsiteSamples.get()) { 188 for (const auto &FS : CS->second) { 189 OS.indent(Indent + 2); 190 OS << CS->first << ": inlined callee: " << FS.second.getName() << ": "; 191 FS.second.print(OS, Indent + 4); 192 } 193 } 194 OS.indent(Indent); 195 OS << "}\n"; 196 } else { 197 OS << "No inlined callsites in this function\n"; 198 } 199 } 200 201 raw_ostream &llvm::sampleprof::operator<<(raw_ostream &OS, 202 const FunctionSamples &FS) { 203 FS.print(OS); 204 return OS; 205 } 206 207 void sampleprof::sortFuncProfiles( 208 const SampleProfileMap &ProfileMap, 209 std::vector<NameFunctionSamples> &SortedProfiles) { 210 for (const auto &I : ProfileMap) { 211 assert(I.first == I.second.getContext() && "Inconsistent profile map"); 212 SortedProfiles.push_back(std::make_pair(I.second.getContext(), &I.second)); 213 } 214 llvm::stable_sort(SortedProfiles, [](const NameFunctionSamples &A, 215 const NameFunctionSamples &B) { 216 if (A.second->getTotalSamples() == B.second->getTotalSamples()) 217 return A.first < B.first; 218 return A.second->getTotalSamples() > B.second->getTotalSamples(); 219 }); 220 } 221 222 unsigned FunctionSamples::getOffset(const DILocation *DIL) { 223 return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) & 224 0xffff; 225 } 226 227 LineLocation FunctionSamples::getCallSiteIdentifier(const DILocation *DIL, 228 bool ProfileIsFS) { 229 if (FunctionSamples::ProfileIsProbeBased) { 230 // In a pseudo-probe based profile, a callsite is simply represented by the 231 // ID of the probe associated with the call instruction. The probe ID is 232 // encoded in the Discriminator field of the call instruction's debug 233 // metadata. 234 return LineLocation(PseudoProbeDwarfDiscriminator::extractProbeIndex( 235 DIL->getDiscriminator()), 236 0); 237 } else { 238 unsigned Discriminator = 239 ProfileIsFS ? DIL->getDiscriminator() : DIL->getBaseDiscriminator(); 240 return LineLocation(FunctionSamples::getOffset(DIL), Discriminator); 241 } 242 } 243 244 uint64_t FunctionSamples::getCallSiteHash(StringRef CalleeName, 245 const LineLocation &Callsite) { 246 uint64_t NameHash = std::hash<std::string>{}(CalleeName.str()); 247 uint64_t LocId = 248 (((uint64_t)Callsite.LineOffset) << 32) | Callsite.Discriminator; 249 return NameHash + (LocId << 5) + LocId; 250 } 251 252 const FunctionSamples *FunctionSamples::findFunctionSamples( 253 const DILocation *DIL, SampleProfileReaderItaniumRemapper *Remapper) const { 254 assert(DIL); 255 SmallVector<std::pair<LineLocation, StringRef>, 10> S; 256 257 const DILocation *PrevDIL = DIL; 258 for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) { 259 // Use C++ linkage name if possible. 260 StringRef Name = PrevDIL->getScope()->getSubprogram()->getLinkageName(); 261 if (Name.empty()) 262 Name = PrevDIL->getScope()->getSubprogram()->getName(); 263 S.emplace_back(FunctionSamples::getCallSiteIdentifier( 264 DIL, FunctionSamples::ProfileIsFS), 265 Name); 266 PrevDIL = DIL; 267 } 268 269 if (S.size() == 0) 270 return this; 271 const FunctionSamples *FS = this; 272 for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) { 273 FS = FS->findFunctionSamplesAt(S[i].first, S[i].second, Remapper); 274 } 275 return FS; 276 } 277 278 void FunctionSamples::findAllNames(DenseSet<StringRef> &NameSet) const { 279 NameSet.insert(getName()); 280 for (const auto &BS : BodySamples) 281 for (const auto &TS : BS.second.getCallTargets()) 282 NameSet.insert(TS.getKey()); 283 284 for (const auto &CS : CallsiteSamples) { 285 for (const auto &NameFS : CS.second) { 286 NameSet.insert(NameFS.first); 287 NameFS.second.findAllNames(NameSet); 288 } 289 } 290 } 291 292 const FunctionSamples *FunctionSamples::findFunctionSamplesAt( 293 const LineLocation &Loc, StringRef CalleeName, 294 SampleProfileReaderItaniumRemapper *Remapper) const { 295 CalleeName = getCanonicalFnName(CalleeName); 296 297 std::string CalleeGUID; 298 CalleeName = getRepInFormat(CalleeName, UseMD5, CalleeGUID); 299 300 auto iter = CallsiteSamples.find(Loc); 301 if (iter == CallsiteSamples.end()) 302 return nullptr; 303 auto FS = iter->second.find(CalleeName); 304 if (FS != iter->second.end()) 305 return &FS->second; 306 if (Remapper) { 307 if (auto NameInProfile = Remapper->lookUpNameInProfile(CalleeName)) { 308 auto FS = iter->second.find(*NameInProfile); 309 if (FS != iter->second.end()) 310 return &FS->second; 311 } 312 } 313 // If we cannot find exact match of the callee name, return the FS with 314 // the max total count. Only do this when CalleeName is not provided, 315 // i.e., only for indirect calls. 316 if (!CalleeName.empty()) 317 return nullptr; 318 uint64_t MaxTotalSamples = 0; 319 const FunctionSamples *R = nullptr; 320 for (const auto &NameFS : iter->second) 321 if (NameFS.second.getTotalSamples() >= MaxTotalSamples) { 322 MaxTotalSamples = NameFS.second.getTotalSamples(); 323 R = &NameFS.second; 324 } 325 return R; 326 } 327 328 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 329 LLVM_DUMP_METHOD void FunctionSamples::dump() const { print(dbgs(), 0); } 330 #endif 331 332 std::error_code ProfileSymbolList::read(const uint8_t *Data, 333 uint64_t ListSize) { 334 const char *ListStart = reinterpret_cast<const char *>(Data); 335 uint64_t Size = 0; 336 uint64_t StrNum = 0; 337 while (Size < ListSize && StrNum < ProfileSymbolListCutOff) { 338 StringRef Str(ListStart + Size); 339 add(Str); 340 Size += Str.size() + 1; 341 StrNum++; 342 } 343 if (Size != ListSize && StrNum != ProfileSymbolListCutOff) 344 return sampleprof_error::malformed; 345 return sampleprof_error::success; 346 } 347 348 void SampleContextTrimmer::trimAndMergeColdContextProfiles( 349 uint64_t ColdCountThreshold, bool TrimColdContext, bool MergeColdContext, 350 uint32_t ColdContextFrameLength, bool TrimBaseProfileOnly) { 351 if (!TrimColdContext && !MergeColdContext) 352 return; 353 354 // Nothing to merge if sample threshold is zero 355 if (ColdCountThreshold == 0) 356 return; 357 358 // Trimming base profiles only is mainly to honor the preinliner decsion. When 359 // MergeColdContext is true preinliner decsion is not honored anyway so turn 360 // off TrimBaseProfileOnly. 361 if (MergeColdContext) 362 TrimBaseProfileOnly = false; 363 364 // Filter the cold profiles from ProfileMap and move them into a tmp 365 // container 366 std::vector<std::pair<SampleContext, const FunctionSamples *>> ColdProfiles; 367 for (const auto &I : ProfileMap) { 368 const SampleContext &Context = I.first; 369 const FunctionSamples &FunctionProfile = I.second; 370 if (FunctionProfile.getTotalSamples() < ColdCountThreshold && 371 (!TrimBaseProfileOnly || Context.isBaseContext())) 372 ColdProfiles.emplace_back(Context, &I.second); 373 } 374 375 // Remove the cold profile from ProfileMap and merge them into 376 // MergedProfileMap by the last K frames of context 377 SampleProfileMap MergedProfileMap; 378 for (const auto &I : ColdProfiles) { 379 if (MergeColdContext) { 380 auto MergedContext = I.second->getContext().getContextFrames(); 381 if (ColdContextFrameLength < MergedContext.size()) 382 MergedContext = MergedContext.take_back(ColdContextFrameLength); 383 auto Ret = MergedProfileMap.emplace(MergedContext, FunctionSamples()); 384 FunctionSamples &MergedProfile = Ret.first->second; 385 MergedProfile.merge(*I.second); 386 } 387 ProfileMap.erase(I.first); 388 } 389 390 // Move the merged profiles into ProfileMap; 391 for (const auto &I : MergedProfileMap) { 392 // Filter the cold merged profile 393 if (TrimColdContext && I.second.getTotalSamples() < ColdCountThreshold && 394 ProfileMap.find(I.first) == ProfileMap.end()) 395 continue; 396 // Merge the profile if the original profile exists, otherwise just insert 397 // as a new profile 398 auto Ret = ProfileMap.emplace(I.first, FunctionSamples()); 399 if (Ret.second) { 400 SampleContext FContext(Ret.first->first, RawContext); 401 FunctionSamples &FProfile = Ret.first->second; 402 FProfile.setContext(FContext); 403 } 404 FunctionSamples &OrigProfile = Ret.first->second; 405 OrigProfile.merge(I.second); 406 } 407 } 408 409 void SampleContextTrimmer::canonicalizeContextProfiles() { 410 std::vector<SampleContext> ProfilesToBeRemoved; 411 SampleProfileMap ProfilesToBeAdded; 412 for (auto &I : ProfileMap) { 413 FunctionSamples &FProfile = I.second; 414 SampleContext &Context = FProfile.getContext(); 415 if (I.first == Context) 416 continue; 417 418 // Use the context string from FunctionSamples to update the keys of 419 // ProfileMap. They can get out of sync after context profile promotion 420 // through pre-inliner. 421 // Duplicate the function profile for later insertion to avoid a conflict 422 // caused by a context both to be add and to be removed. This could happen 423 // when a context is promoted to another context which is also promoted to 424 // the third context. For example, given an original context A @ B @ C that 425 // is promoted to B @ C and the original context B @ C which is promoted to 426 // just C, adding B @ C to the profile map while removing same context (but 427 // with different profiles) from the map can cause a conflict if they are 428 // not handled in a right order. This can be solved by just caching the 429 // profiles to be added. 430 auto Ret = ProfilesToBeAdded.emplace(Context, FProfile); 431 (void)Ret; 432 assert(Ret.second && "Context conflict during canonicalization"); 433 ProfilesToBeRemoved.push_back(I.first); 434 } 435 436 for (auto &I : ProfilesToBeRemoved) { 437 ProfileMap.erase(I); 438 } 439 440 for (auto &I : ProfilesToBeAdded) { 441 ProfileMap.emplace(I.first, I.second); 442 } 443 } 444 445 std::error_code ProfileSymbolList::write(raw_ostream &OS) { 446 // Sort the symbols before output. If doing compression. 447 // It will make the compression much more effective. 448 std::vector<StringRef> SortedList(Syms.begin(), Syms.end()); 449 llvm::sort(SortedList); 450 451 std::string OutputString; 452 for (auto &Sym : SortedList) { 453 OutputString.append(Sym.str()); 454 OutputString.append(1, '\0'); 455 } 456 457 OS << OutputString; 458 return sampleprof_error::success; 459 } 460 461 void ProfileSymbolList::dump(raw_ostream &OS) const { 462 OS << "======== Dump profile symbol list ========\n"; 463 std::vector<StringRef> SortedList(Syms.begin(), Syms.end()); 464 llvm::sort(SortedList); 465 466 for (auto &Sym : SortedList) 467 OS << Sym << "\n"; 468 } 469 470 CSProfileConverter::FrameNode * 471 CSProfileConverter::FrameNode::getOrCreateChildFrame( 472 const LineLocation &CallSite, StringRef CalleeName) { 473 uint64_t Hash = FunctionSamples::getCallSiteHash(CalleeName, CallSite); 474 auto It = AllChildFrames.find(Hash); 475 if (It != AllChildFrames.end()) { 476 assert(It->second.FuncName == CalleeName && 477 "Hash collision for child context node"); 478 return &It->second; 479 } 480 481 AllChildFrames[Hash] = FrameNode(CalleeName, nullptr, CallSite); 482 return &AllChildFrames[Hash]; 483 } 484 485 CSProfileConverter::CSProfileConverter(SampleProfileMap &Profiles) 486 : ProfileMap(Profiles) { 487 for (auto &FuncSample : Profiles) { 488 FunctionSamples *FSamples = &FuncSample.second; 489 auto *NewNode = getOrCreateContextPath(FSamples->getContext()); 490 assert(!NewNode->FuncSamples && "New node cannot have sample profile"); 491 NewNode->FuncSamples = FSamples; 492 } 493 } 494 495 CSProfileConverter::FrameNode * 496 CSProfileConverter::getOrCreateContextPath(const SampleContext &Context) { 497 auto Node = &RootFrame; 498 LineLocation CallSiteLoc(0, 0); 499 for (auto &Callsite : Context.getContextFrames()) { 500 Node = Node->getOrCreateChildFrame(CallSiteLoc, Callsite.FuncName); 501 CallSiteLoc = Callsite.Location; 502 } 503 return Node; 504 } 505 506 void CSProfileConverter::convertProfiles(CSProfileConverter::FrameNode &Node) { 507 // Process each child profile. Add each child profile to callsite profile map 508 // of the current node `Node` if `Node` comes with a profile. Otherwise 509 // promote the child profile to a standalone profile. 510 auto *NodeProfile = Node.FuncSamples; 511 for (auto &It : Node.AllChildFrames) { 512 auto &ChildNode = It.second; 513 convertProfiles(ChildNode); 514 auto *ChildProfile = ChildNode.FuncSamples; 515 if (!ChildProfile) 516 continue; 517 SampleContext OrigChildContext = ChildProfile->getContext(); 518 // Reset the child context to be contextless. 519 ChildProfile->getContext().setName(OrigChildContext.getName()); 520 if (NodeProfile) { 521 // Add child profile to the callsite profile map. 522 auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc); 523 SamplesMap.emplace(OrigChildContext.getName().str(), *ChildProfile); 524 NodeProfile->addTotalSamples(ChildProfile->getTotalSamples()); 525 } 526 527 // Separate child profile to be a standalone profile, if the current parent 528 // profile doesn't exist. This is a duplicating operation when the child 529 // profile is already incorporated into the parent which is still useful and 530 // thus done optionally. It is seen that duplicating context profiles into 531 // base profiles improves the code quality for thinlto build by allowing a 532 // profile in the prelink phase for to-be-fully-inlined functions. 533 if (!NodeProfile) { 534 ProfileMap[ChildProfile->getContext()].merge(*ChildProfile); 535 } else if (GenerateMergedBaseProfiles) { 536 ProfileMap[ChildProfile->getContext()].merge(*ChildProfile); 537 auto &SamplesMap = NodeProfile->functionSamplesAt(ChildNode.CallSiteLoc); 538 SamplesMap[ChildProfile->getName().str()].getContext().setAttribute( 539 ContextDuplicatedIntoBase); 540 } 541 542 // Contexts coming with a `ContextShouldBeInlined` attribute indicate this 543 // is a preinliner-computed profile. 544 if (OrigChildContext.hasAttribute(ContextShouldBeInlined)) 545 FunctionSamples::ProfileIsCSNested = true; 546 547 // Remove the original child profile. 548 ProfileMap.erase(OrigChildContext); 549 } 550 } 551 552 void CSProfileConverter::convertProfiles() { convertProfiles(RootFrame); } 553