1 //===- InstrProfWriter.cpp - Instrumented profiling writer ----------------===//
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 writing profiling data for clang's
10 // instrumentation based PGO and coverage.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ProfileData/InstrProfWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/IR/ProfileSummary.h"
18 #include "llvm/ProfileData/InstrProf.h"
19 #include "llvm/ProfileData/MemProf.h"
20 #include "llvm/ProfileData/ProfileCommon.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/EndianStream.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/OnDiskHashTable.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <cstdint>
28 #include <memory>
29 #include <string>
30 #include <tuple>
31 #include <utility>
32 #include <vector>
33 
34 using namespace llvm;
35 
36 // A struct to define how the data stream should be patched. For Indexed
37 // profiling, only uint64_t data type is needed.
38 struct PatchItem {
39   uint64_t Pos; // Where to patch.
40   uint64_t *D;  // Pointer to an array of source data.
41   int N;        // Number of elements in \c D array.
42 };
43 
44 namespace llvm {
45 
46 // A wrapper class to abstract writer stream with support of bytes
47 // back patching.
48 class ProfOStream {
49 public:
50   ProfOStream(raw_fd_ostream &FD)
51       : IsFDOStream(true), OS(FD), LE(FD, support::little) {}
52   ProfOStream(raw_string_ostream &STR)
53       : IsFDOStream(false), OS(STR), LE(STR, support::little) {}
54 
55   uint64_t tell() { return OS.tell(); }
56   void write(uint64_t V) { LE.write<uint64_t>(V); }
57 
58   // \c patch can only be called when all data is written and flushed.
59   // For raw_string_ostream, the patch is done on the target string
60   // directly and it won't be reflected in the stream's internal buffer.
61   void patch(PatchItem *P, int NItems) {
62     using namespace support;
63 
64     if (IsFDOStream) {
65       raw_fd_ostream &FDOStream = static_cast<raw_fd_ostream &>(OS);
66       const uint64_t LastPos = FDOStream.tell();
67       for (int K = 0; K < NItems; K++) {
68         FDOStream.seek(P[K].Pos);
69         for (int I = 0; I < P[K].N; I++)
70           write(P[K].D[I]);
71       }
72       // Reset the stream to the last position after patching so that users
73       // don't accidentally overwrite data. This makes it consistent with
74       // the string stream below which replaces the data directly.
75       FDOStream.seek(LastPos);
76     } else {
77       raw_string_ostream &SOStream = static_cast<raw_string_ostream &>(OS);
78       std::string &Data = SOStream.str(); // with flush
79       for (int K = 0; K < NItems; K++) {
80         for (int I = 0; I < P[K].N; I++) {
81           uint64_t Bytes = endian::byte_swap<uint64_t, little>(P[K].D[I]);
82           Data.replace(P[K].Pos + I * sizeof(uint64_t), sizeof(uint64_t),
83                        (const char *)&Bytes, sizeof(uint64_t));
84         }
85       }
86     }
87   }
88 
89   // If \c OS is an instance of \c raw_fd_ostream, this field will be
90   // true. Otherwise, \c OS will be an raw_string_ostream.
91   bool IsFDOStream;
92   raw_ostream &OS;
93   support::endian::Writer LE;
94 };
95 
96 class InstrProfRecordWriterTrait {
97 public:
98   using key_type = StringRef;
99   using key_type_ref = StringRef;
100 
101   using data_type = const InstrProfWriter::ProfilingData *const;
102   using data_type_ref = const InstrProfWriter::ProfilingData *const;
103 
104   using hash_value_type = uint64_t;
105   using offset_type = uint64_t;
106 
107   support::endianness ValueProfDataEndianness = support::little;
108   InstrProfSummaryBuilder *SummaryBuilder;
109   InstrProfSummaryBuilder *CSSummaryBuilder;
110 
111   InstrProfRecordWriterTrait() = default;
112 
113   static hash_value_type ComputeHash(key_type_ref K) {
114     return IndexedInstrProf::ComputeHash(K);
115   }
116 
117   static std::pair<offset_type, offset_type>
118   EmitKeyDataLength(raw_ostream &Out, key_type_ref K, data_type_ref V) {
119     using namespace support;
120 
121     endian::Writer LE(Out, little);
122 
123     offset_type N = K.size();
124     LE.write<offset_type>(N);
125 
126     offset_type M = 0;
127     for (const auto &ProfileData : *V) {
128       const InstrProfRecord &ProfRecord = ProfileData.second;
129       M += sizeof(uint64_t); // The function hash
130       M += sizeof(uint64_t); // The size of the Counts vector
131       M += ProfRecord.Counts.size() * sizeof(uint64_t);
132 
133       // Value data
134       M += ValueProfData::getSize(ProfileData.second);
135     }
136     LE.write<offset_type>(M);
137 
138     return std::make_pair(N, M);
139   }
140 
141   void EmitKey(raw_ostream &Out, key_type_ref K, offset_type N) {
142     Out.write(K.data(), N);
143   }
144 
145   void EmitData(raw_ostream &Out, key_type_ref, data_type_ref V, offset_type) {
146     using namespace support;
147 
148     endian::Writer LE(Out, little);
149     for (const auto &ProfileData : *V) {
150       const InstrProfRecord &ProfRecord = ProfileData.second;
151       if (NamedInstrProfRecord::hasCSFlagInHash(ProfileData.first))
152         CSSummaryBuilder->addRecord(ProfRecord);
153       else
154         SummaryBuilder->addRecord(ProfRecord);
155 
156       LE.write<uint64_t>(ProfileData.first); // Function hash
157       LE.write<uint64_t>(ProfRecord.Counts.size());
158       for (uint64_t I : ProfRecord.Counts)
159         LE.write<uint64_t>(I);
160 
161       // Write value data
162       std::unique_ptr<ValueProfData> VDataPtr =
163           ValueProfData::serializeFrom(ProfileData.second);
164       uint32_t S = VDataPtr->getSize();
165       VDataPtr->swapBytesFromHost(ValueProfDataEndianness);
166       Out.write((const char *)VDataPtr.get(), S);
167     }
168   }
169 };
170 
171 } // end namespace llvm
172 
173 InstrProfWriter::InstrProfWriter(bool Sparse)
174     : Sparse(Sparse), InfoObj(new InstrProfRecordWriterTrait()) {}
175 
176 InstrProfWriter::~InstrProfWriter() { delete InfoObj; }
177 
178 // Internal interface for testing purpose only.
179 void InstrProfWriter::setValueProfDataEndianness(
180     support::endianness Endianness) {
181   InfoObj->ValueProfDataEndianness = Endianness;
182 }
183 
184 void InstrProfWriter::setOutputSparse(bool Sparse) {
185   this->Sparse = Sparse;
186 }
187 
188 void InstrProfWriter::addRecord(NamedInstrProfRecord &&I, uint64_t Weight,
189                                 function_ref<void(Error)> Warn) {
190   auto Name = I.Name;
191   auto Hash = I.Hash;
192   addRecord(Name, Hash, std::move(I), Weight, Warn);
193 }
194 
195 void InstrProfWriter::overlapRecord(NamedInstrProfRecord &&Other,
196                                     OverlapStats &Overlap,
197                                     OverlapStats &FuncLevelOverlap,
198                                     const OverlapFuncFilters &FuncFilter) {
199   auto Name = Other.Name;
200   auto Hash = Other.Hash;
201   Other.accumulateCounts(FuncLevelOverlap.Test);
202   if (FunctionData.find(Name) == FunctionData.end()) {
203     Overlap.addOneUnique(FuncLevelOverlap.Test);
204     return;
205   }
206   if (FuncLevelOverlap.Test.CountSum < 1.0f) {
207     Overlap.Overlap.NumEntries += 1;
208     return;
209   }
210   auto &ProfileDataMap = FunctionData[Name];
211   bool NewFunc;
212   ProfilingData::iterator Where;
213   std::tie(Where, NewFunc) =
214       ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
215   if (NewFunc) {
216     Overlap.addOneMismatch(FuncLevelOverlap.Test);
217     return;
218   }
219   InstrProfRecord &Dest = Where->second;
220 
221   uint64_t ValueCutoff = FuncFilter.ValueCutoff;
222   if (!FuncFilter.NameFilter.empty() && Name.contains(FuncFilter.NameFilter))
223     ValueCutoff = 0;
224 
225   Dest.overlap(Other, Overlap, FuncLevelOverlap, ValueCutoff);
226 }
227 
228 void InstrProfWriter::addRecord(StringRef Name, uint64_t Hash,
229                                 InstrProfRecord &&I, uint64_t Weight,
230                                 function_ref<void(Error)> Warn) {
231   auto &ProfileDataMap = FunctionData[Name];
232 
233   bool NewFunc;
234   ProfilingData::iterator Where;
235   std::tie(Where, NewFunc) =
236       ProfileDataMap.insert(std::make_pair(Hash, InstrProfRecord()));
237   InstrProfRecord &Dest = Where->second;
238 
239   auto MapWarn = [&](instrprof_error E) {
240     Warn(make_error<InstrProfError>(E));
241   };
242 
243   if (NewFunc) {
244     // We've never seen a function with this name and hash, add it.
245     Dest = std::move(I);
246     if (Weight > 1)
247       Dest.scale(Weight, 1, MapWarn);
248   } else {
249     // We're updating a function we've seen before.
250     Dest.merge(I, Weight, MapWarn);
251   }
252 
253   Dest.sortValueData();
254 }
255 
256 void InstrProfWriter::addRecord(const Function::GUID Id,
257                                 const memprof::MemProfRecord &Record,
258                                 function_ref<void(Error)> Warn) {
259   auto Result = MemProfData.insert({Id, Record});
260   if (!Result.second) {
261     memprof::MemProfRecord &Existing = Result.first->second;
262     Existing.merge(Record);
263   }
264 }
265 
266 void InstrProfWriter::mergeRecordsFromWriter(InstrProfWriter &&IPW,
267                                              function_ref<void(Error)> Warn) {
268   for (auto &I : IPW.FunctionData)
269     for (auto &Func : I.getValue())
270       addRecord(I.getKey(), Func.first, std::move(Func.second), 1, Warn);
271 
272   for (auto &I : IPW.MemProfData) {
273     addRecord(I.first, I.second, Warn);
274   }
275 }
276 
277 bool InstrProfWriter::shouldEncodeData(const ProfilingData &PD) {
278   if (!Sparse)
279     return true;
280   for (const auto &Func : PD) {
281     const InstrProfRecord &IPR = Func.second;
282     if (llvm::any_of(IPR.Counts, [](uint64_t Count) { return Count > 0; }))
283       return true;
284   }
285   return false;
286 }
287 
288 static void setSummary(IndexedInstrProf::Summary *TheSummary,
289                        ProfileSummary &PS) {
290   using namespace IndexedInstrProf;
291 
292   const std::vector<ProfileSummaryEntry> &Res = PS.getDetailedSummary();
293   TheSummary->NumSummaryFields = Summary::NumKinds;
294   TheSummary->NumCutoffEntries = Res.size();
295   TheSummary->set(Summary::MaxFunctionCount, PS.getMaxFunctionCount());
296   TheSummary->set(Summary::MaxBlockCount, PS.getMaxCount());
297   TheSummary->set(Summary::MaxInternalBlockCount, PS.getMaxInternalCount());
298   TheSummary->set(Summary::TotalBlockCount, PS.getTotalCount());
299   TheSummary->set(Summary::TotalNumBlocks, PS.getNumCounts());
300   TheSummary->set(Summary::TotalNumFunctions, PS.getNumFunctions());
301   for (unsigned I = 0; I < Res.size(); I++)
302     TheSummary->setEntry(I, Res[I]);
303 }
304 
305 Error InstrProfWriter::writeImpl(ProfOStream &OS) {
306   using namespace IndexedInstrProf;
307 
308   OnDiskChainedHashTableGenerator<InstrProfRecordWriterTrait> Generator;
309 
310   InstrProfSummaryBuilder ISB(ProfileSummaryBuilder::DefaultCutoffs);
311   InfoObj->SummaryBuilder = &ISB;
312   InstrProfSummaryBuilder CSISB(ProfileSummaryBuilder::DefaultCutoffs);
313   InfoObj->CSSummaryBuilder = &CSISB;
314 
315   // Populate the hash table generator.
316   for (const auto &I : FunctionData)
317     if (shouldEncodeData(I.getValue()))
318       Generator.insert(I.getKey(), &I.getValue());
319 
320   // Write the header.
321   IndexedInstrProf::Header Header;
322   Header.Magic = IndexedInstrProf::Magic;
323   Header.Version = IndexedInstrProf::ProfVersion::CurrentVersion;
324   if (static_cast<bool>(ProfileKind & InstrProfKind::IRInstrumentation))
325     Header.Version |= VARIANT_MASK_IR_PROF;
326   if (static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive))
327     Header.Version |= VARIANT_MASK_CSIR_PROF;
328   if (static_cast<bool>(ProfileKind &
329                         InstrProfKind::FunctionEntryInstrumentation))
330     Header.Version |= VARIANT_MASK_INSTR_ENTRY;
331   if (static_cast<bool>(ProfileKind & InstrProfKind::SingleByteCoverage))
332     Header.Version |= VARIANT_MASK_BYTE_COVERAGE;
333   if (static_cast<bool>(ProfileKind & InstrProfKind::FunctionEntryOnly))
334     Header.Version |= VARIANT_MASK_FUNCTION_ENTRY_ONLY;
335   if (static_cast<bool>(ProfileKind & InstrProfKind::MemProf))
336     Header.Version |= VARIANT_MASK_MEMPROF;
337 
338   Header.Unused = 0;
339   Header.HashType = static_cast<uint64_t>(IndexedInstrProf::HashType);
340   Header.HashOffset = 0;
341   Header.MemProfOffset = 0;
342   int N = sizeof(IndexedInstrProf::Header) / sizeof(uint64_t);
343 
344   // Only write out all the fields except 'HashOffset' and 'MemProfOffset'. We
345   // need to remember the offset of these fields to allow back patching later.
346   for (int I = 0; I < N - 2; I++)
347     OS.write(reinterpret_cast<uint64_t *>(&Header)[I]);
348 
349   // Save the location of Header.HashOffset field in \c OS.
350   uint64_t HashTableStartFieldOffset = OS.tell();
351   // Reserve the space for HashOffset field.
352   OS.write(0);
353 
354   // Save the location of MemProf profile data. This is stored in two parts as
355   // the schema and as a separate on-disk chained hashtable.
356   uint64_t MemProfSectionOffset = OS.tell();
357   // Reserve space for the MemProf table field to be patched later if this
358   // profile contains memory profile information.
359   OS.write(0);
360 
361   // Reserve space to write profile summary data.
362   uint32_t NumEntries = ProfileSummaryBuilder::DefaultCutoffs.size();
363   uint32_t SummarySize = Summary::getSize(Summary::NumKinds, NumEntries);
364   // Remember the summary offset.
365   uint64_t SummaryOffset = OS.tell();
366   for (unsigned I = 0; I < SummarySize / sizeof(uint64_t); I++)
367     OS.write(0);
368   uint64_t CSSummaryOffset = 0;
369   uint64_t CSSummarySize = 0;
370   if (static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive)) {
371     CSSummaryOffset = OS.tell();
372     CSSummarySize = SummarySize / sizeof(uint64_t);
373     for (unsigned I = 0; I < CSSummarySize; I++)
374       OS.write(0);
375   }
376 
377   // Write the hash table.
378   uint64_t HashTableStart = Generator.Emit(OS.OS, *InfoObj);
379 
380   // Write the MemProf profile data if we have it. This includes a simple schema
381   // with the format described below followed by the hashtable:
382   // uint64_t Offset = MemProfGenerator.Emit
383   // uint64_t Num schema entries
384   // uint64_t Schema entry 0
385   // uint64_t Schema entry 1
386   // ....
387   // uint64_t Schema entry N - 1
388   // OnDiskChainedHashTable MemProfFunctionData
389   uint64_t MemProfSectionStart = 0;
390   if (static_cast<bool>(ProfileKind & InstrProfKind::MemProf)) {
391     MemProfSectionStart = OS.tell();
392     OS.write(0ULL); // Reserve space for the offset.
393 
394     auto Schema = memprof::PortableMemInfoBlock::getSchema();
395     OS.write(static_cast<uint64_t>(Schema.size()));
396     for (const auto Id : Schema) {
397       OS.write(static_cast<uint64_t>(Id));
398     }
399 
400     auto MemProfWriter = std::make_unique<memprof::MemProfRecordWriterTrait>();
401     MemProfWriter->Schema = &Schema;
402     OnDiskChainedHashTableGenerator<memprof::MemProfRecordWriterTrait>
403         MemProfGenerator;
404     for (auto &I : MemProfData) {
405       // Insert the key (func hash) and value (memprof record).
406       MemProfGenerator.insert(I.first, I.second);
407     }
408 
409     uint64_t TableOffset = MemProfGenerator.Emit(OS.OS, *MemProfWriter);
410     PatchItem PatchItems[] = {
411         {MemProfSectionStart, &TableOffset, 1},
412     };
413     OS.patch(PatchItems, 1);
414   }
415 
416   // Allocate space for data to be serialized out.
417   std::unique_ptr<IndexedInstrProf::Summary> TheSummary =
418       IndexedInstrProf::allocSummary(SummarySize);
419   // Compute the Summary and copy the data to the data
420   // structure to be serialized out (to disk or buffer).
421   std::unique_ptr<ProfileSummary> PS = ISB.getSummary();
422   setSummary(TheSummary.get(), *PS);
423   InfoObj->SummaryBuilder = nullptr;
424 
425   // For Context Sensitive summary.
426   std::unique_ptr<IndexedInstrProf::Summary> TheCSSummary = nullptr;
427   if (static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive)) {
428     TheCSSummary = IndexedInstrProf::allocSummary(SummarySize);
429     std::unique_ptr<ProfileSummary> CSPS = CSISB.getSummary();
430     setSummary(TheCSSummary.get(), *CSPS);
431   }
432   InfoObj->CSSummaryBuilder = nullptr;
433 
434   // Now do the final patch:
435   PatchItem PatchItems[] = {
436       // Patch the Header.HashOffset field.
437       {HashTableStartFieldOffset, &HashTableStart, 1},
438       // Patch the Header.MemProfOffset (=0 for profiles without MemProf data).
439       {MemProfSectionOffset, &MemProfSectionStart, 1},
440       // Patch the summary data.
441       {SummaryOffset, reinterpret_cast<uint64_t *>(TheSummary.get()),
442        (int)(SummarySize / sizeof(uint64_t))},
443       {CSSummaryOffset, reinterpret_cast<uint64_t *>(TheCSSummary.get()),
444        (int)CSSummarySize}};
445 
446   OS.patch(PatchItems, sizeof(PatchItems) / sizeof(*PatchItems));
447 
448   for (const auto &I : FunctionData)
449     for (const auto &F : I.getValue())
450       if (Error E = validateRecord(F.second))
451         return E;
452 
453   return Error::success();
454 }
455 
456 Error InstrProfWriter::write(raw_fd_ostream &OS) {
457   // Write the hash table.
458   ProfOStream POS(OS);
459   return writeImpl(POS);
460 }
461 
462 std::unique_ptr<MemoryBuffer> InstrProfWriter::writeBuffer() {
463   std::string Data;
464   raw_string_ostream OS(Data);
465   ProfOStream POS(OS);
466   // Write the hash table.
467   if (Error E = writeImpl(POS))
468     return nullptr;
469   // Return this in an aligned memory buffer.
470   return MemoryBuffer::getMemBufferCopy(Data);
471 }
472 
473 static const char *ValueProfKindStr[] = {
474 #define VALUE_PROF_KIND(Enumerator, Value, Descr) #Enumerator,
475 #include "llvm/ProfileData/InstrProfData.inc"
476 };
477 
478 Error InstrProfWriter::validateRecord(const InstrProfRecord &Func) {
479   for (uint32_t VK = 0; VK <= IPVK_Last; VK++) {
480     uint32_t NS = Func.getNumValueSites(VK);
481     if (!NS)
482       continue;
483     for (uint32_t S = 0; S < NS; S++) {
484       uint32_t ND = Func.getNumValueDataForSite(VK, S);
485       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
486       bool WasZero = false;
487       for (uint32_t I = 0; I < ND; I++)
488         if ((VK != IPVK_IndirectCallTarget) && (VD[I].Value == 0)) {
489           if (WasZero)
490             return make_error<InstrProfError>(instrprof_error::invalid_prof);
491           WasZero = true;
492         }
493     }
494   }
495 
496   return Error::success();
497 }
498 
499 void InstrProfWriter::writeRecordInText(StringRef Name, uint64_t Hash,
500                                         const InstrProfRecord &Func,
501                                         InstrProfSymtab &Symtab,
502                                         raw_fd_ostream &OS) {
503   OS << Name << "\n";
504   OS << "# Func Hash:\n" << Hash << "\n";
505   OS << "# Num Counters:\n" << Func.Counts.size() << "\n";
506   OS << "# Counter Values:\n";
507   for (uint64_t Count : Func.Counts)
508     OS << Count << "\n";
509 
510   uint32_t NumValueKinds = Func.getNumValueKinds();
511   if (!NumValueKinds) {
512     OS << "\n";
513     return;
514   }
515 
516   OS << "# Num Value Kinds:\n" << Func.getNumValueKinds() << "\n";
517   for (uint32_t VK = 0; VK < IPVK_Last + 1; VK++) {
518     uint32_t NS = Func.getNumValueSites(VK);
519     if (!NS)
520       continue;
521     OS << "# ValueKind = " << ValueProfKindStr[VK] << ":\n" << VK << "\n";
522     OS << "# NumValueSites:\n" << NS << "\n";
523     for (uint32_t S = 0; S < NS; S++) {
524       uint32_t ND = Func.getNumValueDataForSite(VK, S);
525       OS << ND << "\n";
526       std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, S);
527       for (uint32_t I = 0; I < ND; I++) {
528         if (VK == IPVK_IndirectCallTarget)
529           OS << Symtab.getFuncNameOrExternalSymbol(VD[I].Value) << ":"
530              << VD[I].Count << "\n";
531         else
532           OS << VD[I].Value << ":" << VD[I].Count << "\n";
533       }
534     }
535   }
536 
537   OS << "\n";
538 }
539 
540 Error InstrProfWriter::writeText(raw_fd_ostream &OS) {
541   // Check CS first since it implies an IR level profile.
542   if (static_cast<bool>(ProfileKind & InstrProfKind::ContextSensitive))
543     OS << "# CSIR level Instrumentation Flag\n:csir\n";
544   else if (static_cast<bool>(ProfileKind & InstrProfKind::IRInstrumentation))
545     OS << "# IR level Instrumentation Flag\n:ir\n";
546 
547   if (static_cast<bool>(ProfileKind &
548                         InstrProfKind::FunctionEntryInstrumentation))
549     OS << "# Always instrument the function entry block\n:entry_first\n";
550   InstrProfSymtab Symtab;
551 
552   using FuncPair = detail::DenseMapPair<uint64_t, InstrProfRecord>;
553   using RecordType = std::pair<StringRef, FuncPair>;
554   SmallVector<RecordType, 4> OrderedFuncData;
555 
556   for (const auto &I : FunctionData) {
557     if (shouldEncodeData(I.getValue())) {
558       if (Error E = Symtab.addFuncName(I.getKey()))
559         return E;
560       for (const auto &Func : I.getValue())
561         OrderedFuncData.push_back(std::make_pair(I.getKey(), Func));
562     }
563   }
564 
565   llvm::sort(OrderedFuncData, [](const RecordType &A, const RecordType &B) {
566     return std::tie(A.first, A.second.first) <
567            std::tie(B.first, B.second.first);
568   });
569 
570   for (const auto &record : OrderedFuncData) {
571     const StringRef &Name = record.first;
572     const FuncPair &Func = record.second;
573     writeRecordInText(Name, Func.first, Func.second, Symtab, OS);
574   }
575 
576   for (const auto &record : OrderedFuncData) {
577     const FuncPair &Func = record.second;
578     if (Error E = validateRecord(Func.second))
579       return E;
580   }
581 
582   return Error::success();
583 }
584