1 //===- SampleProfWriter.cpp - Write LLVM sample profile data --------------===// 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 implements the class that writes LLVM sample profiles. It 10 // supports two file formats: text and binary. The textual representation 11 // is useful for debugging and testing purposes. The binary representation 12 // is more compact, resulting in smaller file sizes. However, they can 13 // both be used interchangeably. 14 // 15 // See lib/ProfileData/SampleProfReader.cpp for documentation on each of the 16 // supported formats. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/ProfileData/SampleProfWriter.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/StringSet.h" 23 #include "llvm/ProfileData/ProfileCommon.h" 24 #include "llvm/ProfileData/SampleProf.h" 25 #include "llvm/Support/Compression.h" 26 #include "llvm/Support/Endian.h" 27 #include "llvm/Support/EndianStream.h" 28 #include "llvm/Support/ErrorOr.h" 29 #include "llvm/Support/FileSystem.h" 30 #include "llvm/Support/LEB128.h" 31 #include "llvm/Support/MD5.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <algorithm> 34 #include <cstdint> 35 #include <memory> 36 #include <set> 37 #include <system_error> 38 #include <utility> 39 #include <vector> 40 41 using namespace llvm; 42 using namespace sampleprof; 43 44 std::error_code 45 SampleProfileWriter::writeFuncProfiles(const SampleProfileMap &ProfileMap) { 46 std::vector<NameFunctionSamples> V; 47 sortFuncProfiles(ProfileMap, V); 48 for (const auto &I : V) { 49 if (std::error_code EC = writeSample(*I.second)) 50 return EC; 51 } 52 return sampleprof_error::success; 53 } 54 55 std::error_code SampleProfileWriter::write(const SampleProfileMap &ProfileMap) { 56 if (std::error_code EC = writeHeader(ProfileMap)) 57 return EC; 58 59 if (std::error_code EC = writeFuncProfiles(ProfileMap)) 60 return EC; 61 62 return sampleprof_error::success; 63 } 64 65 /// Return the current position and prepare to use it as the start 66 /// position of a section given the section type \p Type and its position 67 /// \p LayoutIdx in SectionHdrLayout. 68 uint64_t 69 SampleProfileWriterExtBinaryBase::markSectionStart(SecType Type, 70 uint32_t LayoutIdx) { 71 uint64_t SectionStart = OutputStream->tell(); 72 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range"); 73 const auto &Entry = SectionHdrLayout[LayoutIdx]; 74 assert(Entry.Type == Type && "Unexpected section type"); 75 // Use LocalBuf as a temporary output for writting data. 76 if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress)) 77 LocalBufStream.swap(OutputStream); 78 return SectionStart; 79 } 80 81 std::error_code SampleProfileWriterExtBinaryBase::compressAndOutput() { 82 if (!llvm::zlib::isAvailable()) 83 return sampleprof_error::zlib_unavailable; 84 std::string &UncompressedStrings = 85 static_cast<raw_string_ostream *>(LocalBufStream.get())->str(); 86 if (UncompressedStrings.size() == 0) 87 return sampleprof_error::success; 88 auto &OS = *OutputStream; 89 SmallString<128> CompressedStrings; 90 llvm::Error E = zlib::compress(UncompressedStrings, CompressedStrings, 91 zlib::BestSizeCompression); 92 if (E) 93 return sampleprof_error::compress_failed; 94 encodeULEB128(UncompressedStrings.size(), OS); 95 encodeULEB128(CompressedStrings.size(), OS); 96 OS << CompressedStrings.str(); 97 UncompressedStrings.clear(); 98 return sampleprof_error::success; 99 } 100 101 /// Add a new section into section header table given the section type 102 /// \p Type, its position \p LayoutIdx in SectionHdrLayout and the 103 /// location \p SectionStart where the section should be written to. 104 std::error_code SampleProfileWriterExtBinaryBase::addNewSection( 105 SecType Type, uint32_t LayoutIdx, uint64_t SectionStart) { 106 assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range"); 107 const auto &Entry = SectionHdrLayout[LayoutIdx]; 108 assert(Entry.Type == Type && "Unexpected section type"); 109 if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress)) { 110 LocalBufStream.swap(OutputStream); 111 if (std::error_code EC = compressAndOutput()) 112 return EC; 113 } 114 SecHdrTable.push_back({Type, Entry.Flags, SectionStart - FileStart, 115 OutputStream->tell() - SectionStart, LayoutIdx}); 116 return sampleprof_error::success; 117 } 118 119 std::error_code 120 SampleProfileWriterExtBinaryBase::write(const SampleProfileMap &ProfileMap) { 121 if (std::error_code EC = writeHeader(ProfileMap)) 122 return EC; 123 124 std::string LocalBuf; 125 LocalBufStream = std::make_unique<raw_string_ostream>(LocalBuf); 126 if (std::error_code EC = writeSections(ProfileMap)) 127 return EC; 128 129 if (std::error_code EC = writeSecHdrTable()) 130 return EC; 131 132 return sampleprof_error::success; 133 } 134 135 std::error_code SampleProfileWriterExtBinaryBase::writeContextIdx( 136 const SampleContext &Context) { 137 if (Context.hasContext()) 138 return writeCSNameIdx(Context); 139 else 140 return SampleProfileWriterBinary::writeNameIdx(Context.getName()); 141 } 142 143 std::error_code 144 SampleProfileWriterExtBinaryBase::writeCSNameIdx(const SampleContext &Context) { 145 const auto &Ret = CSNameTable.find(Context); 146 if (Ret == CSNameTable.end()) 147 return sampleprof_error::truncated_name_table; 148 encodeULEB128(Ret->second, *OutputStream); 149 return sampleprof_error::success; 150 } 151 152 std::error_code 153 SampleProfileWriterExtBinaryBase::writeSample(const FunctionSamples &S) { 154 uint64_t Offset = OutputStream->tell(); 155 auto &Context = S.getContext(); 156 FuncOffsetTable[Context] = Offset - SecLBRProfileStart; 157 encodeULEB128(S.getHeadSamples(), *OutputStream); 158 return writeBody(S); 159 } 160 161 std::error_code SampleProfileWriterExtBinaryBase::writeFuncOffsetTable() { 162 auto &OS = *OutputStream; 163 164 // Write out the table size. 165 encodeULEB128(FuncOffsetTable.size(), OS); 166 167 // Write out FuncOffsetTable. 168 auto WriteItem = [&](const SampleContext &Context, uint64_t Offset) { 169 if (std::error_code EC = writeContextIdx(Context)) 170 return EC; 171 encodeULEB128(Offset, OS); 172 return (std::error_code)sampleprof_error::success; 173 }; 174 175 if (FunctionSamples::ProfileIsCS) { 176 // Sort the contexts before writing them out. This is to help fast load all 177 // context profiles for a function as well as their callee contexts which 178 // can help profile-guided importing for ThinLTO. 179 std::map<SampleContext, uint64_t> OrderedFuncOffsetTable( 180 FuncOffsetTable.begin(), FuncOffsetTable.end()); 181 for (const auto &Entry : OrderedFuncOffsetTable) { 182 if (std::error_code EC = WriteItem(Entry.first, Entry.second)) 183 return EC; 184 } 185 addSectionFlag(SecFuncOffsetTable, SecFuncOffsetFlags::SecFlagOrdered); 186 } else { 187 for (const auto &Entry : FuncOffsetTable) { 188 if (std::error_code EC = WriteItem(Entry.first, Entry.second)) 189 return EC; 190 } 191 } 192 193 FuncOffsetTable.clear(); 194 return sampleprof_error::success; 195 } 196 197 std::error_code SampleProfileWriterExtBinaryBase::writeFuncMetadata( 198 const SampleProfileMap &Profiles) { 199 if (!FunctionSamples::ProfileIsProbeBased && !FunctionSamples::ProfileIsCS) 200 return sampleprof_error::success; 201 auto &OS = *OutputStream; 202 for (const auto &Entry : Profiles) { 203 if (std::error_code EC = writeContextIdx(Entry.second.getContext())) 204 return EC; 205 if (FunctionSamples::ProfileIsProbeBased) 206 encodeULEB128(Entry.second.getFunctionHash(), OS); 207 if (FunctionSamples::ProfileIsCS) 208 encodeULEB128(Entry.second.getContext().getAllAttributes(), OS); 209 } 210 return sampleprof_error::success; 211 } 212 213 std::error_code SampleProfileWriterExtBinaryBase::writeNameTable() { 214 if (!UseMD5) 215 return SampleProfileWriterBinary::writeNameTable(); 216 217 auto &OS = *OutputStream; 218 std::set<StringRef> V; 219 stablizeNameTable(NameTable, V); 220 221 // Write out the MD5 name table. We wrote unencoded MD5 so reader can 222 // retrieve the name using the name index without having to read the 223 // whole name table. 224 encodeULEB128(NameTable.size(), OS); 225 support::endian::Writer Writer(OS, support::little); 226 for (auto N : V) 227 Writer.write(MD5Hash(N)); 228 return sampleprof_error::success; 229 } 230 231 std::error_code SampleProfileWriterExtBinaryBase::writeNameTableSection( 232 const SampleProfileMap &ProfileMap) { 233 for (const auto &I : ProfileMap) { 234 assert(I.first == I.second.getContext() && "Inconsistent profile map"); 235 addContext(I.second.getContext()); 236 addNames(I.second); 237 } 238 239 // If NameTable contains ".__uniq." suffix, set SecFlagUniqSuffix flag 240 // so compiler won't strip the suffix during profile matching after 241 // seeing the flag in the profile. 242 for (const auto &I : NameTable) { 243 if (I.first.contains(FunctionSamples::UniqSuffix)) { 244 addSectionFlag(SecNameTable, SecNameTableFlags::SecFlagUniqSuffix); 245 break; 246 } 247 } 248 249 if (auto EC = writeNameTable()) 250 return EC; 251 return sampleprof_error::success; 252 } 253 254 std::error_code SampleProfileWriterExtBinaryBase::writeCSNameTableSection() { 255 // Sort the names to make CSNameTable deterministic. 256 std::set<SampleContext> OrderedContexts; 257 for (const auto &I : CSNameTable) 258 OrderedContexts.insert(I.first); 259 assert(OrderedContexts.size() == CSNameTable.size() && 260 "Unmatched ordered and unordered contexts"); 261 uint64_t I = 0; 262 for (auto &Context : OrderedContexts) 263 CSNameTable[Context] = I++; 264 265 auto &OS = *OutputStream; 266 encodeULEB128(OrderedContexts.size(), OS); 267 support::endian::Writer Writer(OS, support::little); 268 for (auto Context : OrderedContexts) { 269 auto Frames = Context.getContextFrames(); 270 encodeULEB128(Frames.size(), OS); 271 for (auto &Callsite : Frames) { 272 if (std::error_code EC = writeNameIdx(Callsite.FuncName)) 273 return EC; 274 encodeULEB128(Callsite.Location.LineOffset, OS); 275 encodeULEB128(Callsite.Location.Discriminator, OS); 276 } 277 } 278 279 return sampleprof_error::success; 280 } 281 282 std::error_code 283 SampleProfileWriterExtBinaryBase::writeProfileSymbolListSection() { 284 if (ProfSymList && ProfSymList->size() > 0) 285 if (std::error_code EC = ProfSymList->write(*OutputStream)) 286 return EC; 287 288 return sampleprof_error::success; 289 } 290 291 std::error_code SampleProfileWriterExtBinaryBase::writeOneSection( 292 SecType Type, uint32_t LayoutIdx, const SampleProfileMap &ProfileMap) { 293 // The setting of SecFlagCompress should happen before markSectionStart. 294 if (Type == SecProfileSymbolList && ProfSymList && ProfSymList->toCompress()) 295 setToCompressSection(SecProfileSymbolList); 296 if (Type == SecFuncMetadata && FunctionSamples::ProfileIsProbeBased) 297 addSectionFlag(SecFuncMetadata, SecFuncMetadataFlags::SecFlagIsProbeBased); 298 if (Type == SecProfSummary && FunctionSamples::ProfileIsCS) 299 addSectionFlag(SecProfSummary, SecProfSummaryFlags::SecFlagFullContext); 300 if (Type == SecFuncMetadata && FunctionSamples::ProfileIsCS) 301 addSectionFlag(SecFuncMetadata, SecFuncMetadataFlags::SecFlagHasAttribute); 302 if (Type == SecProfSummary && FunctionSamples::ProfileIsFS) 303 addSectionFlag(SecProfSummary, SecProfSummaryFlags::SecFlagFSDiscriminator); 304 305 uint64_t SectionStart = markSectionStart(Type, LayoutIdx); 306 switch (Type) { 307 case SecProfSummary: 308 computeSummary(ProfileMap); 309 if (auto EC = writeSummary()) 310 return EC; 311 break; 312 case SecNameTable: 313 if (auto EC = writeNameTableSection(ProfileMap)) 314 return EC; 315 break; 316 case SecCSNameTable: 317 if (auto EC = writeCSNameTableSection()) 318 return EC; 319 break; 320 case SecLBRProfile: 321 SecLBRProfileStart = OutputStream->tell(); 322 if (std::error_code EC = writeFuncProfiles(ProfileMap)) 323 return EC; 324 break; 325 case SecFuncOffsetTable: 326 if (auto EC = writeFuncOffsetTable()) 327 return EC; 328 break; 329 case SecFuncMetadata: 330 if (std::error_code EC = writeFuncMetadata(ProfileMap)) 331 return EC; 332 break; 333 case SecProfileSymbolList: 334 if (auto EC = writeProfileSymbolListSection()) 335 return EC; 336 break; 337 default: 338 if (auto EC = writeCustomSection(Type)) 339 return EC; 340 break; 341 } 342 if (std::error_code EC = addNewSection(Type, LayoutIdx, SectionStart)) 343 return EC; 344 return sampleprof_error::success; 345 } 346 347 std::error_code SampleProfileWriterExtBinary::writeDefaultLayout( 348 const SampleProfileMap &ProfileMap) { 349 // The const indices passed to writeOneSection below are specifying the 350 // positions of the sections in SectionHdrLayout. Look at 351 // initSectionHdrLayout to find out where each section is located in 352 // SectionHdrLayout. 353 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap)) 354 return EC; 355 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap)) 356 return EC; 357 if (auto EC = writeOneSection(SecCSNameTable, 2, ProfileMap)) 358 return EC; 359 if (auto EC = writeOneSection(SecLBRProfile, 4, ProfileMap)) 360 return EC; 361 if (auto EC = writeOneSection(SecProfileSymbolList, 5, ProfileMap)) 362 return EC; 363 if (auto EC = writeOneSection(SecFuncOffsetTable, 3, ProfileMap)) 364 return EC; 365 if (auto EC = writeOneSection(SecFuncMetadata, 6, ProfileMap)) 366 return EC; 367 return sampleprof_error::success; 368 } 369 370 static void splitProfileMapToTwo(const SampleProfileMap &ProfileMap, 371 SampleProfileMap &ContextProfileMap, 372 SampleProfileMap &NoContextProfileMap) { 373 for (const auto &I : ProfileMap) { 374 if (I.second.getCallsiteSamples().size()) 375 ContextProfileMap.insert({I.first, I.second}); 376 else 377 NoContextProfileMap.insert({I.first, I.second}); 378 } 379 } 380 381 std::error_code SampleProfileWriterExtBinary::writeCtxSplitLayout( 382 const SampleProfileMap &ProfileMap) { 383 SampleProfileMap ContextProfileMap, NoContextProfileMap; 384 splitProfileMapToTwo(ProfileMap, ContextProfileMap, NoContextProfileMap); 385 386 if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap)) 387 return EC; 388 if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap)) 389 return EC; 390 if (auto EC = writeOneSection(SecLBRProfile, 3, ContextProfileMap)) 391 return EC; 392 if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ContextProfileMap)) 393 return EC; 394 // Mark the section to have no context. Note section flag needs to be set 395 // before writing the section. 396 addSectionFlag(5, SecCommonFlags::SecFlagFlat); 397 if (auto EC = writeOneSection(SecLBRProfile, 5, NoContextProfileMap)) 398 return EC; 399 // Mark the section to have no context. Note section flag needs to be set 400 // before writing the section. 401 addSectionFlag(4, SecCommonFlags::SecFlagFlat); 402 if (auto EC = writeOneSection(SecFuncOffsetTable, 4, NoContextProfileMap)) 403 return EC; 404 if (auto EC = writeOneSection(SecProfileSymbolList, 6, ProfileMap)) 405 return EC; 406 if (auto EC = writeOneSection(SecFuncMetadata, 7, ProfileMap)) 407 return EC; 408 409 return sampleprof_error::success; 410 } 411 412 std::error_code SampleProfileWriterExtBinary::writeSections( 413 const SampleProfileMap &ProfileMap) { 414 std::error_code EC; 415 if (SecLayout == DefaultLayout) 416 EC = writeDefaultLayout(ProfileMap); 417 else if (SecLayout == CtxSplitLayout) 418 EC = writeCtxSplitLayout(ProfileMap); 419 else 420 llvm_unreachable("Unsupported layout"); 421 return EC; 422 } 423 424 std::error_code 425 SampleProfileWriterCompactBinary::write(const SampleProfileMap &ProfileMap) { 426 if (std::error_code EC = SampleProfileWriter::write(ProfileMap)) 427 return EC; 428 if (std::error_code EC = writeFuncOffsetTable()) 429 return EC; 430 return sampleprof_error::success; 431 } 432 433 /// Write samples to a text file. 434 /// 435 /// Note: it may be tempting to implement this in terms of 436 /// FunctionSamples::print(). Please don't. The dump functionality is intended 437 /// for debugging and has no specified form. 438 /// 439 /// The format used here is more structured and deliberate because 440 /// it needs to be parsed by the SampleProfileReaderText class. 441 std::error_code SampleProfileWriterText::writeSample(const FunctionSamples &S) { 442 auto &OS = *OutputStream; 443 if (FunctionSamples::ProfileIsCS) 444 OS << "[" << S.getContext().toString() << "]:" << S.getTotalSamples(); 445 else 446 OS << S.getName() << ":" << S.getTotalSamples(); 447 448 if (Indent == 0) 449 OS << ":" << S.getHeadSamples(); 450 OS << "\n"; 451 452 SampleSorter<LineLocation, SampleRecord> SortedSamples(S.getBodySamples()); 453 for (const auto &I : SortedSamples.get()) { 454 LineLocation Loc = I->first; 455 const SampleRecord &Sample = I->second; 456 OS.indent(Indent + 1); 457 if (Loc.Discriminator == 0) 458 OS << Loc.LineOffset << ": "; 459 else 460 OS << Loc.LineOffset << "." << Loc.Discriminator << ": "; 461 462 OS << Sample.getSamples(); 463 464 for (const auto &J : Sample.getSortedCallTargets()) 465 OS << " " << J.first << ":" << J.second; 466 OS << "\n"; 467 } 468 469 SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples( 470 S.getCallsiteSamples()); 471 Indent += 1; 472 for (const auto &I : SortedCallsiteSamples.get()) 473 for (const auto &FS : I->second) { 474 LineLocation Loc = I->first; 475 const FunctionSamples &CalleeSamples = FS.second; 476 OS.indent(Indent); 477 if (Loc.Discriminator == 0) 478 OS << Loc.LineOffset << ": "; 479 else 480 OS << Loc.LineOffset << "." << Loc.Discriminator << ": "; 481 if (std::error_code EC = writeSample(CalleeSamples)) 482 return EC; 483 } 484 Indent -= 1; 485 486 if (Indent == 0) { 487 if (FunctionSamples::ProfileIsProbeBased) { 488 OS.indent(Indent + 1); 489 OS << "!CFGChecksum: " << S.getFunctionHash() << "\n"; 490 } 491 if (FunctionSamples::ProfileIsCS) { 492 OS.indent(Indent + 1); 493 OS << "!Attributes: " << S.getContext().getAllAttributes() << "\n"; 494 } 495 } 496 497 return sampleprof_error::success; 498 } 499 500 std::error_code 501 SampleProfileWriterBinary::writeContextIdx(const SampleContext &Context) { 502 assert(!Context.hasContext() && "cs profile is not supported"); 503 return writeNameIdx(Context.getName()); 504 } 505 506 std::error_code SampleProfileWriterBinary::writeNameIdx(StringRef FName) { 507 auto &NTable = getNameTable(); 508 const auto &Ret = NTable.find(FName); 509 if (Ret == NTable.end()) 510 return sampleprof_error::truncated_name_table; 511 encodeULEB128(Ret->second, *OutputStream); 512 return sampleprof_error::success; 513 } 514 515 void SampleProfileWriterBinary::addName(StringRef FName) { 516 auto &NTable = getNameTable(); 517 NTable.insert(std::make_pair(FName, 0)); 518 } 519 520 void SampleProfileWriterBinary::addContext(const SampleContext &Context) { 521 addName(Context.getName()); 522 } 523 524 void SampleProfileWriterBinary::addNames(const FunctionSamples &S) { 525 // Add all the names in indirect call targets. 526 for (const auto &I : S.getBodySamples()) { 527 const SampleRecord &Sample = I.second; 528 for (const auto &J : Sample.getCallTargets()) 529 addName(J.first()); 530 } 531 532 // Recursively add all the names for inlined callsites. 533 for (const auto &J : S.getCallsiteSamples()) 534 for (const auto &FS : J.second) { 535 const FunctionSamples &CalleeSamples = FS.second; 536 addName(CalleeSamples.getName()); 537 addNames(CalleeSamples); 538 } 539 } 540 541 void SampleProfileWriterExtBinaryBase::addContext( 542 const SampleContext &Context) { 543 if (Context.hasContext()) { 544 for (auto &Callsite : Context.getContextFrames()) 545 SampleProfileWriterBinary::addName(Callsite.FuncName); 546 CSNameTable.insert(std::make_pair(Context, 0)); 547 } else { 548 SampleProfileWriterBinary::addName(Context.getName()); 549 } 550 } 551 552 void SampleProfileWriterBinary::stablizeNameTable( 553 MapVector<StringRef, uint32_t> &NameTable, std::set<StringRef> &V) { 554 // Sort the names to make NameTable deterministic. 555 for (const auto &I : NameTable) 556 V.insert(I.first); 557 int i = 0; 558 for (const StringRef &N : V) 559 NameTable[N] = i++; 560 } 561 562 std::error_code SampleProfileWriterBinary::writeNameTable() { 563 auto &OS = *OutputStream; 564 std::set<StringRef> V; 565 stablizeNameTable(NameTable, V); 566 567 // Write out the name table. 568 encodeULEB128(NameTable.size(), OS); 569 for (auto N : V) { 570 OS << N; 571 encodeULEB128(0, OS); 572 } 573 return sampleprof_error::success; 574 } 575 576 std::error_code SampleProfileWriterCompactBinary::writeFuncOffsetTable() { 577 auto &OS = *OutputStream; 578 579 // Fill the slot remembered by TableOffset with the offset of FuncOffsetTable. 580 auto &OFS = static_cast<raw_fd_ostream &>(OS); 581 uint64_t FuncOffsetTableStart = OS.tell(); 582 if (OFS.seek(TableOffset) == (uint64_t)-1) 583 return sampleprof_error::ostream_seek_unsupported; 584 support::endian::Writer Writer(*OutputStream, support::little); 585 Writer.write(FuncOffsetTableStart); 586 if (OFS.seek(FuncOffsetTableStart) == (uint64_t)-1) 587 return sampleprof_error::ostream_seek_unsupported; 588 589 // Write out the table size. 590 encodeULEB128(FuncOffsetTable.size(), OS); 591 592 // Write out FuncOffsetTable. 593 for (auto Entry : FuncOffsetTable) { 594 if (std::error_code EC = writeNameIdx(Entry.first)) 595 return EC; 596 encodeULEB128(Entry.second, OS); 597 } 598 return sampleprof_error::success; 599 } 600 601 std::error_code SampleProfileWriterCompactBinary::writeNameTable() { 602 auto &OS = *OutputStream; 603 std::set<StringRef> V; 604 stablizeNameTable(NameTable, V); 605 606 // Write out the name table. 607 encodeULEB128(NameTable.size(), OS); 608 for (auto N : V) { 609 encodeULEB128(MD5Hash(N), OS); 610 } 611 return sampleprof_error::success; 612 } 613 614 std::error_code 615 SampleProfileWriterBinary::writeMagicIdent(SampleProfileFormat Format) { 616 auto &OS = *OutputStream; 617 // Write file magic identifier. 618 encodeULEB128(SPMagic(Format), OS); 619 encodeULEB128(SPVersion(), OS); 620 return sampleprof_error::success; 621 } 622 623 std::error_code 624 SampleProfileWriterBinary::writeHeader(const SampleProfileMap &ProfileMap) { 625 writeMagicIdent(Format); 626 627 computeSummary(ProfileMap); 628 if (auto EC = writeSummary()) 629 return EC; 630 631 // Generate the name table for all the functions referenced in the profile. 632 for (const auto &I : ProfileMap) { 633 assert(I.first == I.second.getContext() && "Inconsistent profile map"); 634 addContext(I.first); 635 addNames(I.second); 636 } 637 638 writeNameTable(); 639 return sampleprof_error::success; 640 } 641 642 void SampleProfileWriterExtBinaryBase::setToCompressAllSections() { 643 for (auto &Entry : SectionHdrLayout) 644 addSecFlag(Entry, SecCommonFlags::SecFlagCompress); 645 } 646 647 void SampleProfileWriterExtBinaryBase::setToCompressSection(SecType Type) { 648 addSectionFlag(Type, SecCommonFlags::SecFlagCompress); 649 } 650 651 void SampleProfileWriterExtBinaryBase::allocSecHdrTable() { 652 support::endian::Writer Writer(*OutputStream, support::little); 653 654 Writer.write(static_cast<uint64_t>(SectionHdrLayout.size())); 655 SecHdrTableOffset = OutputStream->tell(); 656 for (uint32_t i = 0; i < SectionHdrLayout.size(); i++) { 657 Writer.write(static_cast<uint64_t>(-1)); 658 Writer.write(static_cast<uint64_t>(-1)); 659 Writer.write(static_cast<uint64_t>(-1)); 660 Writer.write(static_cast<uint64_t>(-1)); 661 } 662 } 663 664 std::error_code SampleProfileWriterExtBinaryBase::writeSecHdrTable() { 665 auto &OFS = static_cast<raw_fd_ostream &>(*OutputStream); 666 uint64_t Saved = OutputStream->tell(); 667 668 // Set OutputStream to the location saved in SecHdrTableOffset. 669 if (OFS.seek(SecHdrTableOffset) == (uint64_t)-1) 670 return sampleprof_error::ostream_seek_unsupported; 671 support::endian::Writer Writer(*OutputStream, support::little); 672 673 assert(SecHdrTable.size() == SectionHdrLayout.size() && 674 "SecHdrTable entries doesn't match SectionHdrLayout"); 675 SmallVector<uint32_t, 16> IndexMap(SecHdrTable.size(), -1); 676 for (uint32_t TableIdx = 0; TableIdx < SecHdrTable.size(); TableIdx++) { 677 IndexMap[SecHdrTable[TableIdx].LayoutIndex] = TableIdx; 678 } 679 680 // Write the section header table in the order specified in 681 // SectionHdrLayout. SectionHdrLayout specifies the sections 682 // order in which profile reader expect to read, so the section 683 // header table should be written in the order in SectionHdrLayout. 684 // Note that the section order in SecHdrTable may be different 685 // from the order in SectionHdrLayout, for example, SecFuncOffsetTable 686 // needs to be computed after SecLBRProfile (the order in SecHdrTable), 687 // but it needs to be read before SecLBRProfile (the order in 688 // SectionHdrLayout). So we use IndexMap above to switch the order. 689 for (uint32_t LayoutIdx = 0; LayoutIdx < SectionHdrLayout.size(); 690 LayoutIdx++) { 691 assert(IndexMap[LayoutIdx] < SecHdrTable.size() && 692 "Incorrect LayoutIdx in SecHdrTable"); 693 auto Entry = SecHdrTable[IndexMap[LayoutIdx]]; 694 Writer.write(static_cast<uint64_t>(Entry.Type)); 695 Writer.write(static_cast<uint64_t>(Entry.Flags)); 696 Writer.write(static_cast<uint64_t>(Entry.Offset)); 697 Writer.write(static_cast<uint64_t>(Entry.Size)); 698 } 699 700 // Reset OutputStream. 701 if (OFS.seek(Saved) == (uint64_t)-1) 702 return sampleprof_error::ostream_seek_unsupported; 703 704 return sampleprof_error::success; 705 } 706 707 std::error_code SampleProfileWriterExtBinaryBase::writeHeader( 708 const SampleProfileMap &ProfileMap) { 709 auto &OS = *OutputStream; 710 FileStart = OS.tell(); 711 writeMagicIdent(Format); 712 713 allocSecHdrTable(); 714 return sampleprof_error::success; 715 } 716 717 std::error_code SampleProfileWriterCompactBinary::writeHeader( 718 const SampleProfileMap &ProfileMap) { 719 support::endian::Writer Writer(*OutputStream, support::little); 720 if (auto EC = SampleProfileWriterBinary::writeHeader(ProfileMap)) 721 return EC; 722 723 // Reserve a slot for the offset of function offset table. The slot will 724 // be populated with the offset of FuncOffsetTable later. 725 TableOffset = OutputStream->tell(); 726 Writer.write(static_cast<uint64_t>(-2)); 727 return sampleprof_error::success; 728 } 729 730 std::error_code SampleProfileWriterBinary::writeSummary() { 731 auto &OS = *OutputStream; 732 encodeULEB128(Summary->getTotalCount(), OS); 733 encodeULEB128(Summary->getMaxCount(), OS); 734 encodeULEB128(Summary->getMaxFunctionCount(), OS); 735 encodeULEB128(Summary->getNumCounts(), OS); 736 encodeULEB128(Summary->getNumFunctions(), OS); 737 const std::vector<ProfileSummaryEntry> &Entries = 738 Summary->getDetailedSummary(); 739 encodeULEB128(Entries.size(), OS); 740 for (auto Entry : Entries) { 741 encodeULEB128(Entry.Cutoff, OS); 742 encodeULEB128(Entry.MinCount, OS); 743 encodeULEB128(Entry.NumCounts, OS); 744 } 745 return sampleprof_error::success; 746 } 747 std::error_code SampleProfileWriterBinary::writeBody(const FunctionSamples &S) { 748 auto &OS = *OutputStream; 749 if (std::error_code EC = writeContextIdx(S.getContext())) 750 return EC; 751 752 encodeULEB128(S.getTotalSamples(), OS); 753 754 // Emit all the body samples. 755 encodeULEB128(S.getBodySamples().size(), OS); 756 for (const auto &I : S.getBodySamples()) { 757 LineLocation Loc = I.first; 758 const SampleRecord &Sample = I.second; 759 encodeULEB128(Loc.LineOffset, OS); 760 encodeULEB128(Loc.Discriminator, OS); 761 encodeULEB128(Sample.getSamples(), OS); 762 encodeULEB128(Sample.getCallTargets().size(), OS); 763 for (const auto &J : Sample.getSortedCallTargets()) { 764 StringRef Callee = J.first; 765 uint64_t CalleeSamples = J.second; 766 if (std::error_code EC = writeNameIdx(Callee)) 767 return EC; 768 encodeULEB128(CalleeSamples, OS); 769 } 770 } 771 772 // Recursively emit all the callsite samples. 773 uint64_t NumCallsites = 0; 774 for (const auto &J : S.getCallsiteSamples()) 775 NumCallsites += J.second.size(); 776 encodeULEB128(NumCallsites, OS); 777 for (const auto &J : S.getCallsiteSamples()) 778 for (const auto &FS : J.second) { 779 LineLocation Loc = J.first; 780 const FunctionSamples &CalleeSamples = FS.second; 781 encodeULEB128(Loc.LineOffset, OS); 782 encodeULEB128(Loc.Discriminator, OS); 783 if (std::error_code EC = writeBody(CalleeSamples)) 784 return EC; 785 } 786 787 return sampleprof_error::success; 788 } 789 790 /// Write samples of a top-level function to a binary file. 791 /// 792 /// \returns true if the samples were written successfully, false otherwise. 793 std::error_code 794 SampleProfileWriterBinary::writeSample(const FunctionSamples &S) { 795 encodeULEB128(S.getHeadSamples(), *OutputStream); 796 return writeBody(S); 797 } 798 799 std::error_code 800 SampleProfileWriterCompactBinary::writeSample(const FunctionSamples &S) { 801 uint64_t Offset = OutputStream->tell(); 802 StringRef Name = S.getName(); 803 FuncOffsetTable[Name] = Offset; 804 encodeULEB128(S.getHeadSamples(), *OutputStream); 805 return writeBody(S); 806 } 807 808 /// Create a sample profile file writer based on the specified format. 809 /// 810 /// \param Filename The file to create. 811 /// 812 /// \param Format Encoding format for the profile file. 813 /// 814 /// \returns an error code indicating the status of the created writer. 815 ErrorOr<std::unique_ptr<SampleProfileWriter>> 816 SampleProfileWriter::create(StringRef Filename, SampleProfileFormat Format) { 817 std::error_code EC; 818 std::unique_ptr<raw_ostream> OS; 819 if (Format == SPF_Binary || Format == SPF_Ext_Binary || 820 Format == SPF_Compact_Binary) 821 OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_None)); 822 else 823 OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_TextWithCRLF)); 824 if (EC) 825 return EC; 826 827 return create(OS, Format); 828 } 829 830 /// Create a sample profile stream writer based on the specified format. 831 /// 832 /// \param OS The output stream to store the profile data to. 833 /// 834 /// \param Format Encoding format for the profile file. 835 /// 836 /// \returns an error code indicating the status of the created writer. 837 ErrorOr<std::unique_ptr<SampleProfileWriter>> 838 SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS, 839 SampleProfileFormat Format) { 840 std::error_code EC; 841 std::unique_ptr<SampleProfileWriter> Writer; 842 843 // Currently only Text and Extended Binary format are supported for CSSPGO. 844 if ((FunctionSamples::ProfileIsCS || FunctionSamples::ProfileIsProbeBased) && 845 (Format == SPF_Binary || Format == SPF_Compact_Binary)) 846 return sampleprof_error::unsupported_writing_format; 847 848 if (Format == SPF_Binary) 849 Writer.reset(new SampleProfileWriterRawBinary(OS)); 850 else if (Format == SPF_Ext_Binary) 851 Writer.reset(new SampleProfileWriterExtBinary(OS)); 852 else if (Format == SPF_Compact_Binary) 853 Writer.reset(new SampleProfileWriterCompactBinary(OS)); 854 else if (Format == SPF_Text) 855 Writer.reset(new SampleProfileWriterText(OS)); 856 else if (Format == SPF_GCC) 857 EC = sampleprof_error::unsupported_writing_format; 858 else 859 EC = sampleprof_error::unrecognized_format; 860 861 if (EC) 862 return EC; 863 864 Writer->Format = Format; 865 return std::move(Writer); 866 } 867 868 void SampleProfileWriter::computeSummary(const SampleProfileMap &ProfileMap) { 869 SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs); 870 Summary = Builder.computeSummaryForProfiles(ProfileMap); 871 } 872