1 //===- InstrProf.cpp - Instrumented 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 support for clang's instrumentation based PGO and 10 // coverage. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ProfileData/InstrProf.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/Config/config.h" 22 #include "llvm/IR/Constant.h" 23 #include "llvm/IR/Constants.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/GlobalValue.h" 26 #include "llvm/IR/GlobalVariable.h" 27 #include "llvm/IR/Instruction.h" 28 #include "llvm/IR/LLVMContext.h" 29 #include "llvm/IR/MDBuilder.h" 30 #include "llvm/IR/Metadata.h" 31 #include "llvm/IR/Module.h" 32 #include "llvm/IR/Type.h" 33 #include "llvm/ProfileData/InstrProfReader.h" 34 #include "llvm/Support/Casting.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/Compiler.h" 37 #include "llvm/Support/Compression.h" 38 #include "llvm/Support/Endian.h" 39 #include "llvm/Support/Error.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #include "llvm/Support/LEB128.h" 42 #include "llvm/Support/ManagedStatic.h" 43 #include "llvm/Support/MathExtras.h" 44 #include "llvm/Support/Path.h" 45 #include "llvm/Support/SwapByteOrder.h" 46 #include <algorithm> 47 #include <cassert> 48 #include <cstddef> 49 #include <cstdint> 50 #include <cstring> 51 #include <memory> 52 #include <string> 53 #include <system_error> 54 #include <utility> 55 #include <vector> 56 57 using namespace llvm; 58 59 static cl::opt<bool> StaticFuncFullModulePrefix( 60 "static-func-full-module-prefix", cl::init(true), cl::Hidden, 61 cl::desc("Use full module build paths in the profile counter names for " 62 "static functions.")); 63 64 // This option is tailored to users that have different top-level directory in 65 // profile-gen and profile-use compilation. Users need to specific the number 66 // of levels to strip. A value larger than the number of directories in the 67 // source file will strip all the directory names and only leave the basename. 68 // 69 // Note current ThinLTO module importing for the indirect-calls assumes 70 // the source directory name not being stripped. A non-zero option value here 71 // can potentially prevent some inter-module indirect-call-promotions. 72 static cl::opt<unsigned> StaticFuncStripDirNamePrefix( 73 "static-func-strip-dirname-prefix", cl::init(0), cl::Hidden, 74 cl::desc("Strip specified level of directory name from source path in " 75 "the profile counter name for static functions.")); 76 77 static std::string getInstrProfErrString(instrprof_error Err, 78 const std::string &ErrMsg = "") { 79 std::string Msg; 80 raw_string_ostream OS(Msg); 81 82 switch (Err) { 83 case instrprof_error::success: 84 OS << "success"; 85 break; 86 case instrprof_error::eof: 87 OS << "end of File"; 88 break; 89 case instrprof_error::unrecognized_format: 90 OS << "unrecognized instrumentation profile encoding format"; 91 break; 92 case instrprof_error::bad_magic: 93 OS << "invalid instrumentation profile data (bad magic)"; 94 break; 95 case instrprof_error::bad_header: 96 OS << "invalid instrumentation profile data (file header is corrupt)"; 97 break; 98 case instrprof_error::unsupported_version: 99 OS << "unsupported instrumentation profile format version"; 100 break; 101 case instrprof_error::unsupported_hash_type: 102 OS << "unsupported instrumentation profile hash type"; 103 break; 104 case instrprof_error::too_large: 105 OS << "too much profile data"; 106 break; 107 case instrprof_error::truncated: 108 OS << "truncated profile data"; 109 break; 110 case instrprof_error::malformed: 111 OS << "malformed instrumentation profile data"; 112 break; 113 case instrprof_error::invalid_prof: 114 OS << "invalid profile created. Please file a bug " 115 "at: " BUG_REPORT_URL 116 " and include the profraw files that caused this error."; 117 break; 118 case instrprof_error::unknown_function: 119 OS << "no profile data available for function"; 120 break; 121 case instrprof_error::hash_mismatch: 122 OS << "function control flow change detected (hash mismatch)"; 123 break; 124 case instrprof_error::count_mismatch: 125 OS << "function basic block count change detected (counter mismatch)"; 126 break; 127 case instrprof_error::counter_overflow: 128 OS << "counter overflow"; 129 break; 130 case instrprof_error::value_site_count_mismatch: 131 OS << "function value site count change detected (counter mismatch)"; 132 break; 133 case instrprof_error::compress_failed: 134 OS << "failed to compress data (zlib)"; 135 break; 136 case instrprof_error::uncompress_failed: 137 OS << "failed to uncompress data (zlib)"; 138 break; 139 case instrprof_error::empty_raw_profile: 140 OS << "empty raw profile file"; 141 break; 142 case instrprof_error::zlib_unavailable: 143 OS << "profile uses zlib compression but the profile reader was built " 144 "without zlib support"; 145 break; 146 } 147 148 // If optional error message is not empty, append it to the message. 149 if (!ErrMsg.empty()) 150 OS << ": " << ErrMsg; 151 152 return OS.str(); 153 } 154 155 namespace { 156 157 // FIXME: This class is only here to support the transition to llvm::Error. It 158 // will be removed once this transition is complete. Clients should prefer to 159 // deal with the Error value directly, rather than converting to error_code. 160 class InstrProfErrorCategoryType : public std::error_category { 161 const char *name() const noexcept override { return "llvm.instrprof"; } 162 163 std::string message(int IE) const override { 164 return getInstrProfErrString(static_cast<instrprof_error>(IE)); 165 } 166 }; 167 168 } // end anonymous namespace 169 170 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory; 171 172 const std::error_category &llvm::instrprof_category() { 173 return *ErrorCategory; 174 } 175 176 namespace { 177 178 const char *InstrProfSectNameCommon[] = { 179 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \ 180 SectNameCommon, 181 #include "llvm/ProfileData/InstrProfData.inc" 182 }; 183 184 const char *InstrProfSectNameCoff[] = { 185 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \ 186 SectNameCoff, 187 #include "llvm/ProfileData/InstrProfData.inc" 188 }; 189 190 const char *InstrProfSectNamePrefix[] = { 191 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \ 192 Prefix, 193 #include "llvm/ProfileData/InstrProfData.inc" 194 }; 195 196 } // namespace 197 198 namespace llvm { 199 200 cl::opt<bool> DoInstrProfNameCompression( 201 "enable-name-compression", 202 cl::desc("Enable name/filename string compression"), cl::init(true)); 203 204 std::string getInstrProfSectionName(InstrProfSectKind IPSK, 205 Triple::ObjectFormatType OF, 206 bool AddSegmentInfo) { 207 std::string SectName; 208 209 if (OF == Triple::MachO && AddSegmentInfo) 210 SectName = InstrProfSectNamePrefix[IPSK]; 211 212 if (OF == Triple::COFF) 213 SectName += InstrProfSectNameCoff[IPSK]; 214 else 215 SectName += InstrProfSectNameCommon[IPSK]; 216 217 if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo) 218 SectName += ",regular,live_support"; 219 220 return SectName; 221 } 222 223 void SoftInstrProfErrors::addError(instrprof_error IE) { 224 if (IE == instrprof_error::success) 225 return; 226 227 if (FirstError == instrprof_error::success) 228 FirstError = IE; 229 230 switch (IE) { 231 case instrprof_error::hash_mismatch: 232 ++NumHashMismatches; 233 break; 234 case instrprof_error::count_mismatch: 235 ++NumCountMismatches; 236 break; 237 case instrprof_error::counter_overflow: 238 ++NumCounterOverflows; 239 break; 240 case instrprof_error::value_site_count_mismatch: 241 ++NumValueSiteCountMismatches; 242 break; 243 default: 244 llvm_unreachable("Not a soft error"); 245 } 246 } 247 248 std::string InstrProfError::message() const { 249 return getInstrProfErrString(Err, Msg); 250 } 251 252 char InstrProfError::ID = 0; 253 254 std::string getPGOFuncName(StringRef RawFuncName, 255 GlobalValue::LinkageTypes Linkage, 256 StringRef FileName, 257 uint64_t Version LLVM_ATTRIBUTE_UNUSED) { 258 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName); 259 } 260 261 // Strip NumPrefix level of directory name from PathNameStr. If the number of 262 // directory separators is less than NumPrefix, strip all the directories and 263 // leave base file name only. 264 static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) { 265 uint32_t Count = NumPrefix; 266 uint32_t Pos = 0, LastPos = 0; 267 for (auto & CI : PathNameStr) { 268 ++Pos; 269 if (llvm::sys::path::is_separator(CI)) { 270 LastPos = Pos; 271 --Count; 272 } 273 if (Count == 0) 274 break; 275 } 276 return PathNameStr.substr(LastPos); 277 } 278 279 // Return the PGOFuncName. This function has some special handling when called 280 // in LTO optimization. The following only applies when calling in LTO passes 281 // (when \c InLTO is true): LTO's internalization privatizes many global linkage 282 // symbols. This happens after value profile annotation, but those internal 283 // linkage functions should not have a source prefix. 284 // Additionally, for ThinLTO mode, exported internal functions are promoted 285 // and renamed. We need to ensure that the original internal PGO name is 286 // used when computing the GUID that is compared against the profiled GUIDs. 287 // To differentiate compiler generated internal symbols from original ones, 288 // PGOFuncName meta data are created and attached to the original internal 289 // symbols in the value profile annotation step 290 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta 291 // data, its original linkage must be non-internal. 292 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) { 293 if (!InLTO) { 294 StringRef FileName(F.getParent()->getSourceFileName()); 295 uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1; 296 if (StripLevel < StaticFuncStripDirNamePrefix) 297 StripLevel = StaticFuncStripDirNamePrefix; 298 if (StripLevel) 299 FileName = stripDirPrefix(FileName, StripLevel); 300 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version); 301 } 302 303 // In LTO mode (when InLTO is true), first check if there is a meta data. 304 if (MDNode *MD = getPGOFuncNameMetadata(F)) { 305 StringRef S = cast<MDString>(MD->getOperand(0))->getString(); 306 return S.str(); 307 } 308 309 // If there is no meta data, the function must be a global before the value 310 // profile annotation pass. Its current linkage may be internal if it is 311 // internalized in LTO mode. 312 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, ""); 313 } 314 315 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) { 316 if (FileName.empty()) 317 return PGOFuncName; 318 // Drop the file name including ':'. See also getPGOFuncName. 319 if (PGOFuncName.startswith(FileName)) 320 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1); 321 return PGOFuncName; 322 } 323 324 // \p FuncName is the string used as profile lookup key for the function. A 325 // symbol is created to hold the name. Return the legalized symbol name. 326 std::string getPGOFuncNameVarName(StringRef FuncName, 327 GlobalValue::LinkageTypes Linkage) { 328 std::string VarName = std::string(getInstrProfNameVarPrefix()); 329 VarName += FuncName; 330 331 if (!GlobalValue::isLocalLinkage(Linkage)) 332 return VarName; 333 334 // Now fix up illegal chars in local VarName that may upset the assembler. 335 const char *InvalidChars = "-:<>/\"'"; 336 size_t found = VarName.find_first_of(InvalidChars); 337 while (found != std::string::npos) { 338 VarName[found] = '_'; 339 found = VarName.find_first_of(InvalidChars, found + 1); 340 } 341 return VarName; 342 } 343 344 GlobalVariable *createPGOFuncNameVar(Module &M, 345 GlobalValue::LinkageTypes Linkage, 346 StringRef PGOFuncName) { 347 // We generally want to match the function's linkage, but available_externally 348 // and extern_weak both have the wrong semantics, and anything that doesn't 349 // need to link across compilation units doesn't need to be visible at all. 350 if (Linkage == GlobalValue::ExternalWeakLinkage) 351 Linkage = GlobalValue::LinkOnceAnyLinkage; 352 else if (Linkage == GlobalValue::AvailableExternallyLinkage) 353 Linkage = GlobalValue::LinkOnceODRLinkage; 354 else if (Linkage == GlobalValue::InternalLinkage || 355 Linkage == GlobalValue::ExternalLinkage) 356 Linkage = GlobalValue::PrivateLinkage; 357 358 auto *Value = 359 ConstantDataArray::getString(M.getContext(), PGOFuncName, false); 360 auto FuncNameVar = 361 new GlobalVariable(M, Value->getType(), true, Linkage, Value, 362 getPGOFuncNameVarName(PGOFuncName, Linkage)); 363 364 // Hide the symbol so that we correctly get a copy for each executable. 365 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage())) 366 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility); 367 368 return FuncNameVar; 369 } 370 371 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) { 372 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName); 373 } 374 375 Error InstrProfSymtab::create(Module &M, bool InLTO) { 376 for (Function &F : M) { 377 // Function may not have a name: like using asm("") to overwrite the name. 378 // Ignore in this case. 379 if (!F.hasName()) 380 continue; 381 const std::string &PGOFuncName = getPGOFuncName(F, InLTO); 382 if (Error E = addFuncName(PGOFuncName)) 383 return E; 384 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F); 385 // In ThinLTO, local function may have been promoted to global and have 386 // suffix ".llvm." added to the function name. We need to add the 387 // stripped function name to the symbol table so that we can find a match 388 // from profile. 389 // 390 // We may have other suffixes similar as ".llvm." which are needed to 391 // be stripped before the matching, but ".__uniq." suffix which is used 392 // to differentiate internal linkage functions in different modules 393 // should be kept. Now this is the only suffix with the pattern ".xxx" 394 // which is kept before matching. 395 const std::string UniqSuffix = ".__uniq."; 396 auto pos = PGOFuncName.find(UniqSuffix); 397 // Search '.' after ".__uniq." if ".__uniq." exists, otherwise 398 // search '.' from the beginning. 399 if (pos != std::string::npos) 400 pos += UniqSuffix.length(); 401 else 402 pos = 0; 403 pos = PGOFuncName.find('.', pos); 404 if (pos != std::string::npos && pos != 0) { 405 const std::string &OtherFuncName = PGOFuncName.substr(0, pos); 406 if (Error E = addFuncName(OtherFuncName)) 407 return E; 408 MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F); 409 } 410 } 411 Sorted = false; 412 finalizeSymtab(); 413 return Error::success(); 414 } 415 416 uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) { 417 finalizeSymtab(); 418 auto It = partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) { 419 return A.first < Address; 420 }); 421 // Raw function pointer collected by value profiler may be from 422 // external functions that are not instrumented. They won't have 423 // mapping data to be used by the deserializer. Force the value to 424 // be 0 in this case. 425 if (It != AddrToMD5Map.end() && It->first == Address) 426 return (uint64_t)It->second; 427 return 0; 428 } 429 430 Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs, 431 bool doCompression, std::string &Result) { 432 assert(!NameStrs.empty() && "No name data to emit"); 433 434 uint8_t Header[16], *P = Header; 435 std::string UncompressedNameStrings = 436 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator()); 437 438 assert(StringRef(UncompressedNameStrings) 439 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) && 440 "PGO name is invalid (contains separator token)"); 441 442 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P); 443 P += EncLen; 444 445 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) { 446 EncLen = encodeULEB128(CompressedLen, P); 447 P += EncLen; 448 char *HeaderStr = reinterpret_cast<char *>(&Header[0]); 449 unsigned HeaderLen = P - &Header[0]; 450 Result.append(HeaderStr, HeaderLen); 451 Result += InputStr; 452 return Error::success(); 453 }; 454 455 if (!doCompression) { 456 return WriteStringToResult(0, UncompressedNameStrings); 457 } 458 459 SmallString<128> CompressedNameStrings; 460 Error E = zlib::compress(StringRef(UncompressedNameStrings), 461 CompressedNameStrings, zlib::BestSizeCompression); 462 if (E) { 463 consumeError(std::move(E)); 464 return make_error<InstrProfError>(instrprof_error::compress_failed); 465 } 466 467 return WriteStringToResult(CompressedNameStrings.size(), 468 CompressedNameStrings); 469 } 470 471 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) { 472 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer()); 473 StringRef NameStr = 474 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString(); 475 return NameStr; 476 } 477 478 Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars, 479 std::string &Result, bool doCompression) { 480 std::vector<std::string> NameStrs; 481 for (auto *NameVar : NameVars) { 482 NameStrs.push_back(std::string(getPGOFuncNameVarInitializer(NameVar))); 483 } 484 return collectPGOFuncNameStrings( 485 NameStrs, zlib::isAvailable() && doCompression, Result); 486 } 487 488 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) { 489 const uint8_t *P = NameStrings.bytes_begin(); 490 const uint8_t *EndP = NameStrings.bytes_end(); 491 while (P < EndP) { 492 uint32_t N; 493 uint64_t UncompressedSize = decodeULEB128(P, &N); 494 P += N; 495 uint64_t CompressedSize = decodeULEB128(P, &N); 496 P += N; 497 bool isCompressed = (CompressedSize != 0); 498 SmallString<128> UncompressedNameStrings; 499 StringRef NameStrings; 500 if (isCompressed) { 501 if (!llvm::zlib::isAvailable()) 502 return make_error<InstrProfError>(instrprof_error::zlib_unavailable); 503 504 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P), 505 CompressedSize); 506 if (Error E = 507 zlib::uncompress(CompressedNameStrings, UncompressedNameStrings, 508 UncompressedSize)) { 509 consumeError(std::move(E)); 510 return make_error<InstrProfError>(instrprof_error::uncompress_failed); 511 } 512 P += CompressedSize; 513 NameStrings = StringRef(UncompressedNameStrings.data(), 514 UncompressedNameStrings.size()); 515 } else { 516 NameStrings = 517 StringRef(reinterpret_cast<const char *>(P), UncompressedSize); 518 P += UncompressedSize; 519 } 520 // Now parse the name strings. 521 SmallVector<StringRef, 0> Names; 522 NameStrings.split(Names, getInstrProfNameSeparator()); 523 for (StringRef &Name : Names) 524 if (Error E = Symtab.addFuncName(Name)) 525 return E; 526 527 while (P < EndP && *P == 0) 528 P++; 529 } 530 return Error::success(); 531 } 532 533 void InstrProfRecord::accumulateCounts(CountSumOrPercent &Sum) const { 534 uint64_t FuncSum = 0; 535 Sum.NumEntries += Counts.size(); 536 for (uint64_t Count : Counts) 537 FuncSum += Count; 538 Sum.CountSum += FuncSum; 539 540 for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) { 541 uint64_t KindSum = 0; 542 uint32_t NumValueSites = getNumValueSites(VK); 543 for (size_t I = 0; I < NumValueSites; ++I) { 544 uint32_t NV = getNumValueDataForSite(VK, I); 545 std::unique_ptr<InstrProfValueData[]> VD = getValueForSite(VK, I); 546 for (uint32_t V = 0; V < NV; V++) 547 KindSum += VD[V].Count; 548 } 549 Sum.ValueCounts[VK] += KindSum; 550 } 551 } 552 553 void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input, 554 uint32_t ValueKind, 555 OverlapStats &Overlap, 556 OverlapStats &FuncLevelOverlap) { 557 this->sortByTargetValues(); 558 Input.sortByTargetValues(); 559 double Score = 0.0f, FuncLevelScore = 0.0f; 560 auto I = ValueData.begin(); 561 auto IE = ValueData.end(); 562 auto J = Input.ValueData.begin(); 563 auto JE = Input.ValueData.end(); 564 while (I != IE && J != JE) { 565 if (I->Value == J->Value) { 566 Score += OverlapStats::score(I->Count, J->Count, 567 Overlap.Base.ValueCounts[ValueKind], 568 Overlap.Test.ValueCounts[ValueKind]); 569 FuncLevelScore += OverlapStats::score( 570 I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind], 571 FuncLevelOverlap.Test.ValueCounts[ValueKind]); 572 ++I; 573 } else if (I->Value < J->Value) { 574 ++I; 575 continue; 576 } 577 ++J; 578 } 579 Overlap.Overlap.ValueCounts[ValueKind] += Score; 580 FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore; 581 } 582 583 // Return false on mismatch. 584 void InstrProfRecord::overlapValueProfData(uint32_t ValueKind, 585 InstrProfRecord &Other, 586 OverlapStats &Overlap, 587 OverlapStats &FuncLevelOverlap) { 588 uint32_t ThisNumValueSites = getNumValueSites(ValueKind); 589 assert(ThisNumValueSites == Other.getNumValueSites(ValueKind)); 590 if (!ThisNumValueSites) 591 return; 592 593 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords = 594 getOrCreateValueSitesForKind(ValueKind); 595 MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords = 596 Other.getValueSitesForKind(ValueKind); 597 for (uint32_t I = 0; I < ThisNumValueSites; I++) 598 ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap, 599 FuncLevelOverlap); 600 } 601 602 void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap, 603 OverlapStats &FuncLevelOverlap, 604 uint64_t ValueCutoff) { 605 // FuncLevel CountSum for other should already computed and nonzero. 606 assert(FuncLevelOverlap.Test.CountSum >= 1.0f); 607 accumulateCounts(FuncLevelOverlap.Base); 608 bool Mismatch = (Counts.size() != Other.Counts.size()); 609 610 // Check if the value profiles mismatch. 611 if (!Mismatch) { 612 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) { 613 uint32_t ThisNumValueSites = getNumValueSites(Kind); 614 uint32_t OtherNumValueSites = Other.getNumValueSites(Kind); 615 if (ThisNumValueSites != OtherNumValueSites) { 616 Mismatch = true; 617 break; 618 } 619 } 620 } 621 if (Mismatch) { 622 Overlap.addOneMismatch(FuncLevelOverlap.Test); 623 return; 624 } 625 626 // Compute overlap for value counts. 627 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) 628 overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap); 629 630 double Score = 0.0; 631 uint64_t MaxCount = 0; 632 // Compute overlap for edge counts. 633 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) { 634 Score += OverlapStats::score(Counts[I], Other.Counts[I], 635 Overlap.Base.CountSum, Overlap.Test.CountSum); 636 MaxCount = std::max(Other.Counts[I], MaxCount); 637 } 638 Overlap.Overlap.CountSum += Score; 639 Overlap.Overlap.NumEntries += 1; 640 641 if (MaxCount >= ValueCutoff) { 642 double FuncScore = 0.0; 643 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) 644 FuncScore += OverlapStats::score(Counts[I], Other.Counts[I], 645 FuncLevelOverlap.Base.CountSum, 646 FuncLevelOverlap.Test.CountSum); 647 FuncLevelOverlap.Overlap.CountSum = FuncScore; 648 FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size(); 649 FuncLevelOverlap.Valid = true; 650 } 651 } 652 653 void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input, 654 uint64_t Weight, 655 function_ref<void(instrprof_error)> Warn) { 656 this->sortByTargetValues(); 657 Input.sortByTargetValues(); 658 auto I = ValueData.begin(); 659 auto IE = ValueData.end(); 660 for (const InstrProfValueData &J : Input.ValueData) { 661 while (I != IE && I->Value < J.Value) 662 ++I; 663 if (I != IE && I->Value == J.Value) { 664 bool Overflowed; 665 I->Count = SaturatingMultiplyAdd(J.Count, Weight, I->Count, &Overflowed); 666 if (Overflowed) 667 Warn(instrprof_error::counter_overflow); 668 ++I; 669 continue; 670 } 671 ValueData.insert(I, J); 672 } 673 } 674 675 void InstrProfValueSiteRecord::scale(uint64_t N, uint64_t D, 676 function_ref<void(instrprof_error)> Warn) { 677 for (InstrProfValueData &I : ValueData) { 678 bool Overflowed; 679 I.Count = SaturatingMultiply(I.Count, N, &Overflowed) / D; 680 if (Overflowed) 681 Warn(instrprof_error::counter_overflow); 682 } 683 } 684 685 // Merge Value Profile data from Src record to this record for ValueKind. 686 // Scale merged value counts by \p Weight. 687 void InstrProfRecord::mergeValueProfData( 688 uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight, 689 function_ref<void(instrprof_error)> Warn) { 690 uint32_t ThisNumValueSites = getNumValueSites(ValueKind); 691 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind); 692 if (ThisNumValueSites != OtherNumValueSites) { 693 Warn(instrprof_error::value_site_count_mismatch); 694 return; 695 } 696 if (!ThisNumValueSites) 697 return; 698 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords = 699 getOrCreateValueSitesForKind(ValueKind); 700 MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords = 701 Src.getValueSitesForKind(ValueKind); 702 for (uint32_t I = 0; I < ThisNumValueSites; I++) 703 ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn); 704 } 705 706 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight, 707 function_ref<void(instrprof_error)> Warn) { 708 // If the number of counters doesn't match we either have bad data 709 // or a hash collision. 710 if (Counts.size() != Other.Counts.size()) { 711 Warn(instrprof_error::count_mismatch); 712 return; 713 } 714 715 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) { 716 bool Overflowed; 717 Counts[I] = 718 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed); 719 if (Overflowed) 720 Warn(instrprof_error::counter_overflow); 721 } 722 723 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) 724 mergeValueProfData(Kind, Other, Weight, Warn); 725 } 726 727 void InstrProfRecord::scaleValueProfData( 728 uint32_t ValueKind, uint64_t N, uint64_t D, 729 function_ref<void(instrprof_error)> Warn) { 730 for (auto &R : getValueSitesForKind(ValueKind)) 731 R.scale(N, D, Warn); 732 } 733 734 void InstrProfRecord::scale(uint64_t N, uint64_t D, 735 function_ref<void(instrprof_error)> Warn) { 736 assert(D != 0 && "D cannot be 0"); 737 for (auto &Count : this->Counts) { 738 bool Overflowed; 739 Count = SaturatingMultiply(Count, N, &Overflowed) / D; 740 if (Overflowed) 741 Warn(instrprof_error::counter_overflow); 742 } 743 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) 744 scaleValueProfData(Kind, N, D, Warn); 745 } 746 747 // Map indirect call target name hash to name string. 748 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind, 749 InstrProfSymtab *SymTab) { 750 if (!SymTab) 751 return Value; 752 753 if (ValueKind == IPVK_IndirectCallTarget) 754 return SymTab->getFunctionHashFromAddress(Value); 755 756 return Value; 757 } 758 759 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site, 760 InstrProfValueData *VData, uint32_t N, 761 InstrProfSymtab *ValueMap) { 762 for (uint32_t I = 0; I < N; I++) { 763 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap); 764 } 765 std::vector<InstrProfValueSiteRecord> &ValueSites = 766 getOrCreateValueSitesForKind(ValueKind); 767 if (N == 0) 768 ValueSites.emplace_back(); 769 else 770 ValueSites.emplace_back(VData, VData + N); 771 } 772 773 #define INSTR_PROF_COMMON_API_IMPL 774 #include "llvm/ProfileData/InstrProfData.inc" 775 776 /*! 777 * ValueProfRecordClosure Interface implementation for InstrProfRecord 778 * class. These C wrappers are used as adaptors so that C++ code can be 779 * invoked as callbacks. 780 */ 781 uint32_t getNumValueKindsInstrProf(const void *Record) { 782 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds(); 783 } 784 785 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) { 786 return reinterpret_cast<const InstrProfRecord *>(Record) 787 ->getNumValueSites(VKind); 788 } 789 790 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) { 791 return reinterpret_cast<const InstrProfRecord *>(Record) 792 ->getNumValueData(VKind); 793 } 794 795 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, 796 uint32_t S) { 797 return reinterpret_cast<const InstrProfRecord *>(R) 798 ->getNumValueDataForSite(VK, S); 799 } 800 801 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, 802 uint32_t K, uint32_t S) { 803 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S); 804 } 805 806 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) { 807 ValueProfData *VD = 808 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData()); 809 memset(VD, 0, TotalSizeInBytes); 810 return VD; 811 } 812 813 static ValueProfRecordClosure InstrProfRecordClosure = { 814 nullptr, 815 getNumValueKindsInstrProf, 816 getNumValueSitesInstrProf, 817 getNumValueDataInstrProf, 818 getNumValueDataForSiteInstrProf, 819 nullptr, 820 getValueForSiteInstrProf, 821 allocValueProfDataInstrProf}; 822 823 // Wrapper implementation using the closure mechanism. 824 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) { 825 auto Closure = InstrProfRecordClosure; 826 Closure.Record = &Record; 827 return getValueProfDataSize(&Closure); 828 } 829 830 // Wrapper implementation using the closure mechanism. 831 std::unique_ptr<ValueProfData> 832 ValueProfData::serializeFrom(const InstrProfRecord &Record) { 833 InstrProfRecordClosure.Record = &Record; 834 835 std::unique_ptr<ValueProfData> VPD( 836 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr)); 837 return VPD; 838 } 839 840 void ValueProfRecord::deserializeTo(InstrProfRecord &Record, 841 InstrProfSymtab *SymTab) { 842 Record.reserveSites(Kind, NumValueSites); 843 844 InstrProfValueData *ValueData = getValueProfRecordValueData(this); 845 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) { 846 uint8_t ValueDataCount = this->SiteCountArray[VSite]; 847 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab); 848 ValueData += ValueDataCount; 849 } 850 } 851 852 // For writing/serializing, Old is the host endianness, and New is 853 // byte order intended on disk. For Reading/deserialization, Old 854 // is the on-disk source endianness, and New is the host endianness. 855 void ValueProfRecord::swapBytes(support::endianness Old, 856 support::endianness New) { 857 using namespace support; 858 859 if (Old == New) 860 return; 861 862 if (getHostEndianness() != Old) { 863 sys::swapByteOrder<uint32_t>(NumValueSites); 864 sys::swapByteOrder<uint32_t>(Kind); 865 } 866 uint32_t ND = getValueProfRecordNumValueData(this); 867 InstrProfValueData *VD = getValueProfRecordValueData(this); 868 869 // No need to swap byte array: SiteCountArrray. 870 for (uint32_t I = 0; I < ND; I++) { 871 sys::swapByteOrder<uint64_t>(VD[I].Value); 872 sys::swapByteOrder<uint64_t>(VD[I].Count); 873 } 874 if (getHostEndianness() == Old) { 875 sys::swapByteOrder<uint32_t>(NumValueSites); 876 sys::swapByteOrder<uint32_t>(Kind); 877 } 878 } 879 880 void ValueProfData::deserializeTo(InstrProfRecord &Record, 881 InstrProfSymtab *SymTab) { 882 if (NumValueKinds == 0) 883 return; 884 885 ValueProfRecord *VR = getFirstValueProfRecord(this); 886 for (uint32_t K = 0; K < NumValueKinds; K++) { 887 VR->deserializeTo(Record, SymTab); 888 VR = getValueProfRecordNext(VR); 889 } 890 } 891 892 template <class T> 893 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) { 894 using namespace support; 895 896 if (Orig == little) 897 return endian::readNext<T, little, unaligned>(D); 898 else 899 return endian::readNext<T, big, unaligned>(D); 900 } 901 902 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) { 903 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize)) 904 ValueProfData()); 905 } 906 907 Error ValueProfData::checkIntegrity() { 908 if (NumValueKinds > IPVK_Last + 1) 909 return make_error<InstrProfError>( 910 instrprof_error::malformed, "number of value profile kinds is invalid"); 911 // Total size needs to be multiple of quadword size. 912 if (TotalSize % sizeof(uint64_t)) 913 return make_error<InstrProfError>( 914 instrprof_error::malformed, "total size is not multiples of quardword"); 915 916 ValueProfRecord *VR = getFirstValueProfRecord(this); 917 for (uint32_t K = 0; K < this->NumValueKinds; K++) { 918 if (VR->Kind > IPVK_Last) 919 return make_error<InstrProfError>(instrprof_error::malformed, 920 "value kind is invalid"); 921 VR = getValueProfRecordNext(VR); 922 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize) 923 return make_error<InstrProfError>( 924 instrprof_error::malformed, 925 "value profile address is greater than total size"); 926 } 927 return Error::success(); 928 } 929 930 Expected<std::unique_ptr<ValueProfData>> 931 ValueProfData::getValueProfData(const unsigned char *D, 932 const unsigned char *const BufferEnd, 933 support::endianness Endianness) { 934 using namespace support; 935 936 if (D + sizeof(ValueProfData) > BufferEnd) 937 return make_error<InstrProfError>(instrprof_error::truncated); 938 939 const unsigned char *Header = D; 940 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness); 941 if (D + TotalSize > BufferEnd) 942 return make_error<InstrProfError>(instrprof_error::too_large); 943 944 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize); 945 memcpy(VPD.get(), D, TotalSize); 946 // Byte swap. 947 VPD->swapBytesToHost(Endianness); 948 949 Error E = VPD->checkIntegrity(); 950 if (E) 951 return std::move(E); 952 953 return std::move(VPD); 954 } 955 956 void ValueProfData::swapBytesToHost(support::endianness Endianness) { 957 using namespace support; 958 959 if (Endianness == getHostEndianness()) 960 return; 961 962 sys::swapByteOrder<uint32_t>(TotalSize); 963 sys::swapByteOrder<uint32_t>(NumValueKinds); 964 965 ValueProfRecord *VR = getFirstValueProfRecord(this); 966 for (uint32_t K = 0; K < NumValueKinds; K++) { 967 VR->swapBytes(Endianness, getHostEndianness()); 968 VR = getValueProfRecordNext(VR); 969 } 970 } 971 972 void ValueProfData::swapBytesFromHost(support::endianness Endianness) { 973 using namespace support; 974 975 if (Endianness == getHostEndianness()) 976 return; 977 978 ValueProfRecord *VR = getFirstValueProfRecord(this); 979 for (uint32_t K = 0; K < NumValueKinds; K++) { 980 ValueProfRecord *NVR = getValueProfRecordNext(VR); 981 VR->swapBytes(getHostEndianness(), Endianness); 982 VR = NVR; 983 } 984 sys::swapByteOrder<uint32_t>(TotalSize); 985 sys::swapByteOrder<uint32_t>(NumValueKinds); 986 } 987 988 void annotateValueSite(Module &M, Instruction &Inst, 989 const InstrProfRecord &InstrProfR, 990 InstrProfValueKind ValueKind, uint32_t SiteIdx, 991 uint32_t MaxMDCount) { 992 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx); 993 if (!NV) 994 return; 995 996 uint64_t Sum = 0; 997 std::unique_ptr<InstrProfValueData[]> VD = 998 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum); 999 1000 ArrayRef<InstrProfValueData> VDs(VD.get(), NV); 1001 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount); 1002 } 1003 1004 void annotateValueSite(Module &M, Instruction &Inst, 1005 ArrayRef<InstrProfValueData> VDs, 1006 uint64_t Sum, InstrProfValueKind ValueKind, 1007 uint32_t MaxMDCount) { 1008 LLVMContext &Ctx = M.getContext(); 1009 MDBuilder MDHelper(Ctx); 1010 SmallVector<Metadata *, 3> Vals; 1011 // Tag 1012 Vals.push_back(MDHelper.createString("VP")); 1013 // Value Kind 1014 Vals.push_back(MDHelper.createConstant( 1015 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind))); 1016 // Total Count 1017 Vals.push_back( 1018 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum))); 1019 1020 // Value Profile Data 1021 uint32_t MDCount = MaxMDCount; 1022 for (auto &VD : VDs) { 1023 Vals.push_back(MDHelper.createConstant( 1024 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value))); 1025 Vals.push_back(MDHelper.createConstant( 1026 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count))); 1027 if (--MDCount == 0) 1028 break; 1029 } 1030 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals)); 1031 } 1032 1033 bool getValueProfDataFromInst(const Instruction &Inst, 1034 InstrProfValueKind ValueKind, 1035 uint32_t MaxNumValueData, 1036 InstrProfValueData ValueData[], 1037 uint32_t &ActualNumValueData, uint64_t &TotalC, 1038 bool GetNoICPValue) { 1039 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof); 1040 if (!MD) 1041 return false; 1042 1043 unsigned NOps = MD->getNumOperands(); 1044 1045 if (NOps < 5) 1046 return false; 1047 1048 // Operand 0 is a string tag "VP": 1049 MDString *Tag = cast<MDString>(MD->getOperand(0)); 1050 if (!Tag) 1051 return false; 1052 1053 if (!Tag->getString().equals("VP")) 1054 return false; 1055 1056 // Now check kind: 1057 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1)); 1058 if (!KindInt) 1059 return false; 1060 if (KindInt->getZExtValue() != ValueKind) 1061 return false; 1062 1063 // Get total count 1064 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2)); 1065 if (!TotalCInt) 1066 return false; 1067 TotalC = TotalCInt->getZExtValue(); 1068 1069 ActualNumValueData = 0; 1070 1071 for (unsigned I = 3; I < NOps; I += 2) { 1072 if (ActualNumValueData >= MaxNumValueData) 1073 break; 1074 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I)); 1075 ConstantInt *Count = 1076 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1)); 1077 if (!Value || !Count) 1078 return false; 1079 uint64_t CntValue = Count->getZExtValue(); 1080 if (!GetNoICPValue && (CntValue == NOMORE_ICP_MAGICNUM)) 1081 continue; 1082 ValueData[ActualNumValueData].Value = Value->getZExtValue(); 1083 ValueData[ActualNumValueData].Count = CntValue; 1084 ActualNumValueData++; 1085 } 1086 return true; 1087 } 1088 1089 MDNode *getPGOFuncNameMetadata(const Function &F) { 1090 return F.getMetadata(getPGOFuncNameMetadataName()); 1091 } 1092 1093 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) { 1094 // Only for internal linkage functions. 1095 if (PGOFuncName == F.getName()) 1096 return; 1097 // Don't create duplicated meta-data. 1098 if (getPGOFuncNameMetadata(F)) 1099 return; 1100 LLVMContext &C = F.getContext(); 1101 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName)); 1102 F.setMetadata(getPGOFuncNameMetadataName(), N); 1103 } 1104 1105 bool needsComdatForCounter(const Function &F, const Module &M) { 1106 if (F.hasComdat()) 1107 return true; 1108 1109 if (!Triple(M.getTargetTriple()).supportsCOMDAT()) 1110 return false; 1111 1112 // See createPGOFuncNameVar for more details. To avoid link errors, profile 1113 // counters for function with available_externally linkage needs to be changed 1114 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be 1115 // created. Without using comdat, duplicate entries won't be removed by the 1116 // linker leading to increased data segement size and raw profile size. Even 1117 // worse, since the referenced counter from profile per-function data object 1118 // will be resolved to the common strong definition, the profile counts for 1119 // available_externally functions will end up being duplicated in raw profile 1120 // data. This can result in distorted profile as the counts of those dups 1121 // will be accumulated by the profile merger. 1122 GlobalValue::LinkageTypes Linkage = F.getLinkage(); 1123 if (Linkage != GlobalValue::ExternalWeakLinkage && 1124 Linkage != GlobalValue::AvailableExternallyLinkage) 1125 return false; 1126 1127 return true; 1128 } 1129 1130 // Check if INSTR_PROF_RAW_VERSION_VAR is defined. 1131 bool isIRPGOFlagSet(const Module *M) { 1132 auto IRInstrVar = 1133 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)); 1134 if (!IRInstrVar || IRInstrVar->hasLocalLinkage()) 1135 return false; 1136 1137 // For CSPGO+LTO, this variable might be marked as non-prevailing and we only 1138 // have the decl. 1139 if (IRInstrVar->isDeclaration()) 1140 return true; 1141 1142 // Check if the flag is set. 1143 if (!IRInstrVar->hasInitializer()) 1144 return false; 1145 1146 auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer()); 1147 if (!InitVal) 1148 return false; 1149 return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0; 1150 } 1151 1152 // Check if we can safely rename this Comdat function. 1153 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) { 1154 if (F.getName().empty()) 1155 return false; 1156 if (!needsComdatForCounter(F, *(F.getParent()))) 1157 return false; 1158 // Unsafe to rename the address-taken function (which can be used in 1159 // function comparison). 1160 if (CheckAddressTaken && F.hasAddressTaken()) 1161 return false; 1162 // Only safe to do if this function may be discarded if it is not used 1163 // in the compilation unit. 1164 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage())) 1165 return false; 1166 1167 // For AvailableExternallyLinkage functions. 1168 if (!F.hasComdat()) { 1169 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage); 1170 return true; 1171 } 1172 return true; 1173 } 1174 1175 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime 1176 // aware this is an ir_level profile so it can set the version flag. 1177 GlobalVariable *createIRLevelProfileFlagVar(Module &M, bool IsCS, 1178 bool InstrEntryBBEnabled) { 1179 const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)); 1180 Type *IntTy64 = Type::getInt64Ty(M.getContext()); 1181 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF); 1182 if (IsCS) 1183 ProfileVersion |= VARIANT_MASK_CSIR_PROF; 1184 if (InstrEntryBBEnabled) 1185 ProfileVersion |= VARIANT_MASK_INSTR_ENTRY; 1186 auto IRLevelVersionVariable = new GlobalVariable( 1187 M, IntTy64, true, GlobalValue::WeakAnyLinkage, 1188 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), VarName); 1189 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility); 1190 Triple TT(M.getTargetTriple()); 1191 if (TT.supportsCOMDAT()) { 1192 IRLevelVersionVariable->setLinkage(GlobalValue::ExternalLinkage); 1193 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName)); 1194 } 1195 return IRLevelVersionVariable; 1196 } 1197 1198 // Create the variable for the profile file name. 1199 void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) { 1200 if (InstrProfileOutput.empty()) 1201 return; 1202 Constant *ProfileNameConst = 1203 ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true); 1204 GlobalVariable *ProfileNameVar = new GlobalVariable( 1205 M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage, 1206 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR)); 1207 Triple TT(M.getTargetTriple()); 1208 if (TT.supportsCOMDAT()) { 1209 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage); 1210 ProfileNameVar->setComdat(M.getOrInsertComdat( 1211 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR)))); 1212 } 1213 } 1214 1215 Error OverlapStats::accumulateCounts(const std::string &BaseFilename, 1216 const std::string &TestFilename, 1217 bool IsCS) { 1218 auto getProfileSum = [IsCS](const std::string &Filename, 1219 CountSumOrPercent &Sum) -> Error { 1220 auto ReaderOrErr = InstrProfReader::create(Filename); 1221 if (Error E = ReaderOrErr.takeError()) { 1222 return E; 1223 } 1224 auto Reader = std::move(ReaderOrErr.get()); 1225 Reader->accumulateCounts(Sum, IsCS); 1226 return Error::success(); 1227 }; 1228 auto Ret = getProfileSum(BaseFilename, Base); 1229 if (Ret) 1230 return Ret; 1231 Ret = getProfileSum(TestFilename, Test); 1232 if (Ret) 1233 return Ret; 1234 this->BaseFilename = &BaseFilename; 1235 this->TestFilename = &TestFilename; 1236 Valid = true; 1237 return Error::success(); 1238 } 1239 1240 void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) { 1241 Mismatch.NumEntries += 1; 1242 Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum; 1243 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) { 1244 if (Test.ValueCounts[I] >= 1.0f) 1245 Mismatch.ValueCounts[I] += 1246 MismatchFunc.ValueCounts[I] / Test.ValueCounts[I]; 1247 } 1248 } 1249 1250 void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) { 1251 Unique.NumEntries += 1; 1252 Unique.CountSum += UniqueFunc.CountSum / Test.CountSum; 1253 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) { 1254 if (Test.ValueCounts[I] >= 1.0f) 1255 Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I]; 1256 } 1257 } 1258 1259 void OverlapStats::dump(raw_fd_ostream &OS) const { 1260 if (!Valid) 1261 return; 1262 1263 const char *EntryName = 1264 (Level == ProgramLevel ? "functions" : "edge counters"); 1265 if (Level == ProgramLevel) { 1266 OS << "Profile overlap infomation for base_profile: " << *BaseFilename 1267 << " and test_profile: " << *TestFilename << "\nProgram level:\n"; 1268 } else { 1269 OS << "Function level:\n" 1270 << " Function: " << FuncName << " (Hash=" << FuncHash << ")\n"; 1271 } 1272 1273 OS << " # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n"; 1274 if (Mismatch.NumEntries) 1275 OS << " # of " << EntryName << " mismatch: " << Mismatch.NumEntries 1276 << "\n"; 1277 if (Unique.NumEntries) 1278 OS << " # of " << EntryName 1279 << " only in test_profile: " << Unique.NumEntries << "\n"; 1280 1281 OS << " Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100) 1282 << "\n"; 1283 if (Mismatch.NumEntries) 1284 OS << " Mismatched count percentage (Edge): " 1285 << format("%.3f%%", Mismatch.CountSum * 100) << "\n"; 1286 if (Unique.NumEntries) 1287 OS << " Percentage of Edge profile only in test_profile: " 1288 << format("%.3f%%", Unique.CountSum * 100) << "\n"; 1289 OS << " Edge profile base count sum: " << format("%.0f", Base.CountSum) 1290 << "\n" 1291 << " Edge profile test count sum: " << format("%.0f", Test.CountSum) 1292 << "\n"; 1293 1294 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) { 1295 if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f) 1296 continue; 1297 char ProfileKindName[20]; 1298 switch (I) { 1299 case IPVK_IndirectCallTarget: 1300 strncpy(ProfileKindName, "IndirectCall", 19); 1301 break; 1302 case IPVK_MemOPSize: 1303 strncpy(ProfileKindName, "MemOP", 19); 1304 break; 1305 default: 1306 snprintf(ProfileKindName, 19, "VP[%d]", I); 1307 break; 1308 } 1309 OS << " " << ProfileKindName 1310 << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100) 1311 << "\n"; 1312 if (Mismatch.NumEntries) 1313 OS << " Mismatched count percentage (" << ProfileKindName 1314 << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n"; 1315 if (Unique.NumEntries) 1316 OS << " Percentage of " << ProfileKindName 1317 << " profile only in test_profile: " 1318 << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n"; 1319 OS << " " << ProfileKindName 1320 << " profile base count sum: " << format("%.0f", Base.ValueCounts[I]) 1321 << "\n" 1322 << " " << ProfileKindName 1323 << " profile test count sum: " << format("%.0f", Test.ValueCounts[I]) 1324 << "\n"; 1325 } 1326 } 1327 1328 } // end namespace llvm 1329