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/ProfileData/ProfileCommon.h"
23 #include "llvm/ProfileData/SampleProf.h"
24 #include "llvm/Support/Compression.h"
25 #include "llvm/Support/Endian.h"
26 #include "llvm/Support/EndianStream.h"
27 #include "llvm/Support/ErrorOr.h"
28 #include "llvm/Support/FileSystem.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/MD5.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cstdint>
34 #include <memory>
35 #include <set>
36 #include <system_error>
37 #include <utility>
38 #include <vector>
39 
40 using namespace llvm;
41 using namespace sampleprof;
42 
43 std::error_code SampleProfileWriter::writeFuncProfiles(
44     const StringMap<FunctionSamples> &ProfileMap) {
45   // Sort the ProfileMap by total samples.
46   typedef std::pair<StringRef, const FunctionSamples *> NameFunctionSamples;
47   std::vector<NameFunctionSamples> V;
48   for (const auto &I : ProfileMap)
49     V.push_back(std::make_pair(I.getKey(), &I.second));
50 
51   llvm::stable_sort(
52       V, [](const NameFunctionSamples &A, const NameFunctionSamples &B) {
53         if (A.second->getTotalSamples() == B.second->getTotalSamples())
54           return A.first > B.first;
55         return A.second->getTotalSamples() > B.second->getTotalSamples();
56       });
57 
58   for (const auto &I : V) {
59     if (std::error_code EC = writeSample(*I.second))
60       return EC;
61   }
62   return sampleprof_error::success;
63 }
64 
65 std::error_code
66 SampleProfileWriter::write(const StringMap<FunctionSamples> &ProfileMap) {
67   if (std::error_code EC = writeHeader(ProfileMap))
68     return EC;
69 
70   if (std::error_code EC = writeFuncProfiles(ProfileMap))
71     return EC;
72 
73   return sampleprof_error::success;
74 }
75 
76 SecHdrTableEntry &
77 SampleProfileWriterExtBinaryBase::getEntryInLayout(SecType Type) {
78   auto SecIt = std::find_if(
79       SectionHdrLayout.begin(), SectionHdrLayout.end(),
80       [=](const auto &Entry) -> bool { return Entry.Type == Type; });
81   return *SecIt;
82 }
83 
84 /// Return the current position and prepare to use it as the start
85 /// position of a section.
86 uint64_t SampleProfileWriterExtBinaryBase::markSectionStart(SecType Type) {
87   uint64_t SectionStart = OutputStream->tell();
88   auto &Entry = getEntryInLayout(Type);
89   // Use LocalBuf as a temporary output for writting data.
90   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress))
91     LocalBufStream.swap(OutputStream);
92   return SectionStart;
93 }
94 
95 std::error_code SampleProfileWriterExtBinaryBase::compressAndOutput() {
96   if (!llvm::zlib::isAvailable())
97     return sampleprof_error::zlib_unavailable;
98   std::string &UncompressedStrings =
99       static_cast<raw_string_ostream *>(LocalBufStream.get())->str();
100   if (UncompressedStrings.size() == 0)
101     return sampleprof_error::success;
102   auto &OS = *OutputStream;
103   SmallString<128> CompressedStrings;
104   llvm::Error E = zlib::compress(UncompressedStrings, CompressedStrings,
105                                  zlib::BestSizeCompression);
106   if (E)
107     return sampleprof_error::compress_failed;
108   encodeULEB128(UncompressedStrings.size(), OS);
109   encodeULEB128(CompressedStrings.size(), OS);
110   OS << CompressedStrings.str();
111   UncompressedStrings.clear();
112   return sampleprof_error::success;
113 }
114 
115 /// Add a new section into section header table.
116 std::error_code
117 SampleProfileWriterExtBinaryBase::addNewSection(SecType Type,
118                                                 uint64_t SectionStart) {
119   auto Entry = getEntryInLayout(Type);
120   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress)) {
121     LocalBufStream.swap(OutputStream);
122     if (std::error_code EC = compressAndOutput())
123       return EC;
124   }
125   SecHdrTable.push_back({Type, Entry.Flags, SectionStart - FileStart,
126                          OutputStream->tell() - SectionStart});
127   return sampleprof_error::success;
128 }
129 
130 std::error_code SampleProfileWriterExtBinaryBase::write(
131     const StringMap<FunctionSamples> &ProfileMap) {
132   if (std::error_code EC = writeHeader(ProfileMap))
133     return EC;
134 
135   std::string LocalBuf;
136   LocalBufStream = std::make_unique<raw_string_ostream>(LocalBuf);
137   if (std::error_code EC = writeSections(ProfileMap))
138     return EC;
139 
140   if (std::error_code EC = writeSecHdrTable())
141     return EC;
142 
143   return sampleprof_error::success;
144 }
145 
146 std::error_code
147 SampleProfileWriterExtBinaryBase::writeSample(const FunctionSamples &S) {
148   uint64_t Offset = OutputStream->tell();
149   StringRef Name = S.getName();
150   FuncOffsetTable[Name] = Offset - SecLBRProfileStart;
151   encodeULEB128(S.getHeadSamples(), *OutputStream);
152   return writeBody(S);
153 }
154 
155 std::error_code SampleProfileWriterExtBinaryBase::writeFuncOffsetTable() {
156   auto &OS = *OutputStream;
157 
158   // Write out the table size.
159   encodeULEB128(FuncOffsetTable.size(), OS);
160 
161   // Write out FuncOffsetTable.
162   for (auto entry : FuncOffsetTable) {
163     writeNameIdx(entry.first);
164     encodeULEB128(entry.second, OS);
165   }
166   return sampleprof_error::success;
167 }
168 
169 std::error_code SampleProfileWriterExtBinaryBase::writeNameTable() {
170   if (!UseMD5)
171     return SampleProfileWriterBinary::writeNameTable();
172 
173   auto &OS = *OutputStream;
174   std::set<StringRef> V;
175   stablizeNameTable(V);
176 
177   // Write out the name table.
178   encodeULEB128(NameTable.size(), OS);
179   for (auto N : V) {
180     encodeULEB128(MD5Hash(N), OS);
181   }
182   return sampleprof_error::success;
183 }
184 
185 std::error_code SampleProfileWriterExtBinaryBase::writeNameTableSection(
186     const StringMap<FunctionSamples> &ProfileMap) {
187   for (const auto &I : ProfileMap) {
188     addName(I.first());
189     addNames(I.second);
190   }
191   if (auto EC = writeNameTable())
192     return EC;
193   return sampleprof_error::success;
194 }
195 
196 std::error_code
197 SampleProfileWriterExtBinaryBase::writeProfileSymbolListSection() {
198   if (ProfSymList && ProfSymList->size() > 0)
199     if (std::error_code EC = ProfSymList->write(*OutputStream))
200       return EC;
201 
202   return sampleprof_error::success;
203 }
204 
205 std::error_code SampleProfileWriterExtBinaryBase::writeOneSection(
206     SecType Type, const StringMap<FunctionSamples> &ProfileMap) {
207   // The setting of SecFlagCompress should happen before markSectionStart.
208   if (Type == SecProfileSymbolList && ProfSymList && ProfSymList->toCompress())
209     setToCompressSection(SecProfileSymbolList);
210 
211   uint64_t SectionStart = markSectionStart(Type);
212   switch (Type) {
213   case SecProfSummary:
214     computeSummary(ProfileMap);
215     if (auto EC = writeSummary())
216       return EC;
217     break;
218   case SecNameTable:
219     if (auto EC = writeNameTableSection(ProfileMap))
220       return EC;
221     break;
222   case SecLBRProfile:
223     SecLBRProfileStart = OutputStream->tell();
224     if (std::error_code EC = writeFuncProfiles(ProfileMap))
225       return EC;
226     break;
227   case SecFuncOffsetTable:
228     if (auto EC = writeFuncOffsetTable())
229       return EC;
230     break;
231   case SecProfileSymbolList:
232     if (auto EC = writeProfileSymbolListSection())
233       return EC;
234     break;
235   default:
236     if (auto EC = writeCustomSection(Type))
237       return EC;
238     break;
239   }
240   if (std::error_code EC = addNewSection(Type, SectionStart))
241     return EC;
242   return sampleprof_error::success;
243 }
244 
245 std::error_code SampleProfileWriterExtBinary::writeSections(
246     const StringMap<FunctionSamples> &ProfileMap) {
247   if (auto EC = writeOneSection(SecProfSummary, ProfileMap))
248     return EC;
249   if (auto EC = writeOneSection(SecNameTable, ProfileMap))
250     return EC;
251   if (auto EC = writeOneSection(SecLBRProfile, ProfileMap))
252     return EC;
253   if (auto EC = writeOneSection(SecProfileSymbolList, ProfileMap))
254     return EC;
255   if (auto EC = writeOneSection(SecFuncOffsetTable, ProfileMap))
256     return EC;
257   return sampleprof_error::success;
258 }
259 
260 std::error_code SampleProfileWriterCompactBinary::write(
261     const StringMap<FunctionSamples> &ProfileMap) {
262   if (std::error_code EC = SampleProfileWriter::write(ProfileMap))
263     return EC;
264   if (std::error_code EC = writeFuncOffsetTable())
265     return EC;
266   return sampleprof_error::success;
267 }
268 
269 /// Write samples to a text file.
270 ///
271 /// Note: it may be tempting to implement this in terms of
272 /// FunctionSamples::print().  Please don't.  The dump functionality is intended
273 /// for debugging and has no specified form.
274 ///
275 /// The format used here is more structured and deliberate because
276 /// it needs to be parsed by the SampleProfileReaderText class.
277 std::error_code SampleProfileWriterText::writeSample(const FunctionSamples &S) {
278   auto &OS = *OutputStream;
279   if (FunctionSamples::ProfileIsCS)
280     OS << "[" << S.getNameWithContext() << "]:" << S.getTotalSamples();
281   else
282     OS << S.getName() << ":" << S.getTotalSamples();
283   if (Indent == 0)
284     OS << ":" << S.getHeadSamples();
285   OS << "\n";
286 
287   SampleSorter<LineLocation, SampleRecord> SortedSamples(S.getBodySamples());
288   for (const auto &I : SortedSamples.get()) {
289     LineLocation Loc = I->first;
290     const SampleRecord &Sample = I->second;
291     OS.indent(Indent + 1);
292     if (Loc.Discriminator == 0)
293       OS << Loc.LineOffset << ": ";
294     else
295       OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
296 
297     OS << Sample.getSamples();
298 
299     for (const auto &J : Sample.getSortedCallTargets())
300       OS << " " << J.first << ":" << J.second;
301     OS << "\n";
302   }
303 
304   SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples(
305       S.getCallsiteSamples());
306   Indent += 1;
307   for (const auto &I : SortedCallsiteSamples.get())
308     for (const auto &FS : I->second) {
309       LineLocation Loc = I->first;
310       const FunctionSamples &CalleeSamples = FS.second;
311       OS.indent(Indent);
312       if (Loc.Discriminator == 0)
313         OS << Loc.LineOffset << ": ";
314       else
315         OS << Loc.LineOffset << "." << Loc.Discriminator << ": ";
316       if (std::error_code EC = writeSample(CalleeSamples))
317         return EC;
318     }
319   Indent -= 1;
320 
321   return sampleprof_error::success;
322 }
323 
324 std::error_code SampleProfileWriterBinary::writeNameIdx(StringRef FName) {
325   const auto &ret = NameTable.find(FName);
326   if (ret == NameTable.end())
327     return sampleprof_error::truncated_name_table;
328   encodeULEB128(ret->second, *OutputStream);
329   return sampleprof_error::success;
330 }
331 
332 void SampleProfileWriterBinary::addName(StringRef FName) {
333   NameTable.insert(std::make_pair(FName, 0));
334 }
335 
336 void SampleProfileWriterBinary::addNames(const FunctionSamples &S) {
337   // Add all the names in indirect call targets.
338   for (const auto &I : S.getBodySamples()) {
339     const SampleRecord &Sample = I.second;
340     for (const auto &J : Sample.getCallTargets())
341       addName(J.first());
342   }
343 
344   // Recursively add all the names for inlined callsites.
345   for (const auto &J : S.getCallsiteSamples())
346     for (const auto &FS : J.second) {
347       const FunctionSamples &CalleeSamples = FS.second;
348       addName(CalleeSamples.getName());
349       addNames(CalleeSamples);
350     }
351 }
352 
353 void SampleProfileWriterBinary::stablizeNameTable(std::set<StringRef> &V) {
354   // Sort the names to make NameTable deterministic.
355   for (const auto &I : NameTable)
356     V.insert(I.first);
357   int i = 0;
358   for (const StringRef &N : V)
359     NameTable[N] = i++;
360 }
361 
362 std::error_code SampleProfileWriterBinary::writeNameTable() {
363   auto &OS = *OutputStream;
364   std::set<StringRef> V;
365   stablizeNameTable(V);
366 
367   // Write out the name table.
368   encodeULEB128(NameTable.size(), OS);
369   for (auto N : V) {
370     OS << N;
371     encodeULEB128(0, OS);
372   }
373   return sampleprof_error::success;
374 }
375 
376 std::error_code SampleProfileWriterCompactBinary::writeFuncOffsetTable() {
377   auto &OS = *OutputStream;
378 
379   // Fill the slot remembered by TableOffset with the offset of FuncOffsetTable.
380   auto &OFS = static_cast<raw_fd_ostream &>(OS);
381   uint64_t FuncOffsetTableStart = OS.tell();
382   if (OFS.seek(TableOffset) == (uint64_t)-1)
383     return sampleprof_error::ostream_seek_unsupported;
384   support::endian::Writer Writer(*OutputStream, support::little);
385   Writer.write(FuncOffsetTableStart);
386   if (OFS.seek(FuncOffsetTableStart) == (uint64_t)-1)
387     return sampleprof_error::ostream_seek_unsupported;
388 
389   // Write out the table size.
390   encodeULEB128(FuncOffsetTable.size(), OS);
391 
392   // Write out FuncOffsetTable.
393   for (auto entry : FuncOffsetTable) {
394     writeNameIdx(entry.first);
395     encodeULEB128(entry.second, OS);
396   }
397   return sampleprof_error::success;
398 }
399 
400 std::error_code SampleProfileWriterCompactBinary::writeNameTable() {
401   auto &OS = *OutputStream;
402   std::set<StringRef> V;
403   stablizeNameTable(V);
404 
405   // Write out the name table.
406   encodeULEB128(NameTable.size(), OS);
407   for (auto N : V) {
408     encodeULEB128(MD5Hash(N), OS);
409   }
410   return sampleprof_error::success;
411 }
412 
413 std::error_code
414 SampleProfileWriterBinary::writeMagicIdent(SampleProfileFormat Format) {
415   auto &OS = *OutputStream;
416   // Write file magic identifier.
417   encodeULEB128(SPMagic(Format), OS);
418   encodeULEB128(SPVersion(), OS);
419   return sampleprof_error::success;
420 }
421 
422 std::error_code SampleProfileWriterBinary::writeHeader(
423     const StringMap<FunctionSamples> &ProfileMap) {
424   writeMagicIdent(Format);
425 
426   computeSummary(ProfileMap);
427   if (auto EC = writeSummary())
428     return EC;
429 
430   // Generate the name table for all the functions referenced in the profile.
431   for (const auto &I : ProfileMap) {
432     addName(I.first());
433     addNames(I.second);
434   }
435 
436   writeNameTable();
437   return sampleprof_error::success;
438 }
439 
440 void SampleProfileWriterExtBinaryBase::setToCompressAllSections() {
441   for (auto &Entry : SectionHdrLayout)
442     addSecFlag(Entry, SecCommonFlags::SecFlagCompress);
443 }
444 
445 void SampleProfileWriterExtBinaryBase::setToCompressSection(SecType Type) {
446   addSectionFlag(Type, SecCommonFlags::SecFlagCompress);
447 }
448 
449 void SampleProfileWriterExtBinaryBase::allocSecHdrTable() {
450   support::endian::Writer Writer(*OutputStream, support::little);
451 
452   Writer.write(static_cast<uint64_t>(SectionHdrLayout.size()));
453   SecHdrTableOffset = OutputStream->tell();
454   for (uint32_t i = 0; i < SectionHdrLayout.size(); i++) {
455     Writer.write(static_cast<uint64_t>(-1));
456     Writer.write(static_cast<uint64_t>(-1));
457     Writer.write(static_cast<uint64_t>(-1));
458     Writer.write(static_cast<uint64_t>(-1));
459   }
460 }
461 
462 std::error_code SampleProfileWriterExtBinaryBase::writeSecHdrTable() {
463   auto &OFS = static_cast<raw_fd_ostream &>(*OutputStream);
464   uint64_t Saved = OutputStream->tell();
465 
466   // Set OutputStream to the location saved in SecHdrTableOffset.
467   if (OFS.seek(SecHdrTableOffset) == (uint64_t)-1)
468     return sampleprof_error::ostream_seek_unsupported;
469   support::endian::Writer Writer(*OutputStream, support::little);
470 
471   DenseMap<uint32_t, uint32_t> IndexMap;
472   for (uint32_t i = 0; i < SecHdrTable.size(); i++) {
473     IndexMap.insert({static_cast<uint32_t>(SecHdrTable[i].Type), i});
474   }
475 
476   // Write the section header table in the order specified in
477   // SectionHdrLayout. That is the sections order Reader will see.
478   // Note that the sections order in which Reader expects to read
479   // may be different from the order in which Writer is able to
480   // write, so we need to adjust the order in SecHdrTable to be
481   // consistent with SectionHdrLayout when we write SecHdrTable
482   // to the memory.
483   for (uint32_t i = 0; i < SectionHdrLayout.size(); i++) {
484     uint32_t idx = IndexMap[static_cast<uint32_t>(SectionHdrLayout[i].Type)];
485     Writer.write(static_cast<uint64_t>(SecHdrTable[idx].Type));
486     Writer.write(static_cast<uint64_t>(SecHdrTable[idx].Flags));
487     Writer.write(static_cast<uint64_t>(SecHdrTable[idx].Offset));
488     Writer.write(static_cast<uint64_t>(SecHdrTable[idx].Size));
489   }
490 
491   // Reset OutputStream.
492   if (OFS.seek(Saved) == (uint64_t)-1)
493     return sampleprof_error::ostream_seek_unsupported;
494 
495   return sampleprof_error::success;
496 }
497 
498 std::error_code SampleProfileWriterExtBinaryBase::writeHeader(
499     const StringMap<FunctionSamples> &ProfileMap) {
500   auto &OS = *OutputStream;
501   FileStart = OS.tell();
502   writeMagicIdent(Format);
503 
504   allocSecHdrTable();
505   return sampleprof_error::success;
506 }
507 
508 std::error_code SampleProfileWriterCompactBinary::writeHeader(
509     const StringMap<FunctionSamples> &ProfileMap) {
510   support::endian::Writer Writer(*OutputStream, support::little);
511   if (auto EC = SampleProfileWriterBinary::writeHeader(ProfileMap))
512     return EC;
513 
514   // Reserve a slot for the offset of function offset table. The slot will
515   // be populated with the offset of FuncOffsetTable later.
516   TableOffset = OutputStream->tell();
517   Writer.write(static_cast<uint64_t>(-2));
518   return sampleprof_error::success;
519 }
520 
521 std::error_code SampleProfileWriterBinary::writeSummary() {
522   auto &OS = *OutputStream;
523   encodeULEB128(Summary->getTotalCount(), OS);
524   encodeULEB128(Summary->getMaxCount(), OS);
525   encodeULEB128(Summary->getMaxFunctionCount(), OS);
526   encodeULEB128(Summary->getNumCounts(), OS);
527   encodeULEB128(Summary->getNumFunctions(), OS);
528   std::vector<ProfileSummaryEntry> &Entries = Summary->getDetailedSummary();
529   encodeULEB128(Entries.size(), OS);
530   for (auto Entry : Entries) {
531     encodeULEB128(Entry.Cutoff, OS);
532     encodeULEB128(Entry.MinCount, OS);
533     encodeULEB128(Entry.NumCounts, OS);
534   }
535   return sampleprof_error::success;
536 }
537 std::error_code SampleProfileWriterBinary::writeBody(const FunctionSamples &S) {
538   auto &OS = *OutputStream;
539 
540   if (std::error_code EC = writeNameIdx(S.getName()))
541     return EC;
542 
543   encodeULEB128(S.getTotalSamples(), OS);
544 
545   // Emit all the body samples.
546   encodeULEB128(S.getBodySamples().size(), OS);
547   for (const auto &I : S.getBodySamples()) {
548     LineLocation Loc = I.first;
549     const SampleRecord &Sample = I.second;
550     encodeULEB128(Loc.LineOffset, OS);
551     encodeULEB128(Loc.Discriminator, OS);
552     encodeULEB128(Sample.getSamples(), OS);
553     encodeULEB128(Sample.getCallTargets().size(), OS);
554     for (const auto &J : Sample.getSortedCallTargets()) {
555       StringRef Callee = J.first;
556       uint64_t CalleeSamples = J.second;
557       if (std::error_code EC = writeNameIdx(Callee))
558         return EC;
559       encodeULEB128(CalleeSamples, OS);
560     }
561   }
562 
563   // Recursively emit all the callsite samples.
564   uint64_t NumCallsites = 0;
565   for (const auto &J : S.getCallsiteSamples())
566     NumCallsites += J.second.size();
567   encodeULEB128(NumCallsites, OS);
568   for (const auto &J : S.getCallsiteSamples())
569     for (const auto &FS : J.second) {
570       LineLocation Loc = J.first;
571       const FunctionSamples &CalleeSamples = FS.second;
572       encodeULEB128(Loc.LineOffset, OS);
573       encodeULEB128(Loc.Discriminator, OS);
574       if (std::error_code EC = writeBody(CalleeSamples))
575         return EC;
576     }
577 
578   return sampleprof_error::success;
579 }
580 
581 /// Write samples of a top-level function to a binary file.
582 ///
583 /// \returns true if the samples were written successfully, false otherwise.
584 std::error_code
585 SampleProfileWriterBinary::writeSample(const FunctionSamples &S) {
586   encodeULEB128(S.getHeadSamples(), *OutputStream);
587   return writeBody(S);
588 }
589 
590 std::error_code
591 SampleProfileWriterCompactBinary::writeSample(const FunctionSamples &S) {
592   uint64_t Offset = OutputStream->tell();
593   StringRef Name = S.getName();
594   FuncOffsetTable[Name] = Offset;
595   encodeULEB128(S.getHeadSamples(), *OutputStream);
596   return writeBody(S);
597 }
598 
599 /// Create a sample profile file writer based on the specified format.
600 ///
601 /// \param Filename The file to create.
602 ///
603 /// \param Format Encoding format for the profile file.
604 ///
605 /// \returns an error code indicating the status of the created writer.
606 ErrorOr<std::unique_ptr<SampleProfileWriter>>
607 SampleProfileWriter::create(StringRef Filename, SampleProfileFormat Format) {
608   std::error_code EC;
609   std::unique_ptr<raw_ostream> OS;
610   if (Format == SPF_Binary || Format == SPF_Ext_Binary ||
611       Format == SPF_Compact_Binary)
612     OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_None));
613   else
614     OS.reset(new raw_fd_ostream(Filename, EC, sys::fs::OF_Text));
615   if (EC)
616     return EC;
617 
618   return create(OS, Format);
619 }
620 
621 /// Create a sample profile stream writer based on the specified format.
622 ///
623 /// \param OS The output stream to store the profile data to.
624 ///
625 /// \param Format Encoding format for the profile file.
626 ///
627 /// \returns an error code indicating the status of the created writer.
628 ErrorOr<std::unique_ptr<SampleProfileWriter>>
629 SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
630                             SampleProfileFormat Format) {
631   std::error_code EC;
632   std::unique_ptr<SampleProfileWriter> Writer;
633 
634   if (Format == SPF_Binary)
635     Writer.reset(new SampleProfileWriterRawBinary(OS));
636   else if (Format == SPF_Ext_Binary)
637     Writer.reset(new SampleProfileWriterExtBinary(OS));
638   else if (Format == SPF_Compact_Binary)
639     Writer.reset(new SampleProfileWriterCompactBinary(OS));
640   else if (Format == SPF_Text)
641     Writer.reset(new SampleProfileWriterText(OS));
642   else if (Format == SPF_GCC)
643     EC = sampleprof_error::unsupported_writing_format;
644   else
645     EC = sampleprof_error::unrecognized_format;
646 
647   if (EC)
648     return EC;
649 
650   Writer->Format = Format;
651   return std::move(Writer);
652 }
653 
654 void SampleProfileWriter::computeSummary(
655     const StringMap<FunctionSamples> &ProfileMap) {
656   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
657   for (const auto &I : ProfileMap) {
658     const FunctionSamples &Profile = I.second;
659     Builder.addRecord(Profile);
660   }
661   Summary = Builder.getSummary();
662 }
663