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