xref: /src/contrib/llvm-project/llvm/lib/ProfileData/SampleProfReader.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
167c32a98SDimitry Andric //===- SampleProfReader.cpp - Read LLVM sample profile data ---------------===//
267c32a98SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
667c32a98SDimitry Andric //
767c32a98SDimitry Andric //===----------------------------------------------------------------------===//
867c32a98SDimitry Andric //
967c32a98SDimitry Andric // This file implements the class that reads LLVM sample profiles. It
10dd58ef01SDimitry Andric // supports three file formats: text, binary and gcov.
1167c32a98SDimitry Andric //
12dd58ef01SDimitry Andric // The textual representation is useful for debugging and testing purposes. The
13dd58ef01SDimitry Andric // binary representation is more compact, resulting in smaller file sizes.
1467c32a98SDimitry Andric //
15dd58ef01SDimitry Andric // The gcov encoding is the one generated by GCC's AutoFDO profile creation
16dd58ef01SDimitry Andric // tool (https://github.com/google/autofdo)
1767c32a98SDimitry Andric //
18dd58ef01SDimitry Andric // All three encodings can be used interchangeably as an input sample profile.
1967c32a98SDimitry Andric //
2067c32a98SDimitry Andric //===----------------------------------------------------------------------===//
2167c32a98SDimitry Andric 
2267c32a98SDimitry Andric #include "llvm/ProfileData/SampleProfReader.h"
23dd58ef01SDimitry Andric #include "llvm/ADT/DenseMap.h"
2401095a5dSDimitry Andric #include "llvm/ADT/STLExtras.h"
2571d5a254SDimitry Andric #include "llvm/ADT/StringRef.h"
26145449b1SDimitry Andric #include "llvm/IR/Module.h"
2771d5a254SDimitry Andric #include "llvm/IR/ProfileSummary.h"
2871d5a254SDimitry Andric #include "llvm/ProfileData/ProfileCommon.h"
2971d5a254SDimitry Andric #include "llvm/ProfileData/SampleProf.h"
30344a3780SDimitry Andric #include "llvm/Support/CommandLine.h"
311d5ae102SDimitry Andric #include "llvm/Support/Compression.h"
3267c32a98SDimitry Andric #include "llvm/Support/ErrorOr.h"
33e3b55780SDimitry Andric #include "llvm/Support/JSON.h"
3467c32a98SDimitry Andric #include "llvm/Support/LEB128.h"
3567c32a98SDimitry Andric #include "llvm/Support/LineIterator.h"
36d8e91e46SDimitry Andric #include "llvm/Support/MD5.h"
3767c32a98SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
387fa27ce4SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
3971d5a254SDimitry Andric #include "llvm/Support/raw_ostream.h"
4071d5a254SDimitry Andric #include <algorithm>
4171d5a254SDimitry Andric #include <cstddef>
4271d5a254SDimitry Andric #include <cstdint>
4371d5a254SDimitry Andric #include <limits>
4471d5a254SDimitry Andric #include <memory>
4571d5a254SDimitry Andric #include <system_error>
4671d5a254SDimitry Andric #include <vector>
4767c32a98SDimitry Andric 
4867c32a98SDimitry Andric using namespace llvm;
4971d5a254SDimitry Andric using namespace sampleprof;
5067c32a98SDimitry Andric 
51344a3780SDimitry Andric #define DEBUG_TYPE "samplepgo-reader"
52344a3780SDimitry Andric 
53344a3780SDimitry Andric // This internal option specifies if the profile uses FS discriminators.
547fa27ce4SDimitry Andric // It only applies to text, and binary format profiles.
55344a3780SDimitry Andric // For ext-binary format profiles, the flag is set in the summary.
56344a3780SDimitry Andric static cl::opt<bool> ProfileIsFSDisciminator(
57344a3780SDimitry Andric     "profile-isfs", cl::Hidden, cl::init(false),
58c0981da4SDimitry Andric     cl::desc("Profile uses flow sensitive discriminators"));
59344a3780SDimitry Andric 
60eb11fae6SDimitry Andric /// Dump the function profile for \p FName.
6167c32a98SDimitry Andric ///
62c0981da4SDimitry Andric /// \param FContext Name + context of the function to print.
6367c32a98SDimitry Andric /// \param OS Stream to emit the output to.
dumpFunctionProfile(const FunctionSamples & FS,raw_ostream & OS)64b1c73532SDimitry Andric void SampleProfileReader::dumpFunctionProfile(const FunctionSamples &FS,
6567c32a98SDimitry Andric                                               raw_ostream &OS) {
66b1c73532SDimitry Andric   OS << "Function: " << FS.getContext().toString() << ": " << FS;
6767c32a98SDimitry Andric }
6867c32a98SDimitry Andric 
69eb11fae6SDimitry Andric /// Dump all the function profiles found on stream \p OS.
dump(raw_ostream & OS)7067c32a98SDimitry Andric void SampleProfileReader::dump(raw_ostream &OS) {
71c0981da4SDimitry Andric   std::vector<NameFunctionSamples> V;
72c0981da4SDimitry Andric   sortFuncProfiles(Profiles, V);
73c0981da4SDimitry Andric   for (const auto &I : V)
74b1c73532SDimitry Andric     dumpFunctionProfile(*I.second, OS);
7567c32a98SDimitry Andric }
7667c32a98SDimitry Andric 
dumpFunctionProfileJson(const FunctionSamples & S,json::OStream & JOS,bool TopLevel=false)77e3b55780SDimitry Andric static void dumpFunctionProfileJson(const FunctionSamples &S,
78e3b55780SDimitry Andric                                     json::OStream &JOS, bool TopLevel = false) {
79e3b55780SDimitry Andric   auto DumpBody = [&](const BodySampleMap &BodySamples) {
80e3b55780SDimitry Andric     for (const auto &I : BodySamples) {
81e3b55780SDimitry Andric       const LineLocation &Loc = I.first;
82e3b55780SDimitry Andric       const SampleRecord &Sample = I.second;
83e3b55780SDimitry Andric       JOS.object([&] {
84e3b55780SDimitry Andric         JOS.attribute("line", Loc.LineOffset);
85e3b55780SDimitry Andric         if (Loc.Discriminator)
86e3b55780SDimitry Andric           JOS.attribute("discriminator", Loc.Discriminator);
87e3b55780SDimitry Andric         JOS.attribute("samples", Sample.getSamples());
88e3b55780SDimitry Andric 
89e3b55780SDimitry Andric         auto CallTargets = Sample.getSortedCallTargets();
90e3b55780SDimitry Andric         if (!CallTargets.empty()) {
91e3b55780SDimitry Andric           JOS.attributeArray("calls", [&] {
92e3b55780SDimitry Andric             for (const auto &J : CallTargets) {
93e3b55780SDimitry Andric               JOS.object([&] {
94b1c73532SDimitry Andric                 JOS.attribute("function", J.first.str());
95e3b55780SDimitry Andric                 JOS.attribute("samples", J.second);
96e3b55780SDimitry Andric               });
97e3b55780SDimitry Andric             }
98e3b55780SDimitry Andric           });
99e3b55780SDimitry Andric         }
100e3b55780SDimitry Andric       });
101e3b55780SDimitry Andric     }
102e3b55780SDimitry Andric   };
103e3b55780SDimitry Andric 
104e3b55780SDimitry Andric   auto DumpCallsiteSamples = [&](const CallsiteSampleMap &CallsiteSamples) {
105e3b55780SDimitry Andric     for (const auto &I : CallsiteSamples)
106e3b55780SDimitry Andric       for (const auto &FS : I.second) {
107e3b55780SDimitry Andric         const LineLocation &Loc = I.first;
108e3b55780SDimitry Andric         const FunctionSamples &CalleeSamples = FS.second;
109e3b55780SDimitry Andric         JOS.object([&] {
110e3b55780SDimitry Andric           JOS.attribute("line", Loc.LineOffset);
111e3b55780SDimitry Andric           if (Loc.Discriminator)
112e3b55780SDimitry Andric             JOS.attribute("discriminator", Loc.Discriminator);
113e3b55780SDimitry Andric           JOS.attributeArray(
114e3b55780SDimitry Andric               "samples", [&] { dumpFunctionProfileJson(CalleeSamples, JOS); });
115e3b55780SDimitry Andric         });
116e3b55780SDimitry Andric       }
117e3b55780SDimitry Andric   };
118e3b55780SDimitry Andric 
119e3b55780SDimitry Andric   JOS.object([&] {
120b1c73532SDimitry Andric     JOS.attribute("name", S.getFunction().str());
121e3b55780SDimitry Andric     JOS.attribute("total", S.getTotalSamples());
122e3b55780SDimitry Andric     if (TopLevel)
123e3b55780SDimitry Andric       JOS.attribute("head", S.getHeadSamples());
124e3b55780SDimitry Andric 
125e3b55780SDimitry Andric     const auto &BodySamples = S.getBodySamples();
126e3b55780SDimitry Andric     if (!BodySamples.empty())
127e3b55780SDimitry Andric       JOS.attributeArray("body", [&] { DumpBody(BodySamples); });
128e3b55780SDimitry Andric 
129e3b55780SDimitry Andric     const auto &CallsiteSamples = S.getCallsiteSamples();
130e3b55780SDimitry Andric     if (!CallsiteSamples.empty())
131e3b55780SDimitry Andric       JOS.attributeArray("callsites",
132e3b55780SDimitry Andric                          [&] { DumpCallsiteSamples(CallsiteSamples); });
133e3b55780SDimitry Andric   });
134e3b55780SDimitry Andric }
135e3b55780SDimitry Andric 
136e3b55780SDimitry Andric /// Dump all the function profiles found on stream \p OS in the JSON format.
dumpJson(raw_ostream & OS)137e3b55780SDimitry Andric void SampleProfileReader::dumpJson(raw_ostream &OS) {
138e3b55780SDimitry Andric   std::vector<NameFunctionSamples> V;
139e3b55780SDimitry Andric   sortFuncProfiles(Profiles, V);
140e3b55780SDimitry Andric   json::OStream JOS(OS, 2);
141e3b55780SDimitry Andric   JOS.arrayBegin();
142e3b55780SDimitry Andric   for (const auto &F : V)
143e3b55780SDimitry Andric     dumpFunctionProfileJson(*F.second, JOS, true);
144e3b55780SDimitry Andric   JOS.arrayEnd();
145e3b55780SDimitry Andric 
146e3b55780SDimitry Andric   // Emit a newline character at the end as json::OStream doesn't emit one.
147e3b55780SDimitry Andric   OS << "\n";
148e3b55780SDimitry Andric }
149e3b55780SDimitry Andric 
150eb11fae6SDimitry Andric /// Parse \p Input as function head.
151dd58ef01SDimitry Andric ///
152dd58ef01SDimitry Andric /// Parse one line of \p Input, and update function name in \p FName,
153dd58ef01SDimitry Andric /// function's total sample count in \p NumSamples, function's entry
154dd58ef01SDimitry Andric /// count in \p NumHeadSamples.
155dd58ef01SDimitry Andric ///
156dd58ef01SDimitry Andric /// \returns true if parsing is successful.
ParseHead(const StringRef & Input,StringRef & FName,uint64_t & NumSamples,uint64_t & NumHeadSamples)157dd58ef01SDimitry Andric static bool ParseHead(const StringRef &Input, StringRef &FName,
158dd58ef01SDimitry Andric                       uint64_t &NumSamples, uint64_t &NumHeadSamples) {
159dd58ef01SDimitry Andric   if (Input[0] == ' ')
160dd58ef01SDimitry Andric     return false;
161dd58ef01SDimitry Andric   size_t n2 = Input.rfind(':');
162dd58ef01SDimitry Andric   size_t n1 = Input.rfind(':', n2 - 1);
163dd58ef01SDimitry Andric   FName = Input.substr(0, n1);
164dd58ef01SDimitry Andric   if (Input.substr(n1 + 1, n2 - n1 - 1).getAsInteger(10, NumSamples))
165dd58ef01SDimitry Andric     return false;
166dd58ef01SDimitry Andric   if (Input.substr(n2 + 1).getAsInteger(10, NumHeadSamples))
167dd58ef01SDimitry Andric     return false;
168dd58ef01SDimitry Andric   return true;
169dd58ef01SDimitry Andric }
170dd58ef01SDimitry Andric 
171eb11fae6SDimitry Andric /// Returns true if line offset \p L is legal (only has 16 bits).
isOffsetLegal(unsigned L)17201095a5dSDimitry Andric static bool isOffsetLegal(unsigned L) { return (L & 0xffff) == L; }
173dd58ef01SDimitry Andric 
174b60736ecSDimitry Andric /// Parse \p Input that contains metadata.
175b60736ecSDimitry Andric /// Possible metadata:
176b60736ecSDimitry Andric /// - CFG Checksum information:
177b60736ecSDimitry Andric ///     !CFGChecksum: 12345
178344a3780SDimitry Andric /// - CFG Checksum information:
179344a3780SDimitry Andric ///     !Attributes: 1
180b60736ecSDimitry Andric /// Stores the FunctionHash (a.k.a. CFG Checksum) into \p FunctionHash.
parseMetadata(const StringRef & Input,uint64_t & FunctionHash,uint32_t & Attributes)181344a3780SDimitry Andric static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash,
182344a3780SDimitry Andric                           uint32_t &Attributes) {
183312c0ed1SDimitry Andric   if (Input.starts_with("!CFGChecksum:")) {
184b60736ecSDimitry Andric     StringRef CFGInfo = Input.substr(strlen("!CFGChecksum:")).trim();
185b60736ecSDimitry Andric     return !CFGInfo.getAsInteger(10, FunctionHash);
186b60736ecSDimitry Andric   }
187b60736ecSDimitry Andric 
188312c0ed1SDimitry Andric   if (Input.starts_with("!Attributes:")) {
189344a3780SDimitry Andric     StringRef Attrib = Input.substr(strlen("!Attributes:")).trim();
190344a3780SDimitry Andric     return !Attrib.getAsInteger(10, Attributes);
191344a3780SDimitry Andric   }
192344a3780SDimitry Andric 
193344a3780SDimitry Andric   return false;
194344a3780SDimitry Andric }
195344a3780SDimitry Andric 
196b60736ecSDimitry Andric enum class LineType {
197b60736ecSDimitry Andric   CallSiteProfile,
198b60736ecSDimitry Andric   BodyProfile,
199b60736ecSDimitry Andric   Metadata,
200b60736ecSDimitry Andric };
201b60736ecSDimitry Andric 
202eb11fae6SDimitry Andric /// Parse \p Input as line sample.
203dd58ef01SDimitry Andric ///
204dd58ef01SDimitry Andric /// \param Input input line.
205b60736ecSDimitry Andric /// \param LineTy Type of this line.
206dd58ef01SDimitry Andric /// \param Depth the depth of the inline stack.
207dd58ef01SDimitry Andric /// \param NumSamples total samples of the line/inlined callsite.
208dd58ef01SDimitry Andric /// \param LineOffset line offset to the start of the function.
209dd58ef01SDimitry Andric /// \param Discriminator discriminator of the line.
210dd58ef01SDimitry Andric /// \param TargetCountMap map from indirect call target to count.
211b60736ecSDimitry Andric /// \param FunctionHash the function's CFG hash, used by pseudo probe.
212dd58ef01SDimitry Andric ///
213dd58ef01SDimitry Andric /// returns true if parsing is successful.
ParseLine(const StringRef & Input,LineType & LineTy,uint32_t & Depth,uint64_t & NumSamples,uint32_t & LineOffset,uint32_t & Discriminator,StringRef & CalleeName,DenseMap<StringRef,uint64_t> & TargetCountMap,uint64_t & FunctionHash,uint32_t & Attributes)214b60736ecSDimitry Andric static bool ParseLine(const StringRef &Input, LineType &LineTy, uint32_t &Depth,
215dd58ef01SDimitry Andric                       uint64_t &NumSamples, uint32_t &LineOffset,
216dd58ef01SDimitry Andric                       uint32_t &Discriminator, StringRef &CalleeName,
217b60736ecSDimitry Andric                       DenseMap<StringRef, uint64_t> &TargetCountMap,
218344a3780SDimitry Andric                       uint64_t &FunctionHash, uint32_t &Attributes) {
219dd58ef01SDimitry Andric   for (Depth = 0; Input[Depth] == ' '; Depth++)
220dd58ef01SDimitry Andric     ;
221dd58ef01SDimitry Andric   if (Depth == 0)
222dd58ef01SDimitry Andric     return false;
223dd58ef01SDimitry Andric 
22477fc4c14SDimitry Andric   if (Input[Depth] == '!') {
225b60736ecSDimitry Andric     LineTy = LineType::Metadata;
226344a3780SDimitry Andric     return parseMetadata(Input.substr(Depth), FunctionHash, Attributes);
227b60736ecSDimitry Andric   }
228b60736ecSDimitry Andric 
229dd58ef01SDimitry Andric   size_t n1 = Input.find(':');
230dd58ef01SDimitry Andric   StringRef Loc = Input.substr(Depth, n1 - Depth);
231dd58ef01SDimitry Andric   size_t n2 = Loc.find('.');
232dd58ef01SDimitry Andric   if (n2 == StringRef::npos) {
233dd58ef01SDimitry Andric     if (Loc.getAsInteger(10, LineOffset) || !isOffsetLegal(LineOffset))
234dd58ef01SDimitry Andric       return false;
235dd58ef01SDimitry Andric     Discriminator = 0;
236dd58ef01SDimitry Andric   } else {
237dd58ef01SDimitry Andric     if (Loc.substr(0, n2).getAsInteger(10, LineOffset))
238dd58ef01SDimitry Andric       return false;
239dd58ef01SDimitry Andric     if (Loc.substr(n2 + 1).getAsInteger(10, Discriminator))
240dd58ef01SDimitry Andric       return false;
241dd58ef01SDimitry Andric   }
242dd58ef01SDimitry Andric 
243dd58ef01SDimitry Andric   StringRef Rest = Input.substr(n1 + 2);
244b60736ecSDimitry Andric   if (isDigit(Rest[0])) {
245b60736ecSDimitry Andric     LineTy = LineType::BodyProfile;
246dd58ef01SDimitry Andric     size_t n3 = Rest.find(' ');
247dd58ef01SDimitry Andric     if (n3 == StringRef::npos) {
248dd58ef01SDimitry Andric       if (Rest.getAsInteger(10, NumSamples))
249dd58ef01SDimitry Andric         return false;
250dd58ef01SDimitry Andric     } else {
251dd58ef01SDimitry Andric       if (Rest.substr(0, n3).getAsInteger(10, NumSamples))
252dd58ef01SDimitry Andric         return false;
253dd58ef01SDimitry Andric     }
254eb11fae6SDimitry Andric     // Find call targets and their sample counts.
255eb11fae6SDimitry Andric     // Note: In some cases, there are symbols in the profile which are not
256eb11fae6SDimitry Andric     // mangled. To accommodate such cases, use colon + integer pairs as the
257eb11fae6SDimitry Andric     // anchor points.
258eb11fae6SDimitry Andric     // An example:
259eb11fae6SDimitry Andric     // _M_construct<char *>:1000 string_view<std::allocator<char> >:437
260eb11fae6SDimitry Andric     // ":1000" and ":437" are used as anchor points so the string above will
261eb11fae6SDimitry Andric     // be interpreted as
262eb11fae6SDimitry Andric     // target: _M_construct<char *>
263eb11fae6SDimitry Andric     // count: 1000
264eb11fae6SDimitry Andric     // target: string_view<std::allocator<char> >
265eb11fae6SDimitry Andric     // count: 437
266dd58ef01SDimitry Andric     while (n3 != StringRef::npos) {
267dd58ef01SDimitry Andric       n3 += Rest.substr(n3).find_first_not_of(' ');
268dd58ef01SDimitry Andric       Rest = Rest.substr(n3);
269eb11fae6SDimitry Andric       n3 = Rest.find_first_of(':');
270eb11fae6SDimitry Andric       if (n3 == StringRef::npos || n3 == 0)
271dd58ef01SDimitry Andric         return false;
272eb11fae6SDimitry Andric 
273eb11fae6SDimitry Andric       StringRef Target;
274eb11fae6SDimitry Andric       uint64_t count, n4;
275eb11fae6SDimitry Andric       while (true) {
276eb11fae6SDimitry Andric         // Get the segment after the current colon.
277eb11fae6SDimitry Andric         StringRef AfterColon = Rest.substr(n3 + 1);
278eb11fae6SDimitry Andric         // Get the target symbol before the current colon.
279eb11fae6SDimitry Andric         Target = Rest.substr(0, n3);
280eb11fae6SDimitry Andric         // Check if the word after the current colon is an integer.
281eb11fae6SDimitry Andric         n4 = AfterColon.find_first_of(' ');
282eb11fae6SDimitry Andric         n4 = (n4 != StringRef::npos) ? n3 + n4 + 1 : Rest.size();
283eb11fae6SDimitry Andric         StringRef WordAfterColon = Rest.substr(n3 + 1, n4 - n3 - 1);
284eb11fae6SDimitry Andric         if (!WordAfterColon.getAsInteger(10, count))
285eb11fae6SDimitry Andric           break;
286eb11fae6SDimitry Andric 
287eb11fae6SDimitry Andric         // Try to find the next colon.
288eb11fae6SDimitry Andric         uint64_t n5 = AfterColon.find_first_of(':');
289eb11fae6SDimitry Andric         if (n5 == StringRef::npos)
290eb11fae6SDimitry Andric           return false;
291eb11fae6SDimitry Andric         n3 += n5 + 1;
292eb11fae6SDimitry Andric       }
293eb11fae6SDimitry Andric 
294eb11fae6SDimitry Andric       // An anchor point is found. Save the {target, count} pair
295eb11fae6SDimitry Andric       TargetCountMap[Target] = count;
296eb11fae6SDimitry Andric       if (n4 == Rest.size())
297eb11fae6SDimitry Andric         break;
298eb11fae6SDimitry Andric       // Change n3 to the next blank space after colon + integer pair.
299eb11fae6SDimitry Andric       n3 = n4;
300dd58ef01SDimitry Andric     }
301dd58ef01SDimitry Andric   } else {
302b60736ecSDimitry Andric     LineTy = LineType::CallSiteProfile;
303dd58ef01SDimitry Andric     size_t n3 = Rest.find_last_of(':');
304dd58ef01SDimitry Andric     CalleeName = Rest.substr(0, n3);
305dd58ef01SDimitry Andric     if (Rest.substr(n3 + 1).getAsInteger(10, NumSamples))
306dd58ef01SDimitry Andric       return false;
307dd58ef01SDimitry Andric   }
308dd58ef01SDimitry Andric   return true;
309dd58ef01SDimitry Andric }
310dd58ef01SDimitry Andric 
311eb11fae6SDimitry Andric /// Load samples from a text file.
31267c32a98SDimitry Andric ///
31367c32a98SDimitry Andric /// See the documentation at the top of the file for an explanation of
31467c32a98SDimitry Andric /// the expected format.
31567c32a98SDimitry Andric ///
31667c32a98SDimitry Andric /// \returns true if the file was loaded successfully, false otherwise.
readImpl()3171d5ae102SDimitry Andric std::error_code SampleProfileReaderText::readImpl() {
31867c32a98SDimitry Andric   line_iterator LineIt(*Buffer, /*SkipBlanks=*/true, '#');
319dd58ef01SDimitry Andric   sampleprof_error Result = sampleprof_error::success;
32067c32a98SDimitry Andric 
321dd58ef01SDimitry Andric   InlineCallStack InlineStack;
32277fc4c14SDimitry Andric   uint32_t TopLevelProbeProfileCount = 0;
323b60736ecSDimitry Andric 
32477fc4c14SDimitry Andric   // DepthMetadata tracks whether we have processed metadata for the current
32577fc4c14SDimitry Andric   // top-level or nested function profile.
32677fc4c14SDimitry Andric   uint32_t DepthMetadata = 0;
327dd58ef01SDimitry Andric 
328344a3780SDimitry Andric   ProfileIsFS = ProfileIsFSDisciminator;
329c0981da4SDimitry Andric   FunctionSamples::ProfileIsFS = ProfileIsFS;
330dd58ef01SDimitry Andric   for (; !LineIt.is_at_eof(); ++LineIt) {
3317fa27ce4SDimitry Andric     size_t pos = LineIt->find_first_not_of(' ');
3327fa27ce4SDimitry Andric     if (pos == LineIt->npos || (*LineIt)[pos] == '#')
333dd58ef01SDimitry Andric       continue;
33467c32a98SDimitry Andric     // Read the header of each function.
33567c32a98SDimitry Andric     //
33667c32a98SDimitry Andric     // Note that for function identifiers we are actually expecting
33767c32a98SDimitry Andric     // mangled names, but we may not always get them. This happens when
33867c32a98SDimitry Andric     // the compiler decides not to emit the function (e.g., it was inlined
33967c32a98SDimitry Andric     // and removed). In this case, the binary will not have the linkage
34067c32a98SDimitry Andric     // name for the function, so the profiler will emit the function's
34167c32a98SDimitry Andric     // unmangled name, which may contain characters like ':' and '>' in its
34267c32a98SDimitry Andric     // name (member functions, templates, etc).
34367c32a98SDimitry Andric     //
34467c32a98SDimitry Andric     // The only requirement we place on the identifier, then, is that it
34567c32a98SDimitry Andric     // should not begin with a number.
346dd58ef01SDimitry Andric     if ((*LineIt)[0] != ' ') {
347dd58ef01SDimitry Andric       uint64_t NumSamples, NumHeadSamples;
348dd58ef01SDimitry Andric       StringRef FName;
349dd58ef01SDimitry Andric       if (!ParseHead(*LineIt, FName, NumSamples, NumHeadSamples)) {
350dd58ef01SDimitry Andric         reportError(LineIt.line_number(),
35167c32a98SDimitry Andric                     "Expected 'mangled_name:NUM:NUM', found " + *LineIt);
35267c32a98SDimitry Andric         return sampleprof_error::malformed;
35367c32a98SDimitry Andric       }
35477fc4c14SDimitry Andric       DepthMetadata = 0;
355c0981da4SDimitry Andric       SampleContext FContext(FName, CSNameTable);
356b60736ecSDimitry Andric       if (FContext.hasContext())
357b60736ecSDimitry Andric         ++CSProfileCount;
358ac9a064cSDimitry Andric       FunctionSamples &FProfile = Profiles.create(FContext);
359ac9a064cSDimitry Andric       mergeSampleProfErrors(Result, FProfile.addTotalSamples(NumSamples));
360ac9a064cSDimitry Andric       mergeSampleProfErrors(Result, FProfile.addHeadSamples(NumHeadSamples));
361dd58ef01SDimitry Andric       InlineStack.clear();
362dd58ef01SDimitry Andric       InlineStack.push_back(&FProfile);
363dd58ef01SDimitry Andric     } else {
364dd58ef01SDimitry Andric       uint64_t NumSamples;
365dd58ef01SDimitry Andric       StringRef FName;
366dd58ef01SDimitry Andric       DenseMap<StringRef, uint64_t> TargetCountMap;
367dd58ef01SDimitry Andric       uint32_t Depth, LineOffset, Discriminator;
368b60736ecSDimitry Andric       LineType LineTy;
369344a3780SDimitry Andric       uint64_t FunctionHash = 0;
370344a3780SDimitry Andric       uint32_t Attributes = 0;
371b60736ecSDimitry Andric       if (!ParseLine(*LineIt, LineTy, Depth, NumSamples, LineOffset,
372344a3780SDimitry Andric                      Discriminator, FName, TargetCountMap, FunctionHash,
373344a3780SDimitry Andric                      Attributes)) {
374dd58ef01SDimitry Andric         reportError(LineIt.line_number(),
375dd58ef01SDimitry Andric                     "Expected 'NUM[.NUM]: NUM[ mangled_name:NUM]*', found " +
376dd58ef01SDimitry Andric                         *LineIt);
37767c32a98SDimitry Andric         return sampleprof_error::malformed;
37867c32a98SDimitry Andric       }
37977fc4c14SDimitry Andric       if (LineTy != LineType::Metadata && Depth == DepthMetadata) {
380b60736ecSDimitry Andric         // Metadata must be put at the end of a function profile.
381b60736ecSDimitry Andric         reportError(LineIt.line_number(),
382b60736ecSDimitry Andric                     "Found non-metadata after metadata: " + *LineIt);
383b60736ecSDimitry Andric         return sampleprof_error::malformed;
384b60736ecSDimitry Andric       }
385344a3780SDimitry Andric 
386344a3780SDimitry Andric       // Here we handle FS discriminators.
387344a3780SDimitry Andric       Discriminator &= getDiscriminatorMask();
388344a3780SDimitry Andric 
389dd58ef01SDimitry Andric       while (InlineStack.size() > Depth) {
390dd58ef01SDimitry Andric         InlineStack.pop_back();
39167c32a98SDimitry Andric       }
392b60736ecSDimitry Andric       switch (LineTy) {
393b60736ecSDimitry Andric       case LineType::CallSiteProfile: {
394dd58ef01SDimitry Andric         FunctionSamples &FSamples = InlineStack.back()->functionSamplesAt(
395b1c73532SDimitry Andric             LineLocation(LineOffset, Discriminator))[FunctionId(FName)];
396b1c73532SDimitry Andric         FSamples.setFunction(FunctionId(FName));
397ac9a064cSDimitry Andric         mergeSampleProfErrors(Result, FSamples.addTotalSamples(NumSamples));
398dd58ef01SDimitry Andric         InlineStack.push_back(&FSamples);
39977fc4c14SDimitry Andric         DepthMetadata = 0;
400b60736ecSDimitry Andric         break;
401b60736ecSDimitry Andric       }
402b60736ecSDimitry Andric       case LineType::BodyProfile: {
403dd58ef01SDimitry Andric         while (InlineStack.size() > Depth) {
404dd58ef01SDimitry Andric           InlineStack.pop_back();
40567c32a98SDimitry Andric         }
406dd58ef01SDimitry Andric         FunctionSamples &FProfile = *InlineStack.back();
407dd58ef01SDimitry Andric         for (const auto &name_count : TargetCountMap) {
408ac9a064cSDimitry Andric           mergeSampleProfErrors(Result, FProfile.addCalledTargetSamples(
409b1c73532SDimitry Andric                                             LineOffset, Discriminator,
410b1c73532SDimitry Andric                                             FunctionId(name_count.first),
411dd58ef01SDimitry Andric                                             name_count.second));
412dd58ef01SDimitry Andric         }
413ac9a064cSDimitry Andric         mergeSampleProfErrors(
414ac9a064cSDimitry Andric             Result,
415ac9a064cSDimitry Andric             FProfile.addBodySamples(LineOffset, Discriminator, NumSamples));
416b60736ecSDimitry Andric         break;
417b60736ecSDimitry Andric       }
418b60736ecSDimitry Andric       case LineType::Metadata: {
419b60736ecSDimitry Andric         FunctionSamples &FProfile = *InlineStack.back();
420344a3780SDimitry Andric         if (FunctionHash) {
421b60736ecSDimitry Andric           FProfile.setFunctionHash(FunctionHash);
42277fc4c14SDimitry Andric           if (Depth == 1)
42377fc4c14SDimitry Andric             ++TopLevelProbeProfileCount;
424344a3780SDimitry Andric         }
425344a3780SDimitry Andric         FProfile.getContext().setAllAttributes(Attributes);
42677fc4c14SDimitry Andric         if (Attributes & (uint32_t)ContextShouldBeInlined)
427145449b1SDimitry Andric           ProfileIsPreInlined = true;
42877fc4c14SDimitry Andric         DepthMetadata = Depth;
429b60736ecSDimitry Andric         break;
430dd58ef01SDimitry Andric       }
43167c32a98SDimitry Andric       }
43267c32a98SDimitry Andric     }
433b60736ecSDimitry Andric   }
434b60736ecSDimitry Andric 
435344a3780SDimitry Andric   assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
436b60736ecSDimitry Andric          "Cannot have both context-sensitive and regular profile");
437145449b1SDimitry Andric   ProfileIsCS = (CSProfileCount > 0);
43877fc4c14SDimitry Andric   assert((TopLevelProbeProfileCount == 0 ||
43977fc4c14SDimitry Andric           TopLevelProbeProfileCount == Profiles.size()) &&
440b60736ecSDimitry Andric          "Cannot have both probe-based profiles and regular profiles");
44177fc4c14SDimitry Andric   ProfileIsProbeBased = (TopLevelProbeProfileCount > 0);
442b60736ecSDimitry Andric   FunctionSamples::ProfileIsProbeBased = ProfileIsProbeBased;
443145449b1SDimitry Andric   FunctionSamples::ProfileIsCS = ProfileIsCS;
444145449b1SDimitry Andric   FunctionSamples::ProfileIsPreInlined = ProfileIsPreInlined;
445b60736ecSDimitry Andric 
44601095a5dSDimitry Andric   if (Result == sampleprof_error::success)
44701095a5dSDimitry Andric     computeSummary();
44867c32a98SDimitry Andric 
449dd58ef01SDimitry Andric   return Result;
450dd58ef01SDimitry Andric }
451dd58ef01SDimitry Andric 
hasFormat(const MemoryBuffer & Buffer)452dd58ef01SDimitry Andric bool SampleProfileReaderText::hasFormat(const MemoryBuffer &Buffer) {
453dd58ef01SDimitry Andric   bool result = false;
454dd58ef01SDimitry Andric 
455dd58ef01SDimitry Andric   // Check that the first non-comment line is a valid function header.
456dd58ef01SDimitry Andric   line_iterator LineIt(Buffer, /*SkipBlanks=*/true, '#');
457dd58ef01SDimitry Andric   if (!LineIt.is_at_eof()) {
458dd58ef01SDimitry Andric     if ((*LineIt)[0] != ' ') {
459dd58ef01SDimitry Andric       uint64_t NumSamples, NumHeadSamples;
460dd58ef01SDimitry Andric       StringRef FName;
461dd58ef01SDimitry Andric       result = ParseHead(*LineIt, FName, NumSamples, NumHeadSamples);
462dd58ef01SDimitry Andric     }
463dd58ef01SDimitry Andric   }
464dd58ef01SDimitry Andric 
465dd58ef01SDimitry Andric   return result;
46667c32a98SDimitry Andric }
46767c32a98SDimitry Andric 
readNumber()46867c32a98SDimitry Andric template <typename T> ErrorOr<T> SampleProfileReaderBinary::readNumber() {
46967c32a98SDimitry Andric   unsigned NumBytesRead = 0;
47067c32a98SDimitry Andric   uint64_t Val = decodeULEB128(Data, &NumBytesRead);
47167c32a98SDimitry Andric 
472b1c73532SDimitry Andric   if (Val > std::numeric_limits<T>::max()) {
473b1c73532SDimitry Andric     std::error_code EC = sampleprof_error::malformed;
474b1c73532SDimitry Andric     reportError(0, EC.message());
475b1c73532SDimitry Andric     return EC;
476b1c73532SDimitry Andric   } else if (Data + NumBytesRead > End) {
477b1c73532SDimitry Andric     std::error_code EC = sampleprof_error::truncated;
478dd58ef01SDimitry Andric     reportError(0, EC.message());
47967c32a98SDimitry Andric     return EC;
48067c32a98SDimitry Andric   }
48167c32a98SDimitry Andric 
48267c32a98SDimitry Andric   Data += NumBytesRead;
48367c32a98SDimitry Andric   return static_cast<T>(Val);
48467c32a98SDimitry Andric }
48567c32a98SDimitry Andric 
readString()48667c32a98SDimitry Andric ErrorOr<StringRef> SampleProfileReaderBinary::readString() {
48767c32a98SDimitry Andric   StringRef Str(reinterpret_cast<const char *>(Data));
48867c32a98SDimitry Andric   if (Data + Str.size() + 1 > End) {
489b1c73532SDimitry Andric     std::error_code EC = sampleprof_error::truncated;
490dd58ef01SDimitry Andric     reportError(0, EC.message());
49167c32a98SDimitry Andric     return EC;
49267c32a98SDimitry Andric   }
49367c32a98SDimitry Andric 
49467c32a98SDimitry Andric   Data += Str.size() + 1;
49567c32a98SDimitry Andric   return Str;
49667c32a98SDimitry Andric }
49767c32a98SDimitry Andric 
498eb11fae6SDimitry Andric template <typename T>
readUnencodedNumber()499d8e91e46SDimitry Andric ErrorOr<T> SampleProfileReaderBinary::readUnencodedNumber() {
500d8e91e46SDimitry Andric   if (Data + sizeof(T) > End) {
501b1c73532SDimitry Andric     std::error_code EC = sampleprof_error::truncated;
502d8e91e46SDimitry Andric     reportError(0, EC.message());
503d8e91e46SDimitry Andric     return EC;
504d8e91e46SDimitry Andric   }
505d8e91e46SDimitry Andric 
506d8e91e46SDimitry Andric   using namespace support;
507ac9a064cSDimitry Andric   T Val = endian::readNext<T, llvm::endianness::little>(Data);
508d8e91e46SDimitry Andric   return Val;
509d8e91e46SDimitry Andric }
510d8e91e46SDimitry Andric 
511d8e91e46SDimitry Andric template <typename T>
readStringIndex(T & Table)5127fa27ce4SDimitry Andric inline ErrorOr<size_t> SampleProfileReaderBinary::readStringIndex(T &Table) {
5137fa27ce4SDimitry Andric   auto Idx = readNumber<size_t>();
514dd58ef01SDimitry Andric   if (std::error_code EC = Idx.getError())
51567c32a98SDimitry Andric     return EC;
516eb11fae6SDimitry Andric   if (*Idx >= Table.size())
517dd58ef01SDimitry Andric     return sampleprof_error::truncated_name_table;
518eb11fae6SDimitry Andric   return *Idx;
519eb11fae6SDimitry Andric }
520eb11fae6SDimitry Andric 
521b1c73532SDimitry Andric ErrorOr<FunctionId>
readStringFromTable(size_t * RetIdx)522b1c73532SDimitry Andric SampleProfileReaderBinary::readStringFromTable(size_t *RetIdx) {
523eb11fae6SDimitry Andric   auto Idx = readStringIndex(NameTable);
524eb11fae6SDimitry Andric   if (std::error_code EC = Idx.getError())
525eb11fae6SDimitry Andric     return EC;
526b1c73532SDimitry Andric   if (RetIdx)
527b1c73532SDimitry Andric     *RetIdx = *Idx;
528b1c73532SDimitry Andric   return NameTable[*Idx];
5297fa27ce4SDimitry Andric }
5307fa27ce4SDimitry Andric 
531b1c73532SDimitry Andric ErrorOr<SampleContextFrames>
readContextFromTable(size_t * RetIdx)532b1c73532SDimitry Andric SampleProfileReaderBinary::readContextFromTable(size_t *RetIdx) {
5337fa27ce4SDimitry Andric   auto ContextIdx = readNumber<size_t>();
5347fa27ce4SDimitry Andric   if (std::error_code EC = ContextIdx.getError())
5357fa27ce4SDimitry Andric     return EC;
5367fa27ce4SDimitry Andric   if (*ContextIdx >= CSNameTable.size())
5377fa27ce4SDimitry Andric     return sampleprof_error::truncated_name_table;
538b1c73532SDimitry Andric   if (RetIdx)
539b1c73532SDimitry Andric     *RetIdx = *ContextIdx;
5407fa27ce4SDimitry Andric   return CSNameTable[*ContextIdx];
541dd58ef01SDimitry Andric }
54267c32a98SDimitry Andric 
543b1c73532SDimitry Andric ErrorOr<std::pair<SampleContext, uint64_t>>
readSampleContextFromTable()544b1c73532SDimitry Andric SampleProfileReaderBinary::readSampleContextFromTable() {
545b1c73532SDimitry Andric   SampleContext Context;
546b1c73532SDimitry Andric   size_t Idx;
5477fa27ce4SDimitry Andric   if (ProfileIsCS) {
548b1c73532SDimitry Andric     auto FContext(readContextFromTable(&Idx));
5497fa27ce4SDimitry Andric     if (std::error_code EC = FContext.getError())
5507fa27ce4SDimitry Andric       return EC;
551b1c73532SDimitry Andric     Context = SampleContext(*FContext);
5527fa27ce4SDimitry Andric   } else {
553b1c73532SDimitry Andric     auto FName(readStringFromTable(&Idx));
554c0981da4SDimitry Andric     if (std::error_code EC = FName.getError())
555c0981da4SDimitry Andric       return EC;
556b1c73532SDimitry Andric     Context = SampleContext(*FName);
557c0981da4SDimitry Andric   }
558b1c73532SDimitry Andric   // Since MD5SampleContextStart may point to the profile's file data, need to
559b1c73532SDimitry Andric   // make sure it is reading the same value on big endian CPU.
560b1c73532SDimitry Andric   uint64_t Hash = support::endian::read64le(MD5SampleContextStart + Idx);
561b1c73532SDimitry Andric   // Lazy computing of hash value, write back to the table to cache it. Only
562b1c73532SDimitry Andric   // compute the context's hash value if it is being referenced for the first
563b1c73532SDimitry Andric   // time.
564b1c73532SDimitry Andric   if (Hash == 0) {
565b1c73532SDimitry Andric     assert(MD5SampleContextStart == MD5SampleContextTable.data());
566b1c73532SDimitry Andric     Hash = Context.getHashCode();
567b1c73532SDimitry Andric     support::endian::write64le(&MD5SampleContextTable[Idx], Hash);
568b1c73532SDimitry Andric   }
569b1c73532SDimitry Andric   return std::make_pair(Context, Hash);
570eb11fae6SDimitry Andric }
571eb11fae6SDimitry Andric 
572dd58ef01SDimitry Andric std::error_code
readProfile(FunctionSamples & FProfile)573dd58ef01SDimitry Andric SampleProfileReaderBinary::readProfile(FunctionSamples &FProfile) {
574dd58ef01SDimitry Andric   auto NumSamples = readNumber<uint64_t>();
575dd58ef01SDimitry Andric   if (std::error_code EC = NumSamples.getError())
57667c32a98SDimitry Andric     return EC;
577dd58ef01SDimitry Andric   FProfile.addTotalSamples(*NumSamples);
57867c32a98SDimitry Andric 
57967c32a98SDimitry Andric   // Read the samples in the body.
580dd58ef01SDimitry Andric   auto NumRecords = readNumber<uint32_t>();
58167c32a98SDimitry Andric   if (std::error_code EC = NumRecords.getError())
58267c32a98SDimitry Andric     return EC;
583dd58ef01SDimitry Andric 
584dd58ef01SDimitry Andric   for (uint32_t I = 0; I < *NumRecords; ++I) {
58567c32a98SDimitry Andric     auto LineOffset = readNumber<uint64_t>();
58667c32a98SDimitry Andric     if (std::error_code EC = LineOffset.getError())
58767c32a98SDimitry Andric       return EC;
58867c32a98SDimitry Andric 
589dd58ef01SDimitry Andric     if (!isOffsetLegal(*LineOffset)) {
590dd58ef01SDimitry Andric       return std::error_code();
591dd58ef01SDimitry Andric     }
592dd58ef01SDimitry Andric 
59367c32a98SDimitry Andric     auto Discriminator = readNumber<uint64_t>();
59467c32a98SDimitry Andric     if (std::error_code EC = Discriminator.getError())
59567c32a98SDimitry Andric       return EC;
59667c32a98SDimitry Andric 
59767c32a98SDimitry Andric     auto NumSamples = readNumber<uint64_t>();
59867c32a98SDimitry Andric     if (std::error_code EC = NumSamples.getError())
59967c32a98SDimitry Andric       return EC;
60067c32a98SDimitry Andric 
601dd58ef01SDimitry Andric     auto NumCalls = readNumber<uint32_t>();
60267c32a98SDimitry Andric     if (std::error_code EC = NumCalls.getError())
60367c32a98SDimitry Andric       return EC;
60467c32a98SDimitry Andric 
605344a3780SDimitry Andric     // Here we handle FS discriminators:
606344a3780SDimitry Andric     uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
607344a3780SDimitry Andric 
608dd58ef01SDimitry Andric     for (uint32_t J = 0; J < *NumCalls; ++J) {
609dd58ef01SDimitry Andric       auto CalledFunction(readStringFromTable());
61067c32a98SDimitry Andric       if (std::error_code EC = CalledFunction.getError())
61167c32a98SDimitry Andric         return EC;
61267c32a98SDimitry Andric 
61367c32a98SDimitry Andric       auto CalledFunctionSamples = readNumber<uint64_t>();
61467c32a98SDimitry Andric       if (std::error_code EC = CalledFunctionSamples.getError())
61567c32a98SDimitry Andric         return EC;
61667c32a98SDimitry Andric 
617344a3780SDimitry Andric       FProfile.addCalledTargetSamples(*LineOffset, DiscriminatorVal,
618dd58ef01SDimitry Andric                                       *CalledFunction, *CalledFunctionSamples);
61967c32a98SDimitry Andric     }
62067c32a98SDimitry Andric 
621344a3780SDimitry Andric     FProfile.addBodySamples(*LineOffset, DiscriminatorVal, *NumSamples);
62267c32a98SDimitry Andric   }
623dd58ef01SDimitry Andric 
624dd58ef01SDimitry Andric   // Read all the samples for inlined function calls.
625dd58ef01SDimitry Andric   auto NumCallsites = readNumber<uint32_t>();
626dd58ef01SDimitry Andric   if (std::error_code EC = NumCallsites.getError())
627dd58ef01SDimitry Andric     return EC;
628dd58ef01SDimitry Andric 
629dd58ef01SDimitry Andric   for (uint32_t J = 0; J < *NumCallsites; ++J) {
630dd58ef01SDimitry Andric     auto LineOffset = readNumber<uint64_t>();
631dd58ef01SDimitry Andric     if (std::error_code EC = LineOffset.getError())
632dd58ef01SDimitry Andric       return EC;
633dd58ef01SDimitry Andric 
634dd58ef01SDimitry Andric     auto Discriminator = readNumber<uint64_t>();
635dd58ef01SDimitry Andric     if (std::error_code EC = Discriminator.getError())
636dd58ef01SDimitry Andric       return EC;
637dd58ef01SDimitry Andric 
638dd58ef01SDimitry Andric     auto FName(readStringFromTable());
639dd58ef01SDimitry Andric     if (std::error_code EC = FName.getError())
640dd58ef01SDimitry Andric       return EC;
641dd58ef01SDimitry Andric 
642344a3780SDimitry Andric     // Here we handle FS discriminators:
643344a3780SDimitry Andric     uint32_t DiscriminatorVal = (*Discriminator) & getDiscriminatorMask();
644344a3780SDimitry Andric 
64571d5a254SDimitry Andric     FunctionSamples &CalleeProfile = FProfile.functionSamplesAt(
646b1c73532SDimitry Andric         LineLocation(*LineOffset, DiscriminatorVal))[*FName];
647b1c73532SDimitry Andric     CalleeProfile.setFunction(*FName);
648dd58ef01SDimitry Andric     if (std::error_code EC = readProfile(CalleeProfile))
649dd58ef01SDimitry Andric       return EC;
650dd58ef01SDimitry Andric   }
651dd58ef01SDimitry Andric 
652dd58ef01SDimitry Andric   return sampleprof_error::success;
653dd58ef01SDimitry Andric }
654dd58ef01SDimitry Andric 
6551d5ae102SDimitry Andric std::error_code
readFuncProfile(const uint8_t * Start)6561d5ae102SDimitry Andric SampleProfileReaderBinary::readFuncProfile(const uint8_t *Start) {
6571d5ae102SDimitry Andric   Data = Start;
658dd58ef01SDimitry Andric   auto NumHeadSamples = readNumber<uint64_t>();
659dd58ef01SDimitry Andric   if (std::error_code EC = NumHeadSamples.getError())
660dd58ef01SDimitry Andric     return EC;
661dd58ef01SDimitry Andric 
662b1c73532SDimitry Andric   auto FContextHash(readSampleContextFromTable());
663b1c73532SDimitry Andric   if (std::error_code EC = FContextHash.getError())
664dd58ef01SDimitry Andric     return EC;
665dd58ef01SDimitry Andric 
666b1c73532SDimitry Andric   auto &[FContext, Hash] = *FContextHash;
667b1c73532SDimitry Andric   // Use the cached hash value for insertion instead of recalculating it.
668b1c73532SDimitry Andric   auto Res = Profiles.try_emplace(Hash, FContext, FunctionSamples());
669b1c73532SDimitry Andric   FunctionSamples &FProfile = Res.first->second;
670b1c73532SDimitry Andric   FProfile.setContext(FContext);
671dd58ef01SDimitry Andric   FProfile.addHeadSamples(*NumHeadSamples);
672dd58ef01SDimitry Andric 
673b1c73532SDimitry Andric   if (FContext.hasContext())
674344a3780SDimitry Andric     CSProfileCount++;
675344a3780SDimitry Andric 
676dd58ef01SDimitry Andric   if (std::error_code EC = readProfile(FProfile))
677dd58ef01SDimitry Andric     return EC;
678d8e91e46SDimitry Andric   return sampleprof_error::success;
67967c32a98SDimitry Andric }
68067c32a98SDimitry Andric 
readImpl()6811d5ae102SDimitry Andric std::error_code SampleProfileReaderBinary::readImpl() {
682344a3780SDimitry Andric   ProfileIsFS = ProfileIsFSDisciminator;
683c0981da4SDimitry Andric   FunctionSamples::ProfileIsFS = ProfileIsFS;
6847fa27ce4SDimitry Andric   while (Data < End) {
6851d5ae102SDimitry Andric     if (std::error_code EC = readFuncProfile(Data))
686d8e91e46SDimitry Andric       return EC;
687d8e91e46SDimitry Andric   }
688d8e91e46SDimitry Andric 
689d8e91e46SDimitry Andric   return sampleprof_error::success;
690d8e91e46SDimitry Andric }
691d8e91e46SDimitry Andric 
readOneSection(const uint8_t * Start,uint64_t Size,const SecHdrTableEntry & Entry)692b60736ecSDimitry Andric std::error_code SampleProfileReaderExtBinaryBase::readOneSection(
693cfca06d7SDimitry Andric     const uint8_t *Start, uint64_t Size, const SecHdrTableEntry &Entry) {
6941d5ae102SDimitry Andric   Data = Start;
6951d5ae102SDimitry Andric   End = Start + Size;
696cfca06d7SDimitry Andric   switch (Entry.Type) {
6971d5ae102SDimitry Andric   case SecProfSummary:
6981d5ae102SDimitry Andric     if (std::error_code EC = readSummary())
6991d5ae102SDimitry Andric       return EC;
700cfca06d7SDimitry Andric     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
701cfca06d7SDimitry Andric       Summary->setPartialProfile(true);
702344a3780SDimitry Andric     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFullContext))
703145449b1SDimitry Andric       FunctionSamples::ProfileIsCS = ProfileIsCS = true;
704145449b1SDimitry Andric     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagIsPreInlined))
705145449b1SDimitry Andric       FunctionSamples::ProfileIsPreInlined = ProfileIsPreInlined = true;
706344a3780SDimitry Andric     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFSDiscriminator))
707344a3780SDimitry Andric       FunctionSamples::ProfileIsFS = ProfileIsFS = true;
7081d5ae102SDimitry Andric     break;
709b60736ecSDimitry Andric   case SecNameTable: {
7107fa27ce4SDimitry Andric     bool FixedLengthMD5 =
711b60736ecSDimitry Andric         hasSecFlag(Entry, SecNameTableFlags::SecFlagFixedLengthMD5);
712b60736ecSDimitry Andric     bool UseMD5 = hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name);
7137fa27ce4SDimitry Andric     // UseMD5 means if THIS section uses MD5, ProfileIsMD5 means if the entire
7147fa27ce4SDimitry Andric     // profile uses MD5 for function name matching in IPO passes.
7157fa27ce4SDimitry Andric     ProfileIsMD5 = ProfileIsMD5 || UseMD5;
716344a3780SDimitry Andric     FunctionSamples::HasUniqSuffix =
717344a3780SDimitry Andric         hasSecFlag(Entry, SecNameTableFlags::SecFlagUniqSuffix);
7187fa27ce4SDimitry Andric     if (std::error_code EC = readNameTableSec(UseMD5, FixedLengthMD5))
7191d5ae102SDimitry Andric       return EC;
7201d5ae102SDimitry Andric     break;
721b60736ecSDimitry Andric   }
722c0981da4SDimitry Andric   case SecCSNameTable: {
723c0981da4SDimitry Andric     if (std::error_code EC = readCSNameTableSec())
724c0981da4SDimitry Andric       return EC;
725c0981da4SDimitry Andric     break;
726c0981da4SDimitry Andric   }
7271d5ae102SDimitry Andric   case SecLBRProfile:
7281d5ae102SDimitry Andric     if (std::error_code EC = readFuncProfiles())
7291d5ae102SDimitry Andric       return EC;
7301d5ae102SDimitry Andric     break;
7311d5ae102SDimitry Andric   case SecFuncOffsetTable:
7327fa27ce4SDimitry Andric     // If module is absent, we are using LLVM tools, and need to read all
7337fa27ce4SDimitry Andric     // profiles, so skip reading the function offset table.
7347fa27ce4SDimitry Andric     if (!M) {
7357fa27ce4SDimitry Andric       Data = End;
7367fa27ce4SDimitry Andric     } else {
7377fa27ce4SDimitry Andric       assert((!ProfileIsCS ||
7387fa27ce4SDimitry Andric               hasSecFlag(Entry, SecFuncOffsetFlags::SecFlagOrdered)) &&
7397fa27ce4SDimitry Andric              "func offset table should always be sorted in CS profile");
7401d5ae102SDimitry Andric       if (std::error_code EC = readFuncOffsetTable())
7411d5ae102SDimitry Andric         return EC;
7427fa27ce4SDimitry Andric     }
7431d5ae102SDimitry Andric     break;
744344a3780SDimitry Andric   case SecFuncMetadata: {
745b60736ecSDimitry Andric     ProfileIsProbeBased =
746b60736ecSDimitry Andric         hasSecFlag(Entry, SecFuncMetadataFlags::SecFlagIsProbeBased);
747b60736ecSDimitry Andric     FunctionSamples::ProfileIsProbeBased = ProfileIsProbeBased;
748344a3780SDimitry Andric     bool HasAttribute =
749344a3780SDimitry Andric         hasSecFlag(Entry, SecFuncMetadataFlags::SecFlagHasAttribute);
750344a3780SDimitry Andric     if (std::error_code EC = readFuncMetadata(HasAttribute))
751b60736ecSDimitry Andric       return EC;
752b60736ecSDimitry Andric     break;
753344a3780SDimitry Andric   }
754b60736ecSDimitry Andric   case SecProfileSymbolList:
755b60736ecSDimitry Andric     if (std::error_code EC = readProfileSymbolList())
756b60736ecSDimitry Andric       return EC;
757b60736ecSDimitry Andric     break;
7581d5ae102SDimitry Andric   default:
759b60736ecSDimitry Andric     if (std::error_code EC = readCustomSection(Entry))
760b60736ecSDimitry Andric       return EC;
7611d5ae102SDimitry Andric     break;
7621d5ae102SDimitry Andric   }
7631d5ae102SDimitry Andric   return sampleprof_error::success;
7641d5ae102SDimitry Andric }
7651d5ae102SDimitry Andric 
useFuncOffsetList() const7667fa27ce4SDimitry Andric bool SampleProfileReaderExtBinaryBase::useFuncOffsetList() const {
7677fa27ce4SDimitry Andric   // If profile is CS, the function offset section is expected to consist of
7687fa27ce4SDimitry Andric   // sequences of contexts in pre-order layout
7697fa27ce4SDimitry Andric   // (e.g. [A, A:1 @ B, A:1 @ B:2.3 @ C] [D, D:1 @ E]), so that when a matched
7707fa27ce4SDimitry Andric   // context in the module is found, the profiles of all its callees are
7717fa27ce4SDimitry Andric   // recursively loaded. A list is needed since the order of profiles matters.
7727fa27ce4SDimitry Andric   if (ProfileIsCS)
7737fa27ce4SDimitry Andric     return true;
7747fa27ce4SDimitry Andric 
7757fa27ce4SDimitry Andric   // If the profile is MD5, use the map container to lookup functions in
7767fa27ce4SDimitry Andric   // the module. A remapper has no use on MD5 names.
7777fa27ce4SDimitry Andric   if (useMD5())
7787fa27ce4SDimitry Andric     return false;
7797fa27ce4SDimitry Andric 
7807fa27ce4SDimitry Andric   // Profile is not MD5 and if a remapper is present, the remapped name of
7817fa27ce4SDimitry Andric   // every function needed to be matched against the module, so use the list
7827fa27ce4SDimitry Andric   // container since each entry is accessed.
7837fa27ce4SDimitry Andric   if (Remapper)
7847fa27ce4SDimitry Andric     return true;
7857fa27ce4SDimitry Andric 
7867fa27ce4SDimitry Andric   // Otherwise use the map container for faster lookup.
7877fa27ce4SDimitry Andric   // TODO: If the cardinality of the function offset section is much smaller
7887fa27ce4SDimitry Andric   // than the number of functions in the module, using the list container can
7897fa27ce4SDimitry Andric   // be always faster, but we need to figure out the constant factor to
7907fa27ce4SDimitry Andric   // determine the cutoff.
7917fa27ce4SDimitry Andric   return false;
7927fa27ce4SDimitry Andric }
7937fa27ce4SDimitry Andric 
7947fa27ce4SDimitry Andric 
collectFuncsFromModule()795344a3780SDimitry Andric bool SampleProfileReaderExtBinaryBase::collectFuncsFromModule() {
796344a3780SDimitry Andric   if (!M)
797344a3780SDimitry Andric     return false;
7981d5ae102SDimitry Andric   FuncsToUse.clear();
799344a3780SDimitry Andric   for (auto &F : *M)
8001d5ae102SDimitry Andric     FuncsToUse.insert(FunctionSamples::getCanonicalFnName(F));
801344a3780SDimitry Andric   return true;
8021d5ae102SDimitry Andric }
8031d5ae102SDimitry Andric 
readFuncOffsetTable()804b60736ecSDimitry Andric std::error_code SampleProfileReaderExtBinaryBase::readFuncOffsetTable() {
8057fa27ce4SDimitry Andric   // If there are more than one function offset section, the profile associated
8067fa27ce4SDimitry Andric   // with the previous section has to be done reading before next one is read.
807b60736ecSDimitry Andric   FuncOffsetTable.clear();
8087fa27ce4SDimitry Andric   FuncOffsetList.clear();
809b60736ecSDimitry Andric 
8101d5ae102SDimitry Andric   auto Size = readNumber<uint64_t>();
8111d5ae102SDimitry Andric   if (std::error_code EC = Size.getError())
8121d5ae102SDimitry Andric     return EC;
8131d5ae102SDimitry Andric 
8147fa27ce4SDimitry Andric   bool UseFuncOffsetList = useFuncOffsetList();
8157fa27ce4SDimitry Andric   if (UseFuncOffsetList)
8167fa27ce4SDimitry Andric     FuncOffsetList.reserve(*Size);
8177fa27ce4SDimitry Andric   else
8181d5ae102SDimitry Andric     FuncOffsetTable.reserve(*Size);
819c0981da4SDimitry Andric 
820e3b55780SDimitry Andric   for (uint64_t I = 0; I < *Size; ++I) {
821b1c73532SDimitry Andric     auto FContextHash(readSampleContextFromTable());
822b1c73532SDimitry Andric     if (std::error_code EC = FContextHash.getError())
8231d5ae102SDimitry Andric       return EC;
8241d5ae102SDimitry Andric 
825b1c73532SDimitry Andric     auto &[FContext, Hash] = *FContextHash;
8261d5ae102SDimitry Andric     auto Offset = readNumber<uint64_t>();
8271d5ae102SDimitry Andric     if (std::error_code EC = Offset.getError())
8281d5ae102SDimitry Andric       return EC;
8291d5ae102SDimitry Andric 
8307fa27ce4SDimitry Andric     if (UseFuncOffsetList)
831b1c73532SDimitry Andric       FuncOffsetList.emplace_back(FContext, *Offset);
8327fa27ce4SDimitry Andric     else
833b1c73532SDimitry Andric       // Because Porfiles replace existing value with new value if collision
834b1c73532SDimitry Andric       // happens, we also use the latest offset so that they are consistent.
835b1c73532SDimitry Andric       FuncOffsetTable[Hash] = *Offset;
8361d5ae102SDimitry Andric  }
837c0981da4SDimitry Andric 
8381d5ae102SDimitry Andric  return sampleprof_error::success;
8391d5ae102SDimitry Andric }
8401d5ae102SDimitry Andric 
readFuncProfiles()841b60736ecSDimitry Andric std::error_code SampleProfileReaderExtBinaryBase::readFuncProfiles() {
842344a3780SDimitry Andric   // Collect functions used by current module if the Reader has been
843344a3780SDimitry Andric   // given a module.
844344a3780SDimitry Andric   // collectFuncsFromModule uses FunctionSamples::getCanonicalFnName
845344a3780SDimitry Andric   // which will query FunctionSamples::HasUniqSuffix, so it has to be
846344a3780SDimitry Andric   // called after FunctionSamples::HasUniqSuffix is set, i.e. after
847344a3780SDimitry Andric   // NameTable section is read.
848344a3780SDimitry Andric   bool LoadFuncsToBeUsed = collectFuncsFromModule();
849344a3780SDimitry Andric 
8507fa27ce4SDimitry Andric   // When LoadFuncsToBeUsed is false, we are using LLVM tool, need to read all
8517fa27ce4SDimitry Andric   // profiles.
8521d5ae102SDimitry Andric   const uint8_t *Start = Data;
853344a3780SDimitry Andric   if (!LoadFuncsToBeUsed) {
8541d5ae102SDimitry Andric     while (Data < End) {
8551d5ae102SDimitry Andric       if (std::error_code EC = readFuncProfile(Data))
8561d5ae102SDimitry Andric         return EC;
8571d5ae102SDimitry Andric     }
8581d5ae102SDimitry Andric     assert(Data == End && "More data is read than expected");
859344a3780SDimitry Andric   } else {
860344a3780SDimitry Andric     // Load function profiles on demand.
8611d5ae102SDimitry Andric     if (Remapper) {
8621d5ae102SDimitry Andric       for (auto Name : FuncsToUse) {
8631d5ae102SDimitry Andric         Remapper->insert(Name);
8641d5ae102SDimitry Andric       }
8651d5ae102SDimitry Andric     }
8661d5ae102SDimitry Andric 
867145449b1SDimitry Andric     if (ProfileIsCS) {
8687fa27ce4SDimitry Andric       assert(useFuncOffsetList());
869c0981da4SDimitry Andric       DenseSet<uint64_t> FuncGuidsToUse;
870c0981da4SDimitry Andric       if (useMD5()) {
871c0981da4SDimitry Andric         for (auto Name : FuncsToUse)
872c0981da4SDimitry Andric           FuncGuidsToUse.insert(Function::getGUID(Name));
873c0981da4SDimitry Andric       }
874c0981da4SDimitry Andric 
875c0981da4SDimitry Andric       // For each function in current module, load all context profiles for
876c0981da4SDimitry Andric       // the function as well as their callee contexts which can help profile
877c0981da4SDimitry Andric       // guided importing for ThinLTO. This can be achieved by walking
878c0981da4SDimitry Andric       // through an ordered context container, where contexts are laid out
879c0981da4SDimitry Andric       // as if they were walked in preorder of a context trie. While
880c0981da4SDimitry Andric       // traversing the trie, a link to the highest common ancestor node is
881c0981da4SDimitry Andric       // kept so that all of its decendants will be loaded.
882c0981da4SDimitry Andric       const SampleContext *CommonContext = nullptr;
8837fa27ce4SDimitry Andric       for (const auto &NameOffset : FuncOffsetList) {
884c0981da4SDimitry Andric         const auto &FContext = NameOffset.first;
885b1c73532SDimitry Andric         FunctionId FName = FContext.getFunction();
886b1c73532SDimitry Andric         StringRef FNameString;
887b1c73532SDimitry Andric         if (!useMD5())
888b1c73532SDimitry Andric           FNameString = FName.stringRef();
889b1c73532SDimitry Andric 
890c0981da4SDimitry Andric         // For function in the current module, keep its farthest ancestor
891c0981da4SDimitry Andric         // context. This can be used to load itself and its child and
892c0981da4SDimitry Andric         // sibling contexts.
893b1c73532SDimitry Andric         if ((useMD5() && FuncGuidsToUse.count(FName.getHashCode())) ||
894b1c73532SDimitry Andric             (!useMD5() && (FuncsToUse.count(FNameString) ||
895b1c73532SDimitry Andric                            (Remapper && Remapper->exist(FNameString))))) {
896ac9a064cSDimitry Andric           if (!CommonContext || !CommonContext->isPrefixOf(FContext))
897c0981da4SDimitry Andric             CommonContext = &FContext;
898c0981da4SDimitry Andric         }
899c0981da4SDimitry Andric 
900c0981da4SDimitry Andric         if (CommonContext == &FContext ||
901ac9a064cSDimitry Andric             (CommonContext && CommonContext->isPrefixOf(FContext))) {
902c0981da4SDimitry Andric           // Load profile for the current context which originated from
903c0981da4SDimitry Andric           // the common ancestor.
904c0981da4SDimitry Andric           const uint8_t *FuncProfileAddr = Start + NameOffset.second;
905c0981da4SDimitry Andric           if (std::error_code EC = readFuncProfile(FuncProfileAddr))
906c0981da4SDimitry Andric             return EC;
907c0981da4SDimitry Andric         }
908c0981da4SDimitry Andric       }
9097fa27ce4SDimitry Andric     } else if (useMD5()) {
9107fa27ce4SDimitry Andric       assert(!useFuncOffsetList());
911cfca06d7SDimitry Andric       for (auto Name : FuncsToUse) {
912b1c73532SDimitry Andric         auto GUID = MD5Hash(Name);
913b1c73532SDimitry Andric         auto iter = FuncOffsetTable.find(GUID);
914cfca06d7SDimitry Andric         if (iter == FuncOffsetTable.end())
915cfca06d7SDimitry Andric           continue;
916cfca06d7SDimitry Andric         const uint8_t *FuncProfileAddr = Start + iter->second;
9177fa27ce4SDimitry Andric         if (std::error_code EC = readFuncProfile(FuncProfileAddr))
9187fa27ce4SDimitry Andric           return EC;
9197fa27ce4SDimitry Andric       }
9207fa27ce4SDimitry Andric     } else if (Remapper) {
9217fa27ce4SDimitry Andric       assert(useFuncOffsetList());
9227fa27ce4SDimitry Andric       for (auto NameOffset : FuncOffsetList) {
9237fa27ce4SDimitry Andric         SampleContext FContext(NameOffset.first);
924b1c73532SDimitry Andric         auto FuncName = FContext.getFunction();
925b1c73532SDimitry Andric         StringRef FuncNameStr = FuncName.stringRef();
926b1c73532SDimitry Andric         if (!FuncsToUse.count(FuncNameStr) && !Remapper->exist(FuncNameStr))
9277fa27ce4SDimitry Andric           continue;
9287fa27ce4SDimitry Andric         const uint8_t *FuncProfileAddr = Start + NameOffset.second;
929cfca06d7SDimitry Andric         if (std::error_code EC = readFuncProfile(FuncProfileAddr))
930cfca06d7SDimitry Andric           return EC;
931cfca06d7SDimitry Andric       }
932cfca06d7SDimitry Andric     } else {
9337fa27ce4SDimitry Andric       assert(!useFuncOffsetList());
9347fa27ce4SDimitry Andric       for (auto Name : FuncsToUse) {
935b1c73532SDimitry Andric         auto iter = FuncOffsetTable.find(MD5Hash(Name));
9367fa27ce4SDimitry Andric         if (iter == FuncOffsetTable.end())
9371d5ae102SDimitry Andric           continue;
9387fa27ce4SDimitry Andric         const uint8_t *FuncProfileAddr = Start + iter->second;
9391d5ae102SDimitry Andric         if (std::error_code EC = readFuncProfile(FuncProfileAddr))
9401d5ae102SDimitry Andric           return EC;
9411d5ae102SDimitry Andric       }
942cfca06d7SDimitry Andric     }
9431d5ae102SDimitry Andric     Data = End;
944344a3780SDimitry Andric   }
945344a3780SDimitry Andric   assert((CSProfileCount == 0 || CSProfileCount == Profiles.size()) &&
946344a3780SDimitry Andric          "Cannot have both context-sensitive and regular profile");
947145449b1SDimitry Andric   assert((!CSProfileCount || ProfileIsCS) &&
948344a3780SDimitry Andric          "Section flag should be consistent with actual profile");
9491d5ae102SDimitry Andric   return sampleprof_error::success;
9501d5ae102SDimitry Andric }
9511d5ae102SDimitry Andric 
readProfileSymbolList()952b60736ecSDimitry Andric std::error_code SampleProfileReaderExtBinaryBase::readProfileSymbolList() {
9531d5ae102SDimitry Andric   if (!ProfSymList)
9541d5ae102SDimitry Andric     ProfSymList = std::make_unique<ProfileSymbolList>();
9551d5ae102SDimitry Andric 
9561d5ae102SDimitry Andric   if (std::error_code EC = ProfSymList->read(Data, End - Data))
9571d5ae102SDimitry Andric     return EC;
9581d5ae102SDimitry Andric 
9591d5ae102SDimitry Andric   Data = End;
9601d5ae102SDimitry Andric   return sampleprof_error::success;
9611d5ae102SDimitry Andric }
9621d5ae102SDimitry Andric 
decompressSection(const uint8_t * SecStart,const uint64_t SecSize,const uint8_t * & DecompressBuf,uint64_t & DecompressBufSize)9631d5ae102SDimitry Andric std::error_code SampleProfileReaderExtBinaryBase::decompressSection(
9641d5ae102SDimitry Andric     const uint8_t *SecStart, const uint64_t SecSize,
9651d5ae102SDimitry Andric     const uint8_t *&DecompressBuf, uint64_t &DecompressBufSize) {
9661d5ae102SDimitry Andric   Data = SecStart;
9671d5ae102SDimitry Andric   End = SecStart + SecSize;
9681d5ae102SDimitry Andric   auto DecompressSize = readNumber<uint64_t>();
9691d5ae102SDimitry Andric   if (std::error_code EC = DecompressSize.getError())
9701d5ae102SDimitry Andric     return EC;
9711d5ae102SDimitry Andric   DecompressBufSize = *DecompressSize;
9721d5ae102SDimitry Andric 
9731d5ae102SDimitry Andric   auto CompressSize = readNumber<uint64_t>();
9741d5ae102SDimitry Andric   if (std::error_code EC = CompressSize.getError())
9751d5ae102SDimitry Andric     return EC;
9761d5ae102SDimitry Andric 
9771f917f69SDimitry Andric   if (!llvm::compression::zlib::isAvailable())
9781d5ae102SDimitry Andric     return sampleprof_error::zlib_unavailable;
9791d5ae102SDimitry Andric 
9801f917f69SDimitry Andric   uint8_t *Buffer = Allocator.Allocate<uint8_t>(DecompressBufSize);
9811d5ae102SDimitry Andric   size_t UCSize = DecompressBufSize;
982e3b55780SDimitry Andric   llvm::Error E = compression::zlib::decompress(ArrayRef(Data, *CompressSize),
983e3b55780SDimitry Andric                                                 Buffer, UCSize);
9841d5ae102SDimitry Andric   if (E)
9851d5ae102SDimitry Andric     return sampleprof_error::uncompress_failed;
9861d5ae102SDimitry Andric   DecompressBuf = reinterpret_cast<const uint8_t *>(Buffer);
9871d5ae102SDimitry Andric   return sampleprof_error::success;
9881d5ae102SDimitry Andric }
9891d5ae102SDimitry Andric 
readImpl()9901d5ae102SDimitry Andric std::error_code SampleProfileReaderExtBinaryBase::readImpl() {
9911d5ae102SDimitry Andric   const uint8_t *BufStart =
9921d5ae102SDimitry Andric       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
9931d5ae102SDimitry Andric 
9941d5ae102SDimitry Andric   for (auto &Entry : SecHdrTable) {
9951d5ae102SDimitry Andric     // Skip empty section.
9961d5ae102SDimitry Andric     if (!Entry.Size)
9971d5ae102SDimitry Andric       continue;
9981d5ae102SDimitry Andric 
999b60736ecSDimitry Andric     // Skip sections without context when SkipFlatProf is true.
1000b60736ecSDimitry Andric     if (SkipFlatProf && hasSecFlag(Entry, SecCommonFlags::SecFlagFlat))
1001b60736ecSDimitry Andric       continue;
1002b60736ecSDimitry Andric 
10031d5ae102SDimitry Andric     const uint8_t *SecStart = BufStart + Entry.Offset;
10041d5ae102SDimitry Andric     uint64_t SecSize = Entry.Size;
10051d5ae102SDimitry Andric 
10061d5ae102SDimitry Andric     // If the section is compressed, decompress it into a buffer
10071d5ae102SDimitry Andric     // DecompressBuf before reading the actual data. The pointee of
10081d5ae102SDimitry Andric     // 'Data' will be changed to buffer hold by DecompressBuf
10091d5ae102SDimitry Andric     // temporarily when reading the actual data.
1010cfca06d7SDimitry Andric     bool isCompressed = hasSecFlag(Entry, SecCommonFlags::SecFlagCompress);
10111d5ae102SDimitry Andric     if (isCompressed) {
10121d5ae102SDimitry Andric       const uint8_t *DecompressBuf;
10131d5ae102SDimitry Andric       uint64_t DecompressBufSize;
10141d5ae102SDimitry Andric       if (std::error_code EC = decompressSection(
10151d5ae102SDimitry Andric               SecStart, SecSize, DecompressBuf, DecompressBufSize))
10161d5ae102SDimitry Andric         return EC;
10171d5ae102SDimitry Andric       SecStart = DecompressBuf;
10181d5ae102SDimitry Andric       SecSize = DecompressBufSize;
10191d5ae102SDimitry Andric     }
10201d5ae102SDimitry Andric 
1021cfca06d7SDimitry Andric     if (std::error_code EC = readOneSection(SecStart, SecSize, Entry))
10221d5ae102SDimitry Andric       return EC;
10231d5ae102SDimitry Andric     if (Data != SecStart + SecSize)
10241d5ae102SDimitry Andric       return sampleprof_error::malformed;
10251d5ae102SDimitry Andric 
10261d5ae102SDimitry Andric     // Change the pointee of 'Data' from DecompressBuf to original Buffer.
10271d5ae102SDimitry Andric     if (isCompressed) {
10281d5ae102SDimitry Andric       Data = BufStart + Entry.Offset;
10291d5ae102SDimitry Andric       End = BufStart + Buffer->getBufferSize();
10301d5ae102SDimitry Andric     }
10311d5ae102SDimitry Andric   }
10321d5ae102SDimitry Andric 
10331d5ae102SDimitry Andric   return sampleprof_error::success;
10341d5ae102SDimitry Andric }
10351d5ae102SDimitry Andric 
verifySPMagic(uint64_t Magic)1036eb11fae6SDimitry Andric std::error_code SampleProfileReaderRawBinary::verifySPMagic(uint64_t Magic) {
1037eb11fae6SDimitry Andric   if (Magic == SPMagic())
1038eb11fae6SDimitry Andric     return sampleprof_error::success;
103967c32a98SDimitry Andric   return sampleprof_error::bad_magic;
1040eb11fae6SDimitry Andric }
104167c32a98SDimitry Andric 
verifySPMagic(uint64_t Magic)10421d5ae102SDimitry Andric std::error_code SampleProfileReaderExtBinary::verifySPMagic(uint64_t Magic) {
10431d5ae102SDimitry Andric   if (Magic == SPMagic(SPF_Ext_Binary))
10441d5ae102SDimitry Andric     return sampleprof_error::success;
10451d5ae102SDimitry Andric   return sampleprof_error::bad_magic;
10461d5ae102SDimitry Andric }
10471d5ae102SDimitry Andric 
readNameTable()10481d5ae102SDimitry Andric std::error_code SampleProfileReaderBinary::readNameTable() {
10497fa27ce4SDimitry Andric   auto Size = readNumber<size_t>();
1050dd58ef01SDimitry Andric   if (std::error_code EC = Size.getError())
1051dd58ef01SDimitry Andric     return EC;
10527fa27ce4SDimitry Andric 
10537fa27ce4SDimitry Andric   // Normally if useMD5 is true, the name table should have MD5 values, not
10547fa27ce4SDimitry Andric   // strings, however in the case that ExtBinary profile has multiple name
10557fa27ce4SDimitry Andric   // tables mixing string and MD5, all of them have to be normalized to use MD5,
10567fa27ce4SDimitry Andric   // because optimization passes can only handle either type.
10577fa27ce4SDimitry Andric   bool UseMD5 = useMD5();
10587fa27ce4SDimitry Andric 
10597fa27ce4SDimitry Andric   NameTable.clear();
10607fa27ce4SDimitry Andric   NameTable.reserve(*Size);
1061b1c73532SDimitry Andric   if (!ProfileIsCS) {
1062b1c73532SDimitry Andric     MD5SampleContextTable.clear();
1063b1c73532SDimitry Andric     if (UseMD5)
1064b1c73532SDimitry Andric       MD5SampleContextTable.reserve(*Size);
1065b1c73532SDimitry Andric     else
1066b1c73532SDimitry Andric       // If we are using strings, delay MD5 computation since only a portion of
1067b1c73532SDimitry Andric       // names are used by top level functions. Use 0 to indicate MD5 value is
1068b1c73532SDimitry Andric       // to be calculated as no known string has a MD5 value of 0.
1069b1c73532SDimitry Andric       MD5SampleContextTable.resize(*Size);
1070b1c73532SDimitry Andric   }
10717fa27ce4SDimitry Andric   for (size_t I = 0; I < *Size; ++I) {
1072dd58ef01SDimitry Andric     auto Name(readString());
1073dd58ef01SDimitry Andric     if (std::error_code EC = Name.getError())
1074dd58ef01SDimitry Andric       return EC;
10757fa27ce4SDimitry Andric     if (UseMD5) {
1076b1c73532SDimitry Andric       FunctionId FID(*Name);
1077b1c73532SDimitry Andric       if (!ProfileIsCS)
1078b1c73532SDimitry Andric         MD5SampleContextTable.emplace_back(FID.getHashCode());
1079b1c73532SDimitry Andric       NameTable.emplace_back(FID);
10807fa27ce4SDimitry Andric     } else
1081b1c73532SDimitry Andric       NameTable.push_back(FunctionId(*Name));
1082dd58ef01SDimitry Andric   }
1083b1c73532SDimitry Andric   if (!ProfileIsCS)
1084b1c73532SDimitry Andric     MD5SampleContextStart = MD5SampleContextTable.data();
108567c32a98SDimitry Andric   return sampleprof_error::success;
108667c32a98SDimitry Andric }
108767c32a98SDimitry Andric 
10887fa27ce4SDimitry Andric std::error_code
readNameTableSec(bool IsMD5,bool FixedLengthMD5)10897fa27ce4SDimitry Andric SampleProfileReaderExtBinaryBase::readNameTableSec(bool IsMD5,
10907fa27ce4SDimitry Andric                                                    bool FixedLengthMD5) {
10917fa27ce4SDimitry Andric   if (FixedLengthMD5) {
10927fa27ce4SDimitry Andric     if (!IsMD5)
10937fa27ce4SDimitry Andric       errs() << "If FixedLengthMD5 is true, UseMD5 has to be true";
10947fa27ce4SDimitry Andric     auto Size = readNumber<size_t>();
1095cfca06d7SDimitry Andric     if (std::error_code EC = Size.getError())
1096cfca06d7SDimitry Andric       return EC;
10977fa27ce4SDimitry Andric 
10987fa27ce4SDimitry Andric     assert(Data + (*Size) * sizeof(uint64_t) == End &&
10997fa27ce4SDimitry Andric            "Fixed length MD5 name table does not contain specified number of "
11007fa27ce4SDimitry Andric            "entries");
11017fa27ce4SDimitry Andric     if (Data + (*Size) * sizeof(uint64_t) > End)
11027fa27ce4SDimitry Andric       return sampleprof_error::truncated;
11037fa27ce4SDimitry Andric 
11047fa27ce4SDimitry Andric     NameTable.clear();
1105b1c73532SDimitry Andric     NameTable.reserve(*Size);
1106b1c73532SDimitry Andric     for (size_t I = 0; I < *Size; ++I) {
1107b1c73532SDimitry Andric       using namespace support;
1108b1c73532SDimitry Andric       uint64_t FID = endian::read<uint64_t, endianness::little, unaligned>(
1109b1c73532SDimitry Andric           Data + I * sizeof(uint64_t));
1110b1c73532SDimitry Andric       NameTable.emplace_back(FunctionId(FID));
1111b1c73532SDimitry Andric     }
1112b1c73532SDimitry Andric     if (!ProfileIsCS)
1113b1c73532SDimitry Andric       MD5SampleContextStart = reinterpret_cast<const uint64_t *>(Data);
1114b60736ecSDimitry Andric     Data = Data + (*Size) * sizeof(uint64_t);
1115b60736ecSDimitry Andric     return sampleprof_error::success;
1116b60736ecSDimitry Andric   }
11177fa27ce4SDimitry Andric 
11187fa27ce4SDimitry Andric   if (IsMD5) {
11197fa27ce4SDimitry Andric     assert(!FixedLengthMD5 && "FixedLengthMD5 should be unreachable here");
11207fa27ce4SDimitry Andric     auto Size = readNumber<size_t>();
11217fa27ce4SDimitry Andric     if (std::error_code EC = Size.getError())
11227fa27ce4SDimitry Andric       return EC;
11237fa27ce4SDimitry Andric 
11247fa27ce4SDimitry Andric     NameTable.clear();
1125b60736ecSDimitry Andric     NameTable.reserve(*Size);
1126b1c73532SDimitry Andric     if (!ProfileIsCS)
1127b1c73532SDimitry Andric       MD5SampleContextTable.resize(*Size);
11287fa27ce4SDimitry Andric     for (size_t I = 0; I < *Size; ++I) {
1129cfca06d7SDimitry Andric       auto FID = readNumber<uint64_t>();
1130cfca06d7SDimitry Andric       if (std::error_code EC = FID.getError())
1131cfca06d7SDimitry Andric         return EC;
1132b1c73532SDimitry Andric       if (!ProfileIsCS)
1133b1c73532SDimitry Andric         support::endian::write64le(&MD5SampleContextTable[I], *FID);
1134b1c73532SDimitry Andric       NameTable.emplace_back(FunctionId(*FID));
1135cfca06d7SDimitry Andric     }
1136b1c73532SDimitry Andric     if (!ProfileIsCS)
1137b1c73532SDimitry Andric       MD5SampleContextStart = MD5SampleContextTable.data();
1138cfca06d7SDimitry Andric     return sampleprof_error::success;
1139cfca06d7SDimitry Andric   }
1140cfca06d7SDimitry Andric 
1141cfca06d7SDimitry Andric   return SampleProfileReaderBinary::readNameTable();
1142cfca06d7SDimitry Andric }
1143cfca06d7SDimitry Andric 
1144c0981da4SDimitry Andric // Read in the CS name table section, which basically contains a list of context
1145c0981da4SDimitry Andric // vectors. Each element of a context vector, aka a frame, refers to the
1146c0981da4SDimitry Andric // underlying raw function names that are stored in the name table, as well as
1147c0981da4SDimitry Andric // a callsite identifier that only makes sense for non-leaf frames.
readCSNameTableSec()1148c0981da4SDimitry Andric std::error_code SampleProfileReaderExtBinaryBase::readCSNameTableSec() {
11497fa27ce4SDimitry Andric   auto Size = readNumber<size_t>();
1150c0981da4SDimitry Andric   if (std::error_code EC = Size.getError())
1151c0981da4SDimitry Andric     return EC;
1152c0981da4SDimitry Andric 
11537fa27ce4SDimitry Andric   CSNameTable.clear();
11547fa27ce4SDimitry Andric   CSNameTable.reserve(*Size);
1155b1c73532SDimitry Andric   if (ProfileIsCS) {
1156b1c73532SDimitry Andric     // Delay MD5 computation of CS context until they are needed. Use 0 to
1157b1c73532SDimitry Andric     // indicate MD5 value is to be calculated as no known string has a MD5
1158b1c73532SDimitry Andric     // value of 0.
1159b1c73532SDimitry Andric     MD5SampleContextTable.clear();
1160b1c73532SDimitry Andric     MD5SampleContextTable.resize(*Size);
1161b1c73532SDimitry Andric     MD5SampleContextStart = MD5SampleContextTable.data();
1162b1c73532SDimitry Andric   }
11637fa27ce4SDimitry Andric   for (size_t I = 0; I < *Size; ++I) {
11647fa27ce4SDimitry Andric     CSNameTable.emplace_back(SampleContextFrameVector());
1165c0981da4SDimitry Andric     auto ContextSize = readNumber<uint32_t>();
1166c0981da4SDimitry Andric     if (std::error_code EC = ContextSize.getError())
1167c0981da4SDimitry Andric       return EC;
1168c0981da4SDimitry Andric     for (uint32_t J = 0; J < *ContextSize; ++J) {
1169b60736ecSDimitry Andric       auto FName(readStringFromTable());
1170b60736ecSDimitry Andric       if (std::error_code EC = FName.getError())
1171b60736ecSDimitry Andric         return EC;
1172c0981da4SDimitry Andric       auto LineOffset = readNumber<uint64_t>();
1173c0981da4SDimitry Andric       if (std::error_code EC = LineOffset.getError())
1174c0981da4SDimitry Andric         return EC;
1175b60736ecSDimitry Andric 
1176c0981da4SDimitry Andric       if (!isOffsetLegal(*LineOffset))
1177c0981da4SDimitry Andric         return std::error_code();
1178344a3780SDimitry Andric 
1179c0981da4SDimitry Andric       auto Discriminator = readNumber<uint64_t>();
1180c0981da4SDimitry Andric       if (std::error_code EC = Discriminator.getError())
1181c0981da4SDimitry Andric         return EC;
1182c0981da4SDimitry Andric 
11837fa27ce4SDimitry Andric       CSNameTable.back().emplace_back(
1184c0981da4SDimitry Andric           FName.get(), LineLocation(LineOffset.get(), Discriminator.get()));
1185c0981da4SDimitry Andric     }
1186c0981da4SDimitry Andric   }
1187c0981da4SDimitry Andric 
1188c0981da4SDimitry Andric   return sampleprof_error::success;
1189c0981da4SDimitry Andric }
1190c0981da4SDimitry Andric 
1191c0981da4SDimitry Andric std::error_code
readFuncMetadata(bool ProfileHasAttribute,FunctionSamples * FProfile)119277fc4c14SDimitry Andric SampleProfileReaderExtBinaryBase::readFuncMetadata(bool ProfileHasAttribute,
119377fc4c14SDimitry Andric                                                    FunctionSamples *FProfile) {
119477fc4c14SDimitry Andric   if (Data < End) {
1195344a3780SDimitry Andric     if (ProfileIsProbeBased) {
1196b60736ecSDimitry Andric       auto Checksum = readNumber<uint64_t>();
1197b60736ecSDimitry Andric       if (std::error_code EC = Checksum.getError())
1198b60736ecSDimitry Andric         return EC;
119977fc4c14SDimitry Andric       if (FProfile)
120077fc4c14SDimitry Andric         FProfile->setFunctionHash(*Checksum);
1201b60736ecSDimitry Andric     }
1202344a3780SDimitry Andric 
1203344a3780SDimitry Andric     if (ProfileHasAttribute) {
1204344a3780SDimitry Andric       auto Attributes = readNumber<uint32_t>();
1205344a3780SDimitry Andric       if (std::error_code EC = Attributes.getError())
1206344a3780SDimitry Andric         return EC;
120777fc4c14SDimitry Andric       if (FProfile)
120877fc4c14SDimitry Andric         FProfile->getContext().setAllAttributes(*Attributes);
1209344a3780SDimitry Andric     }
121077fc4c14SDimitry Andric 
1211145449b1SDimitry Andric     if (!ProfileIsCS) {
121277fc4c14SDimitry Andric       // Read all the attributes for inlined function calls.
121377fc4c14SDimitry Andric       auto NumCallsites = readNumber<uint32_t>();
121477fc4c14SDimitry Andric       if (std::error_code EC = NumCallsites.getError())
121577fc4c14SDimitry Andric         return EC;
121677fc4c14SDimitry Andric 
121777fc4c14SDimitry Andric       for (uint32_t J = 0; J < *NumCallsites; ++J) {
121877fc4c14SDimitry Andric         auto LineOffset = readNumber<uint64_t>();
121977fc4c14SDimitry Andric         if (std::error_code EC = LineOffset.getError())
122077fc4c14SDimitry Andric           return EC;
122177fc4c14SDimitry Andric 
122277fc4c14SDimitry Andric         auto Discriminator = readNumber<uint64_t>();
122377fc4c14SDimitry Andric         if (std::error_code EC = Discriminator.getError())
122477fc4c14SDimitry Andric           return EC;
122577fc4c14SDimitry Andric 
1226b1c73532SDimitry Andric         auto FContextHash(readSampleContextFromTable());
1227b1c73532SDimitry Andric         if (std::error_code EC = FContextHash.getError())
122877fc4c14SDimitry Andric           return EC;
122977fc4c14SDimitry Andric 
1230b1c73532SDimitry Andric         auto &[FContext, Hash] = *FContextHash;
123177fc4c14SDimitry Andric         FunctionSamples *CalleeProfile = nullptr;
123277fc4c14SDimitry Andric         if (FProfile) {
123377fc4c14SDimitry Andric           CalleeProfile = const_cast<FunctionSamples *>(
123477fc4c14SDimitry Andric               &FProfile->functionSamplesAt(LineLocation(
123577fc4c14SDimitry Andric                   *LineOffset,
1236b1c73532SDimitry Andric                   *Discriminator))[FContext.getFunction()]);
123777fc4c14SDimitry Andric         }
123877fc4c14SDimitry Andric         if (std::error_code EC =
123977fc4c14SDimitry Andric                 readFuncMetadata(ProfileHasAttribute, CalleeProfile))
124077fc4c14SDimitry Andric           return EC;
124177fc4c14SDimitry Andric       }
124277fc4c14SDimitry Andric     }
124377fc4c14SDimitry Andric   }
124477fc4c14SDimitry Andric 
124577fc4c14SDimitry Andric   return sampleprof_error::success;
124677fc4c14SDimitry Andric }
124777fc4c14SDimitry Andric 
124877fc4c14SDimitry Andric std::error_code
readFuncMetadata(bool ProfileHasAttribute)124977fc4c14SDimitry Andric SampleProfileReaderExtBinaryBase::readFuncMetadata(bool ProfileHasAttribute) {
125077fc4c14SDimitry Andric   while (Data < End) {
1251b1c73532SDimitry Andric     auto FContextHash(readSampleContextFromTable());
1252b1c73532SDimitry Andric     if (std::error_code EC = FContextHash.getError())
125377fc4c14SDimitry Andric       return EC;
1254b1c73532SDimitry Andric     auto &[FContext, Hash] = *FContextHash;
125577fc4c14SDimitry Andric     FunctionSamples *FProfile = nullptr;
1256b1c73532SDimitry Andric     auto It = Profiles.find(FContext);
125777fc4c14SDimitry Andric     if (It != Profiles.end())
125877fc4c14SDimitry Andric       FProfile = &It->second;
125977fc4c14SDimitry Andric 
126077fc4c14SDimitry Andric     if (std::error_code EC = readFuncMetadata(ProfileHasAttribute, FProfile))
126177fc4c14SDimitry Andric       return EC;
1262344a3780SDimitry Andric   }
1263344a3780SDimitry Andric 
1264344a3780SDimitry Andric   assert(Data == End && "More data is read than expected");
1265b60736ecSDimitry Andric   return sampleprof_error::success;
1266b60736ecSDimitry Andric }
1267b60736ecSDimitry Andric 
1268b60736ecSDimitry Andric std::error_code
readSecHdrTableEntry(uint64_t Idx)12697fa27ce4SDimitry Andric SampleProfileReaderExtBinaryBase::readSecHdrTableEntry(uint64_t Idx) {
12701d5ae102SDimitry Andric   SecHdrTableEntry Entry;
12711d5ae102SDimitry Andric   auto Type = readUnencodedNumber<uint64_t>();
12721d5ae102SDimitry Andric   if (std::error_code EC = Type.getError())
12731d5ae102SDimitry Andric     return EC;
12741d5ae102SDimitry Andric   Entry.Type = static_cast<SecType>(*Type);
1275eb11fae6SDimitry Andric 
12761d5ae102SDimitry Andric   auto Flags = readUnencodedNumber<uint64_t>();
12771d5ae102SDimitry Andric   if (std::error_code EC = Flags.getError())
12781d5ae102SDimitry Andric     return EC;
12791d5ae102SDimitry Andric   Entry.Flags = *Flags;
12801d5ae102SDimitry Andric 
12811d5ae102SDimitry Andric   auto Offset = readUnencodedNumber<uint64_t>();
12821d5ae102SDimitry Andric   if (std::error_code EC = Offset.getError())
12831d5ae102SDimitry Andric     return EC;
12841d5ae102SDimitry Andric   Entry.Offset = *Offset;
12851d5ae102SDimitry Andric 
12861d5ae102SDimitry Andric   auto Size = readUnencodedNumber<uint64_t>();
12871d5ae102SDimitry Andric   if (std::error_code EC = Size.getError())
12881d5ae102SDimitry Andric     return EC;
12891d5ae102SDimitry Andric   Entry.Size = *Size;
12901d5ae102SDimitry Andric 
1291b60736ecSDimitry Andric   Entry.LayoutIndex = Idx;
12921d5ae102SDimitry Andric   SecHdrTable.push_back(std::move(Entry));
12931d5ae102SDimitry Andric   return sampleprof_error::success;
12941d5ae102SDimitry Andric }
12951d5ae102SDimitry Andric 
readSecHdrTable()12961d5ae102SDimitry Andric std::error_code SampleProfileReaderExtBinaryBase::readSecHdrTable() {
12971d5ae102SDimitry Andric   auto EntryNum = readUnencodedNumber<uint64_t>();
12981d5ae102SDimitry Andric   if (std::error_code EC = EntryNum.getError())
12991d5ae102SDimitry Andric     return EC;
13001d5ae102SDimitry Andric 
1301e3b55780SDimitry Andric   for (uint64_t i = 0; i < (*EntryNum); i++)
1302b60736ecSDimitry Andric     if (std::error_code EC = readSecHdrTableEntry(i))
13031d5ae102SDimitry Andric       return EC;
13041d5ae102SDimitry Andric 
13051d5ae102SDimitry Andric   return sampleprof_error::success;
13061d5ae102SDimitry Andric }
13071d5ae102SDimitry Andric 
readHeader()13081d5ae102SDimitry Andric std::error_code SampleProfileReaderExtBinaryBase::readHeader() {
13091d5ae102SDimitry Andric   const uint8_t *BufStart =
13101d5ae102SDimitry Andric       reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
13111d5ae102SDimitry Andric   Data = BufStart;
13121d5ae102SDimitry Andric   End = BufStart + Buffer->getBufferSize();
13131d5ae102SDimitry Andric 
13141d5ae102SDimitry Andric   if (std::error_code EC = readMagicIdent())
13151d5ae102SDimitry Andric     return EC;
13161d5ae102SDimitry Andric 
13171d5ae102SDimitry Andric   if (std::error_code EC = readSecHdrTable())
13181d5ae102SDimitry Andric     return EC;
13191d5ae102SDimitry Andric 
13201d5ae102SDimitry Andric   return sampleprof_error::success;
13211d5ae102SDimitry Andric }
13221d5ae102SDimitry Andric 
getSectionSize(SecType Type)13231d5ae102SDimitry Andric uint64_t SampleProfileReaderExtBinaryBase::getSectionSize(SecType Type) {
1324b60736ecSDimitry Andric   uint64_t Size = 0;
13251d5ae102SDimitry Andric   for (auto &Entry : SecHdrTable) {
13261d5ae102SDimitry Andric     if (Entry.Type == Type)
1327b60736ecSDimitry Andric       Size += Entry.Size;
13281d5ae102SDimitry Andric   }
1329b60736ecSDimitry Andric   return Size;
13301d5ae102SDimitry Andric }
13311d5ae102SDimitry Andric 
getFileSize()13321d5ae102SDimitry Andric uint64_t SampleProfileReaderExtBinaryBase::getFileSize() {
13331d5ae102SDimitry Andric   // Sections in SecHdrTable is not necessarily in the same order as
13341d5ae102SDimitry Andric   // sections in the profile because section like FuncOffsetTable needs
13351d5ae102SDimitry Andric   // to be written after section LBRProfile but needs to be read before
13361d5ae102SDimitry Andric   // section LBRProfile, so we cannot simply use the last entry in
13371d5ae102SDimitry Andric   // SecHdrTable to calculate the file size.
13381d5ae102SDimitry Andric   uint64_t FileSize = 0;
13391d5ae102SDimitry Andric   for (auto &Entry : SecHdrTable) {
13401d5ae102SDimitry Andric     FileSize = std::max(Entry.Offset + Entry.Size, FileSize);
13411d5ae102SDimitry Andric   }
13421d5ae102SDimitry Andric   return FileSize;
13431d5ae102SDimitry Andric }
13441d5ae102SDimitry Andric 
getSecFlagsStr(const SecHdrTableEntry & Entry)1345cfca06d7SDimitry Andric static std::string getSecFlagsStr(const SecHdrTableEntry &Entry) {
1346cfca06d7SDimitry Andric   std::string Flags;
1347cfca06d7SDimitry Andric   if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress))
1348cfca06d7SDimitry Andric     Flags.append("{compressed,");
1349cfca06d7SDimitry Andric   else
1350cfca06d7SDimitry Andric     Flags.append("{");
1351cfca06d7SDimitry Andric 
1352b60736ecSDimitry Andric   if (hasSecFlag(Entry, SecCommonFlags::SecFlagFlat))
1353b60736ecSDimitry Andric     Flags.append("flat,");
1354b60736ecSDimitry Andric 
1355cfca06d7SDimitry Andric   switch (Entry.Type) {
1356cfca06d7SDimitry Andric   case SecNameTable:
1357b60736ecSDimitry Andric     if (hasSecFlag(Entry, SecNameTableFlags::SecFlagFixedLengthMD5))
1358b60736ecSDimitry Andric       Flags.append("fixlenmd5,");
1359b60736ecSDimitry Andric     else if (hasSecFlag(Entry, SecNameTableFlags::SecFlagMD5Name))
1360cfca06d7SDimitry Andric       Flags.append("md5,");
1361344a3780SDimitry Andric     if (hasSecFlag(Entry, SecNameTableFlags::SecFlagUniqSuffix))
1362344a3780SDimitry Andric       Flags.append("uniq,");
1363cfca06d7SDimitry Andric     break;
1364cfca06d7SDimitry Andric   case SecProfSummary:
1365cfca06d7SDimitry Andric     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagPartial))
1366cfca06d7SDimitry Andric       Flags.append("partial,");
1367344a3780SDimitry Andric     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFullContext))
1368344a3780SDimitry Andric       Flags.append("context,");
1369145449b1SDimitry Andric     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagIsPreInlined))
1370145449b1SDimitry Andric       Flags.append("preInlined,");
1371344a3780SDimitry Andric     if (hasSecFlag(Entry, SecProfSummaryFlags::SecFlagFSDiscriminator))
1372344a3780SDimitry Andric       Flags.append("fs-discriminator,");
1373cfca06d7SDimitry Andric     break;
1374c0981da4SDimitry Andric   case SecFuncOffsetTable:
1375c0981da4SDimitry Andric     if (hasSecFlag(Entry, SecFuncOffsetFlags::SecFlagOrdered))
1376c0981da4SDimitry Andric       Flags.append("ordered,");
1377c0981da4SDimitry Andric     break;
1378c0981da4SDimitry Andric   case SecFuncMetadata:
1379c0981da4SDimitry Andric     if (hasSecFlag(Entry, SecFuncMetadataFlags::SecFlagIsProbeBased))
1380c0981da4SDimitry Andric       Flags.append("probe,");
1381c0981da4SDimitry Andric     if (hasSecFlag(Entry, SecFuncMetadataFlags::SecFlagHasAttribute))
1382c0981da4SDimitry Andric       Flags.append("attr,");
1383c0981da4SDimitry Andric     break;
1384cfca06d7SDimitry Andric   default:
1385cfca06d7SDimitry Andric     break;
1386cfca06d7SDimitry Andric   }
1387cfca06d7SDimitry Andric   char &last = Flags.back();
1388cfca06d7SDimitry Andric   if (last == ',')
1389cfca06d7SDimitry Andric     last = '}';
1390cfca06d7SDimitry Andric   else
1391cfca06d7SDimitry Andric     Flags.append("}");
1392cfca06d7SDimitry Andric   return Flags;
1393cfca06d7SDimitry Andric }
1394cfca06d7SDimitry Andric 
dumpSectionInfo(raw_ostream & OS)13951d5ae102SDimitry Andric bool SampleProfileReaderExtBinaryBase::dumpSectionInfo(raw_ostream &OS) {
13961d5ae102SDimitry Andric   uint64_t TotalSecsSize = 0;
13971d5ae102SDimitry Andric   for (auto &Entry : SecHdrTable) {
13981d5ae102SDimitry Andric     OS << getSecName(Entry.Type) << " - Offset: " << Entry.Offset
1399cfca06d7SDimitry Andric        << ", Size: " << Entry.Size << ", Flags: " << getSecFlagsStr(Entry)
1400cfca06d7SDimitry Andric        << "\n";
1401cfca06d7SDimitry Andric     ;
1402b60736ecSDimitry Andric     TotalSecsSize += Entry.Size;
14031d5ae102SDimitry Andric   }
14041d5ae102SDimitry Andric   uint64_t HeaderSize = SecHdrTable.front().Offset;
14051d5ae102SDimitry Andric   assert(HeaderSize + TotalSecsSize == getFileSize() &&
14061d5ae102SDimitry Andric          "Size of 'header + sections' doesn't match the total size of profile");
14071d5ae102SDimitry Andric 
14081d5ae102SDimitry Andric   OS << "Header Size: " << HeaderSize << "\n";
14091d5ae102SDimitry Andric   OS << "Total Sections Size: " << TotalSecsSize << "\n";
14101d5ae102SDimitry Andric   OS << "File Size: " << getFileSize() << "\n";
14111d5ae102SDimitry Andric   return true;
14121d5ae102SDimitry Andric }
14131d5ae102SDimitry Andric 
readMagicIdent()14141d5ae102SDimitry Andric std::error_code SampleProfileReaderBinary::readMagicIdent() {
1415eb11fae6SDimitry Andric   // Read and check the magic identifier.
1416eb11fae6SDimitry Andric   auto Magic = readNumber<uint64_t>();
1417eb11fae6SDimitry Andric   if (std::error_code EC = Magic.getError())
1418eb11fae6SDimitry Andric     return EC;
1419eb11fae6SDimitry Andric   else if (std::error_code EC = verifySPMagic(*Magic))
1420eb11fae6SDimitry Andric     return EC;
1421eb11fae6SDimitry Andric 
1422eb11fae6SDimitry Andric   // Read the version number.
1423eb11fae6SDimitry Andric   auto Version = readNumber<uint64_t>();
1424eb11fae6SDimitry Andric   if (std::error_code EC = Version.getError())
1425eb11fae6SDimitry Andric     return EC;
1426eb11fae6SDimitry Andric   else if (*Version != SPVersion())
1427eb11fae6SDimitry Andric     return sampleprof_error::unsupported_version;
1428eb11fae6SDimitry Andric 
14291d5ae102SDimitry Andric   return sampleprof_error::success;
14301d5ae102SDimitry Andric }
14311d5ae102SDimitry Andric 
readHeader()14321d5ae102SDimitry Andric std::error_code SampleProfileReaderBinary::readHeader() {
14331d5ae102SDimitry Andric   Data = reinterpret_cast<const uint8_t *>(Buffer->getBufferStart());
14341d5ae102SDimitry Andric   End = Data + Buffer->getBufferSize();
14351d5ae102SDimitry Andric 
14361d5ae102SDimitry Andric   if (std::error_code EC = readMagicIdent())
14371d5ae102SDimitry Andric     return EC;
14381d5ae102SDimitry Andric 
1439eb11fae6SDimitry Andric   if (std::error_code EC = readSummary())
1440eb11fae6SDimitry Andric     return EC;
1441eb11fae6SDimitry Andric 
1442eb11fae6SDimitry Andric   if (std::error_code EC = readNameTable())
1443eb11fae6SDimitry Andric     return EC;
1444eb11fae6SDimitry Andric   return sampleprof_error::success;
1445eb11fae6SDimitry Andric }
1446eb11fae6SDimitry Andric 
readSummaryEntry(std::vector<ProfileSummaryEntry> & Entries)144701095a5dSDimitry Andric std::error_code SampleProfileReaderBinary::readSummaryEntry(
144801095a5dSDimitry Andric     std::vector<ProfileSummaryEntry> &Entries) {
144901095a5dSDimitry Andric   auto Cutoff = readNumber<uint64_t>();
145001095a5dSDimitry Andric   if (std::error_code EC = Cutoff.getError())
145101095a5dSDimitry Andric     return EC;
145201095a5dSDimitry Andric 
145301095a5dSDimitry Andric   auto MinBlockCount = readNumber<uint64_t>();
145401095a5dSDimitry Andric   if (std::error_code EC = MinBlockCount.getError())
145501095a5dSDimitry Andric     return EC;
145601095a5dSDimitry Andric 
145701095a5dSDimitry Andric   auto NumBlocks = readNumber<uint64_t>();
145801095a5dSDimitry Andric   if (std::error_code EC = NumBlocks.getError())
145901095a5dSDimitry Andric     return EC;
146001095a5dSDimitry Andric 
146101095a5dSDimitry Andric   Entries.emplace_back(*Cutoff, *MinBlockCount, *NumBlocks);
146201095a5dSDimitry Andric   return sampleprof_error::success;
146301095a5dSDimitry Andric }
146401095a5dSDimitry Andric 
readSummary()146501095a5dSDimitry Andric std::error_code SampleProfileReaderBinary::readSummary() {
146601095a5dSDimitry Andric   auto TotalCount = readNumber<uint64_t>();
146701095a5dSDimitry Andric   if (std::error_code EC = TotalCount.getError())
146801095a5dSDimitry Andric     return EC;
146901095a5dSDimitry Andric 
147001095a5dSDimitry Andric   auto MaxBlockCount = readNumber<uint64_t>();
147101095a5dSDimitry Andric   if (std::error_code EC = MaxBlockCount.getError())
147201095a5dSDimitry Andric     return EC;
147301095a5dSDimitry Andric 
147401095a5dSDimitry Andric   auto MaxFunctionCount = readNumber<uint64_t>();
147501095a5dSDimitry Andric   if (std::error_code EC = MaxFunctionCount.getError())
147601095a5dSDimitry Andric     return EC;
147701095a5dSDimitry Andric 
147801095a5dSDimitry Andric   auto NumBlocks = readNumber<uint64_t>();
147901095a5dSDimitry Andric   if (std::error_code EC = NumBlocks.getError())
148001095a5dSDimitry Andric     return EC;
148101095a5dSDimitry Andric 
148201095a5dSDimitry Andric   auto NumFunctions = readNumber<uint64_t>();
148301095a5dSDimitry Andric   if (std::error_code EC = NumFunctions.getError())
148401095a5dSDimitry Andric     return EC;
148501095a5dSDimitry Andric 
148601095a5dSDimitry Andric   auto NumSummaryEntries = readNumber<uint64_t>();
148701095a5dSDimitry Andric   if (std::error_code EC = NumSummaryEntries.getError())
148801095a5dSDimitry Andric     return EC;
148901095a5dSDimitry Andric 
149001095a5dSDimitry Andric   std::vector<ProfileSummaryEntry> Entries;
149101095a5dSDimitry Andric   for (unsigned i = 0; i < *NumSummaryEntries; i++) {
149201095a5dSDimitry Andric     std::error_code EC = readSummaryEntry(Entries);
149301095a5dSDimitry Andric     if (EC != sampleprof_error::success)
149401095a5dSDimitry Andric       return EC;
149501095a5dSDimitry Andric   }
14961d5ae102SDimitry Andric   Summary = std::make_unique<ProfileSummary>(
149701095a5dSDimitry Andric       ProfileSummary::PSK_Sample, Entries, *TotalCount, *MaxBlockCount, 0,
149801095a5dSDimitry Andric       *MaxFunctionCount, *NumBlocks, *NumFunctions);
149901095a5dSDimitry Andric 
150001095a5dSDimitry Andric   return sampleprof_error::success;
150101095a5dSDimitry Andric }
150201095a5dSDimitry Andric 
hasFormat(const MemoryBuffer & Buffer)1503eb11fae6SDimitry Andric bool SampleProfileReaderRawBinary::hasFormat(const MemoryBuffer &Buffer) {
150467c32a98SDimitry Andric   const uint8_t *Data =
150567c32a98SDimitry Andric       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
150667c32a98SDimitry Andric   uint64_t Magic = decodeULEB128(Data);
150767c32a98SDimitry Andric   return Magic == SPMagic();
150867c32a98SDimitry Andric }
150967c32a98SDimitry Andric 
hasFormat(const MemoryBuffer & Buffer)15101d5ae102SDimitry Andric bool SampleProfileReaderExtBinary::hasFormat(const MemoryBuffer &Buffer) {
15111d5ae102SDimitry Andric   const uint8_t *Data =
15121d5ae102SDimitry Andric       reinterpret_cast<const uint8_t *>(Buffer.getBufferStart());
15131d5ae102SDimitry Andric   uint64_t Magic = decodeULEB128(Data);
15141d5ae102SDimitry Andric   return Magic == SPMagic(SPF_Ext_Binary);
15151d5ae102SDimitry Andric }
15161d5ae102SDimitry Andric 
skipNextWord()1517dd58ef01SDimitry Andric std::error_code SampleProfileReaderGCC::skipNextWord() {
1518dd58ef01SDimitry Andric   uint32_t dummy;
1519dd58ef01SDimitry Andric   if (!GcovBuffer.readInt(dummy))
1520dd58ef01SDimitry Andric     return sampleprof_error::truncated;
1521dd58ef01SDimitry Andric   return sampleprof_error::success;
1522dd58ef01SDimitry Andric }
1523dd58ef01SDimitry Andric 
readNumber()1524dd58ef01SDimitry Andric template <typename T> ErrorOr<T> SampleProfileReaderGCC::readNumber() {
1525dd58ef01SDimitry Andric   if (sizeof(T) <= sizeof(uint32_t)) {
1526dd58ef01SDimitry Andric     uint32_t Val;
1527dd58ef01SDimitry Andric     if (GcovBuffer.readInt(Val) && Val <= std::numeric_limits<T>::max())
1528dd58ef01SDimitry Andric       return static_cast<T>(Val);
1529dd58ef01SDimitry Andric   } else if (sizeof(T) <= sizeof(uint64_t)) {
1530dd58ef01SDimitry Andric     uint64_t Val;
1531dd58ef01SDimitry Andric     if (GcovBuffer.readInt64(Val) && Val <= std::numeric_limits<T>::max())
1532dd58ef01SDimitry Andric       return static_cast<T>(Val);
1533dd58ef01SDimitry Andric   }
1534dd58ef01SDimitry Andric 
1535dd58ef01SDimitry Andric   std::error_code EC = sampleprof_error::malformed;
1536dd58ef01SDimitry Andric   reportError(0, EC.message());
1537dd58ef01SDimitry Andric   return EC;
1538dd58ef01SDimitry Andric }
1539dd58ef01SDimitry Andric 
readString()1540dd58ef01SDimitry Andric ErrorOr<StringRef> SampleProfileReaderGCC::readString() {
1541dd58ef01SDimitry Andric   StringRef Str;
1542dd58ef01SDimitry Andric   if (!GcovBuffer.readString(Str))
1543dd58ef01SDimitry Andric     return sampleprof_error::truncated;
1544dd58ef01SDimitry Andric   return Str;
1545dd58ef01SDimitry Andric }
1546dd58ef01SDimitry Andric 
readHeader()1547dd58ef01SDimitry Andric std::error_code SampleProfileReaderGCC::readHeader() {
1548dd58ef01SDimitry Andric   // Read the magic identifier.
1549dd58ef01SDimitry Andric   if (!GcovBuffer.readGCDAFormat())
1550dd58ef01SDimitry Andric     return sampleprof_error::unrecognized_format;
1551dd58ef01SDimitry Andric 
1552dd58ef01SDimitry Andric   // Read the version number. Note - the GCC reader does not validate this
1553dd58ef01SDimitry Andric   // version, but the profile creator generates v704.
1554dd58ef01SDimitry Andric   GCOV::GCOVVersion version;
1555dd58ef01SDimitry Andric   if (!GcovBuffer.readGCOVVersion(version))
1556dd58ef01SDimitry Andric     return sampleprof_error::unrecognized_format;
1557dd58ef01SDimitry Andric 
1558cfca06d7SDimitry Andric   if (version != GCOV::V407)
1559dd58ef01SDimitry Andric     return sampleprof_error::unsupported_version;
1560dd58ef01SDimitry Andric 
1561dd58ef01SDimitry Andric   // Skip the empty integer.
1562dd58ef01SDimitry Andric   if (std::error_code EC = skipNextWord())
1563dd58ef01SDimitry Andric     return EC;
1564dd58ef01SDimitry Andric 
1565dd58ef01SDimitry Andric   return sampleprof_error::success;
1566dd58ef01SDimitry Andric }
1567dd58ef01SDimitry Andric 
readSectionTag(uint32_t Expected)1568dd58ef01SDimitry Andric std::error_code SampleProfileReaderGCC::readSectionTag(uint32_t Expected) {
1569dd58ef01SDimitry Andric   uint32_t Tag;
1570dd58ef01SDimitry Andric   if (!GcovBuffer.readInt(Tag))
1571dd58ef01SDimitry Andric     return sampleprof_error::truncated;
1572dd58ef01SDimitry Andric 
1573dd58ef01SDimitry Andric   if (Tag != Expected)
1574dd58ef01SDimitry Andric     return sampleprof_error::malformed;
1575dd58ef01SDimitry Andric 
1576dd58ef01SDimitry Andric   if (std::error_code EC = skipNextWord())
1577dd58ef01SDimitry Andric     return EC;
1578dd58ef01SDimitry Andric 
1579dd58ef01SDimitry Andric   return sampleprof_error::success;
1580dd58ef01SDimitry Andric }
1581dd58ef01SDimitry Andric 
readNameTable()1582dd58ef01SDimitry Andric std::error_code SampleProfileReaderGCC::readNameTable() {
1583dd58ef01SDimitry Andric   if (std::error_code EC = readSectionTag(GCOVTagAFDOFileNames))
1584dd58ef01SDimitry Andric     return EC;
1585dd58ef01SDimitry Andric 
1586dd58ef01SDimitry Andric   uint32_t Size;
1587dd58ef01SDimitry Andric   if (!GcovBuffer.readInt(Size))
1588dd58ef01SDimitry Andric     return sampleprof_error::truncated;
1589dd58ef01SDimitry Andric 
1590dd58ef01SDimitry Andric   for (uint32_t I = 0; I < Size; ++I) {
1591dd58ef01SDimitry Andric     StringRef Str;
1592dd58ef01SDimitry Andric     if (!GcovBuffer.readString(Str))
1593dd58ef01SDimitry Andric       return sampleprof_error::truncated;
1594cfca06d7SDimitry Andric     Names.push_back(std::string(Str));
1595dd58ef01SDimitry Andric   }
1596dd58ef01SDimitry Andric 
1597dd58ef01SDimitry Andric   return sampleprof_error::success;
1598dd58ef01SDimitry Andric }
1599dd58ef01SDimitry Andric 
readFunctionProfiles()1600dd58ef01SDimitry Andric std::error_code SampleProfileReaderGCC::readFunctionProfiles() {
1601dd58ef01SDimitry Andric   if (std::error_code EC = readSectionTag(GCOVTagAFDOFunction))
1602dd58ef01SDimitry Andric     return EC;
1603dd58ef01SDimitry Andric 
1604dd58ef01SDimitry Andric   uint32_t NumFunctions;
1605dd58ef01SDimitry Andric   if (!GcovBuffer.readInt(NumFunctions))
1606dd58ef01SDimitry Andric     return sampleprof_error::truncated;
1607dd58ef01SDimitry Andric 
1608dd58ef01SDimitry Andric   InlineCallStack Stack;
1609dd58ef01SDimitry Andric   for (uint32_t I = 0; I < NumFunctions; ++I)
1610dd58ef01SDimitry Andric     if (std::error_code EC = readOneFunctionProfile(Stack, true, 0))
1611dd58ef01SDimitry Andric       return EC;
1612dd58ef01SDimitry Andric 
161301095a5dSDimitry Andric   computeSummary();
1614dd58ef01SDimitry Andric   return sampleprof_error::success;
1615dd58ef01SDimitry Andric }
1616dd58ef01SDimitry Andric 
readOneFunctionProfile(const InlineCallStack & InlineStack,bool Update,uint32_t Offset)1617dd58ef01SDimitry Andric std::error_code SampleProfileReaderGCC::readOneFunctionProfile(
1618dd58ef01SDimitry Andric     const InlineCallStack &InlineStack, bool Update, uint32_t Offset) {
1619dd58ef01SDimitry Andric   uint64_t HeadCount = 0;
1620dd58ef01SDimitry Andric   if (InlineStack.size() == 0)
1621dd58ef01SDimitry Andric     if (!GcovBuffer.readInt64(HeadCount))
1622dd58ef01SDimitry Andric       return sampleprof_error::truncated;
1623dd58ef01SDimitry Andric 
1624dd58ef01SDimitry Andric   uint32_t NameIdx;
1625dd58ef01SDimitry Andric   if (!GcovBuffer.readInt(NameIdx))
1626dd58ef01SDimitry Andric     return sampleprof_error::truncated;
1627dd58ef01SDimitry Andric 
1628dd58ef01SDimitry Andric   StringRef Name(Names[NameIdx]);
1629dd58ef01SDimitry Andric 
1630dd58ef01SDimitry Andric   uint32_t NumPosCounts;
1631dd58ef01SDimitry Andric   if (!GcovBuffer.readInt(NumPosCounts))
1632dd58ef01SDimitry Andric     return sampleprof_error::truncated;
1633dd58ef01SDimitry Andric 
1634dd58ef01SDimitry Andric   uint32_t NumCallsites;
1635dd58ef01SDimitry Andric   if (!GcovBuffer.readInt(NumCallsites))
1636dd58ef01SDimitry Andric     return sampleprof_error::truncated;
1637dd58ef01SDimitry Andric 
1638dd58ef01SDimitry Andric   FunctionSamples *FProfile = nullptr;
1639dd58ef01SDimitry Andric   if (InlineStack.size() == 0) {
1640dd58ef01SDimitry Andric     // If this is a top function that we have already processed, do not
1641dd58ef01SDimitry Andric     // update its profile again.  This happens in the presence of
1642dd58ef01SDimitry Andric     // function aliases.  Since these aliases share the same function
1643dd58ef01SDimitry Andric     // body, there will be identical replicated profiles for the
1644dd58ef01SDimitry Andric     // original function.  In this case, we simply not bother updating
1645dd58ef01SDimitry Andric     // the profile of the original function.
1646b1c73532SDimitry Andric     FProfile = &Profiles[FunctionId(Name)];
1647dd58ef01SDimitry Andric     FProfile->addHeadSamples(HeadCount);
1648dd58ef01SDimitry Andric     if (FProfile->getTotalSamples() > 0)
1649dd58ef01SDimitry Andric       Update = false;
1650dd58ef01SDimitry Andric   } else {
1651dd58ef01SDimitry Andric     // Otherwise, we are reading an inlined instance. The top of the
1652dd58ef01SDimitry Andric     // inline stack contains the profile of the caller. Insert this
1653dd58ef01SDimitry Andric     // callee in the caller's CallsiteMap.
1654dd58ef01SDimitry Andric     FunctionSamples *CallerProfile = InlineStack.front();
1655dd58ef01SDimitry Andric     uint32_t LineOffset = Offset >> 16;
1656dd58ef01SDimitry Andric     uint32_t Discriminator = Offset & 0xffff;
1657dd58ef01SDimitry Andric     FProfile = &CallerProfile->functionSamplesAt(
1658b1c73532SDimitry Andric         LineLocation(LineOffset, Discriminator))[FunctionId(Name)];
1659dd58ef01SDimitry Andric   }
1660b1c73532SDimitry Andric   FProfile->setFunction(FunctionId(Name));
1661dd58ef01SDimitry Andric 
1662dd58ef01SDimitry Andric   for (uint32_t I = 0; I < NumPosCounts; ++I) {
1663dd58ef01SDimitry Andric     uint32_t Offset;
1664dd58ef01SDimitry Andric     if (!GcovBuffer.readInt(Offset))
1665dd58ef01SDimitry Andric       return sampleprof_error::truncated;
1666dd58ef01SDimitry Andric 
1667dd58ef01SDimitry Andric     uint32_t NumTargets;
1668dd58ef01SDimitry Andric     if (!GcovBuffer.readInt(NumTargets))
1669dd58ef01SDimitry Andric       return sampleprof_error::truncated;
1670dd58ef01SDimitry Andric 
1671dd58ef01SDimitry Andric     uint64_t Count;
1672dd58ef01SDimitry Andric     if (!GcovBuffer.readInt64(Count))
1673dd58ef01SDimitry Andric       return sampleprof_error::truncated;
1674dd58ef01SDimitry Andric 
1675dd58ef01SDimitry Andric     // The line location is encoded in the offset as:
1676dd58ef01SDimitry Andric     //   high 16 bits: line offset to the start of the function.
1677dd58ef01SDimitry Andric     //   low 16 bits: discriminator.
1678dd58ef01SDimitry Andric     uint32_t LineOffset = Offset >> 16;
1679dd58ef01SDimitry Andric     uint32_t Discriminator = Offset & 0xffff;
1680dd58ef01SDimitry Andric 
1681dd58ef01SDimitry Andric     InlineCallStack NewStack;
1682dd58ef01SDimitry Andric     NewStack.push_back(FProfile);
1683b60736ecSDimitry Andric     llvm::append_range(NewStack, InlineStack);
1684dd58ef01SDimitry Andric     if (Update) {
1685dd58ef01SDimitry Andric       // Walk up the inline stack, adding the samples on this line to
1686dd58ef01SDimitry Andric       // the total sample count of the callers in the chain.
1687e3b55780SDimitry Andric       for (auto *CallerProfile : NewStack)
1688dd58ef01SDimitry Andric         CallerProfile->addTotalSamples(Count);
1689dd58ef01SDimitry Andric 
1690dd58ef01SDimitry Andric       // Update the body samples for the current profile.
1691dd58ef01SDimitry Andric       FProfile->addBodySamples(LineOffset, Discriminator, Count);
1692dd58ef01SDimitry Andric     }
1693dd58ef01SDimitry Andric 
1694dd58ef01SDimitry Andric     // Process the list of functions called at an indirect call site.
1695dd58ef01SDimitry Andric     // These are all the targets that a function pointer (or virtual
1696dd58ef01SDimitry Andric     // function) resolved at runtime.
1697dd58ef01SDimitry Andric     for (uint32_t J = 0; J < NumTargets; J++) {
1698dd58ef01SDimitry Andric       uint32_t HistVal;
1699dd58ef01SDimitry Andric       if (!GcovBuffer.readInt(HistVal))
1700dd58ef01SDimitry Andric         return sampleprof_error::truncated;
1701dd58ef01SDimitry Andric 
1702dd58ef01SDimitry Andric       if (HistVal != HIST_TYPE_INDIR_CALL_TOPN)
1703dd58ef01SDimitry Andric         return sampleprof_error::malformed;
1704dd58ef01SDimitry Andric 
1705dd58ef01SDimitry Andric       uint64_t TargetIdx;
1706dd58ef01SDimitry Andric       if (!GcovBuffer.readInt64(TargetIdx))
1707dd58ef01SDimitry Andric         return sampleprof_error::truncated;
1708dd58ef01SDimitry Andric       StringRef TargetName(Names[TargetIdx]);
1709dd58ef01SDimitry Andric 
1710dd58ef01SDimitry Andric       uint64_t TargetCount;
1711dd58ef01SDimitry Andric       if (!GcovBuffer.readInt64(TargetCount))
1712dd58ef01SDimitry Andric         return sampleprof_error::truncated;
1713dd58ef01SDimitry Andric 
171471d5a254SDimitry Andric       if (Update)
171571d5a254SDimitry Andric         FProfile->addCalledTargetSamples(LineOffset, Discriminator,
1716b1c73532SDimitry Andric                                          FunctionId(TargetName),
1717b1c73532SDimitry Andric                                          TargetCount);
1718dd58ef01SDimitry Andric     }
1719dd58ef01SDimitry Andric   }
1720dd58ef01SDimitry Andric 
1721dd58ef01SDimitry Andric   // Process all the inlined callers into the current function. These
1722dd58ef01SDimitry Andric   // are all the callsites that were inlined into this function.
1723dd58ef01SDimitry Andric   for (uint32_t I = 0; I < NumCallsites; I++) {
1724dd58ef01SDimitry Andric     // The offset is encoded as:
1725dd58ef01SDimitry Andric     //   high 16 bits: line offset to the start of the function.
1726dd58ef01SDimitry Andric     //   low 16 bits: discriminator.
1727dd58ef01SDimitry Andric     uint32_t Offset;
1728dd58ef01SDimitry Andric     if (!GcovBuffer.readInt(Offset))
1729dd58ef01SDimitry Andric       return sampleprof_error::truncated;
1730dd58ef01SDimitry Andric     InlineCallStack NewStack;
1731dd58ef01SDimitry Andric     NewStack.push_back(FProfile);
1732b60736ecSDimitry Andric     llvm::append_range(NewStack, InlineStack);
1733dd58ef01SDimitry Andric     if (std::error_code EC = readOneFunctionProfile(NewStack, Update, Offset))
1734dd58ef01SDimitry Andric       return EC;
1735dd58ef01SDimitry Andric   }
1736dd58ef01SDimitry Andric 
1737dd58ef01SDimitry Andric   return sampleprof_error::success;
1738dd58ef01SDimitry Andric }
1739dd58ef01SDimitry Andric 
1740eb11fae6SDimitry Andric /// Read a GCC AutoFDO profile.
1741dd58ef01SDimitry Andric ///
1742dd58ef01SDimitry Andric /// This format is generated by the Linux Perf conversion tool at
1743dd58ef01SDimitry Andric /// https://github.com/google/autofdo.
readImpl()17441d5ae102SDimitry Andric std::error_code SampleProfileReaderGCC::readImpl() {
1745344a3780SDimitry Andric   assert(!ProfileIsFSDisciminator && "Gcc profiles not support FSDisciminator");
1746dd58ef01SDimitry Andric   // Read the string table.
1747dd58ef01SDimitry Andric   if (std::error_code EC = readNameTable())
1748dd58ef01SDimitry Andric     return EC;
1749dd58ef01SDimitry Andric 
1750dd58ef01SDimitry Andric   // Read the source profile.
1751dd58ef01SDimitry Andric   if (std::error_code EC = readFunctionProfiles())
1752dd58ef01SDimitry Andric     return EC;
1753dd58ef01SDimitry Andric 
1754dd58ef01SDimitry Andric   return sampleprof_error::success;
1755dd58ef01SDimitry Andric }
1756dd58ef01SDimitry Andric 
hasFormat(const MemoryBuffer & Buffer)1757dd58ef01SDimitry Andric bool SampleProfileReaderGCC::hasFormat(const MemoryBuffer &Buffer) {
1758dd58ef01SDimitry Andric   StringRef Magic(reinterpret_cast<const char *>(Buffer.getBufferStart()));
1759dd58ef01SDimitry Andric   return Magic == "adcg*704";
1760dd58ef01SDimitry Andric }
1761dd58ef01SDimitry Andric 
applyRemapping(LLVMContext & Ctx)17621d5ae102SDimitry Andric void SampleProfileReaderItaniumRemapper::applyRemapping(LLVMContext &Ctx) {
1763cfca06d7SDimitry Andric   // If the reader uses MD5 to represent string, we can't remap it because
1764d8e91e46SDimitry Andric   // we don't know what the original function names were.
1765cfca06d7SDimitry Andric   if (Reader.useMD5()) {
1766d8e91e46SDimitry Andric     Ctx.diagnose(DiagnosticInfoSampleProfile(
17671d5ae102SDimitry Andric         Reader.getBuffer()->getBufferIdentifier(),
1768d8e91e46SDimitry Andric         "Profile data remapping cannot be applied to profile data "
17697fa27ce4SDimitry Andric         "using MD5 names (original mangled names are not available).",
1770d8e91e46SDimitry Andric         DS_Warning));
17711d5ae102SDimitry Andric     return;
1772d8e91e46SDimitry Andric   }
1773d8e91e46SDimitry Andric 
1774b60736ecSDimitry Andric   // CSSPGO-TODO: Remapper is not yet supported.
1775b60736ecSDimitry Andric   // We will need to remap the entire context string.
17761d5ae102SDimitry Andric   assert(Remappings && "should be initialized while creating remapper");
1777b60736ecSDimitry Andric   for (auto &Sample : Reader.getProfiles()) {
1778b1c73532SDimitry Andric     DenseSet<FunctionId> NamesInSample;
1779b60736ecSDimitry Andric     Sample.second.findAllNames(NamesInSample);
1780b1c73532SDimitry Andric     for (auto &Name : NamesInSample) {
1781b1c73532SDimitry Andric       StringRef NameStr = Name.stringRef();
1782b1c73532SDimitry Andric       if (auto Key = Remappings->insert(NameStr))
1783b1c73532SDimitry Andric         NameMap.insert({Key, NameStr});
1784b1c73532SDimitry Andric     }
1785b60736ecSDimitry Andric   }
1786d8e91e46SDimitry Andric 
17871d5ae102SDimitry Andric   RemappingApplied = true;
1788d8e91e46SDimitry Andric }
1789d8e91e46SDimitry Andric 
1790e3b55780SDimitry Andric std::optional<StringRef>
lookUpNameInProfile(StringRef Fname)1791b60736ecSDimitry Andric SampleProfileReaderItaniumRemapper::lookUpNameInProfile(StringRef Fname) {
1792b1c73532SDimitry Andric   if (auto Key = Remappings->lookup(Fname)) {
1793b1c73532SDimitry Andric     StringRef Result = NameMap.lookup(Key);
1794b1c73532SDimitry Andric     if (!Result.empty())
1795b1c73532SDimitry Andric       return Result;
1796b1c73532SDimitry Andric   }
1797e3b55780SDimitry Andric   return std::nullopt;
1798d8e91e46SDimitry Andric }
1799d8e91e46SDimitry Andric 
1800eb11fae6SDimitry Andric /// Prepare a memory buffer for the contents of \p Filename.
180167c32a98SDimitry Andric ///
180267c32a98SDimitry Andric /// \returns an error code indicating the status of the buffer.
180367c32a98SDimitry Andric static ErrorOr<std::unique_ptr<MemoryBuffer>>
setupMemoryBuffer(const Twine & Filename,vfs::FileSystem & FS)18047fa27ce4SDimitry Andric setupMemoryBuffer(const Twine &Filename, vfs::FileSystem &FS) {
18057fa27ce4SDimitry Andric   auto BufferOrErr = Filename.str() == "-" ? MemoryBuffer::getSTDIN()
18067fa27ce4SDimitry Andric                                            : FS.getBufferForFile(Filename);
180767c32a98SDimitry Andric   if (std::error_code EC = BufferOrErr.getError())
180867c32a98SDimitry Andric     return EC;
180967c32a98SDimitry Andric   auto Buffer = std::move(BufferOrErr.get());
181067c32a98SDimitry Andric 
181167c32a98SDimitry Andric   return std::move(Buffer);
181267c32a98SDimitry Andric }
181367c32a98SDimitry Andric 
1814eb11fae6SDimitry Andric /// Create a sample profile reader based on the format of the input file.
181567c32a98SDimitry Andric ///
181667c32a98SDimitry Andric /// \param Filename The file to open.
181767c32a98SDimitry Andric ///
181867c32a98SDimitry Andric /// \param C The LLVM context to use to emit diagnostics.
181967c32a98SDimitry Andric ///
1820344a3780SDimitry Andric /// \param P The FSDiscriminatorPass.
1821344a3780SDimitry Andric ///
18221d5ae102SDimitry Andric /// \param RemapFilename The file used for profile remapping.
18231d5ae102SDimitry Andric ///
182467c32a98SDimitry Andric /// \returns an error code indicating the status of the created reader.
182567c32a98SDimitry Andric ErrorOr<std::unique_ptr<SampleProfileReader>>
create(StringRef Filename,LLVMContext & C,vfs::FileSystem & FS,FSDiscriminatorPass P,StringRef RemapFilename)1826ac9a064cSDimitry Andric SampleProfileReader::create(StringRef Filename, LLVMContext &C,
18277fa27ce4SDimitry Andric                             vfs::FileSystem &FS, FSDiscriminatorPass P,
1828ac9a064cSDimitry Andric                             StringRef RemapFilename) {
18297fa27ce4SDimitry Andric   auto BufferOrError = setupMemoryBuffer(Filename, FS);
183067c32a98SDimitry Andric   if (std::error_code EC = BufferOrError.getError())
183167c32a98SDimitry Andric     return EC;
18327fa27ce4SDimitry Andric   return create(BufferOrError.get(), C, FS, P, RemapFilename);
1833dd58ef01SDimitry Andric }
183467c32a98SDimitry Andric 
1835d8e91e46SDimitry Andric /// Create a sample profile remapper from the given input, to remap the
1836d8e91e46SDimitry Andric /// function names in the given profile data.
1837d8e91e46SDimitry Andric ///
1838d8e91e46SDimitry Andric /// \param Filename The file to open.
1839d8e91e46SDimitry Andric ///
18401d5ae102SDimitry Andric /// \param Reader The profile reader the remapper is going to be applied to.
18411d5ae102SDimitry Andric ///
1842d8e91e46SDimitry Andric /// \param C The LLVM context to use to emit diagnostics.
1843d8e91e46SDimitry Andric ///
1844d8e91e46SDimitry Andric /// \returns an error code indicating the status of the created reader.
18451d5ae102SDimitry Andric ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
create(StringRef Filename,vfs::FileSystem & FS,SampleProfileReader & Reader,LLVMContext & C)1846ac9a064cSDimitry Andric SampleProfileReaderItaniumRemapper::create(StringRef Filename,
18477fa27ce4SDimitry Andric                                            vfs::FileSystem &FS,
18481d5ae102SDimitry Andric                                            SampleProfileReader &Reader,
18491d5ae102SDimitry Andric                                            LLVMContext &C) {
18507fa27ce4SDimitry Andric   auto BufferOrError = setupMemoryBuffer(Filename, FS);
1851d8e91e46SDimitry Andric   if (std::error_code EC = BufferOrError.getError())
1852d8e91e46SDimitry Andric     return EC;
18531d5ae102SDimitry Andric   return create(BufferOrError.get(), Reader, C);
18541d5ae102SDimitry Andric }
18551d5ae102SDimitry Andric 
18561d5ae102SDimitry Andric /// Create a sample profile remapper from the given input, to remap the
18571d5ae102SDimitry Andric /// function names in the given profile data.
18581d5ae102SDimitry Andric ///
18591d5ae102SDimitry Andric /// \param B The memory buffer to create the reader from (assumes ownership).
18601d5ae102SDimitry Andric ///
18611d5ae102SDimitry Andric /// \param C The LLVM context to use to emit diagnostics.
18621d5ae102SDimitry Andric ///
18631d5ae102SDimitry Andric /// \param Reader The profile reader the remapper is going to be applied to.
18641d5ae102SDimitry Andric ///
18651d5ae102SDimitry Andric /// \returns an error code indicating the status of the created reader.
18661d5ae102SDimitry Andric ErrorOr<std::unique_ptr<SampleProfileReaderItaniumRemapper>>
create(std::unique_ptr<MemoryBuffer> & B,SampleProfileReader & Reader,LLVMContext & C)18671d5ae102SDimitry Andric SampleProfileReaderItaniumRemapper::create(std::unique_ptr<MemoryBuffer> &B,
18681d5ae102SDimitry Andric                                            SampleProfileReader &Reader,
18691d5ae102SDimitry Andric                                            LLVMContext &C) {
18701d5ae102SDimitry Andric   auto Remappings = std::make_unique<SymbolRemappingReader>();
1871145449b1SDimitry Andric   if (Error E = Remappings->read(*B)) {
18721d5ae102SDimitry Andric     handleAllErrors(
18731d5ae102SDimitry Andric         std::move(E), [&](const SymbolRemappingParseError &ParseError) {
18741d5ae102SDimitry Andric           C.diagnose(DiagnosticInfoSampleProfile(B->getBufferIdentifier(),
18751d5ae102SDimitry Andric                                                  ParseError.getLineNum(),
18761d5ae102SDimitry Andric                                                  ParseError.getMessage()));
18771d5ae102SDimitry Andric         });
18781d5ae102SDimitry Andric     return sampleprof_error::malformed;
18791d5ae102SDimitry Andric   }
18801d5ae102SDimitry Andric 
18811d5ae102SDimitry Andric   return std::make_unique<SampleProfileReaderItaniumRemapper>(
18821d5ae102SDimitry Andric       std::move(B), std::move(Remappings), Reader);
1883d8e91e46SDimitry Andric }
1884d8e91e46SDimitry Andric 
1885eb11fae6SDimitry Andric /// Create a sample profile reader based on the format of the input data.
1886dd58ef01SDimitry Andric ///
1887dd58ef01SDimitry Andric /// \param B The memory buffer to create the reader from (assumes ownership).
1888dd58ef01SDimitry Andric ///
1889dd58ef01SDimitry Andric /// \param C The LLVM context to use to emit diagnostics.
1890dd58ef01SDimitry Andric ///
1891344a3780SDimitry Andric /// \param P The FSDiscriminatorPass.
1892344a3780SDimitry Andric ///
18931d5ae102SDimitry Andric /// \param RemapFilename The file used for profile remapping.
18941d5ae102SDimitry Andric ///
1895dd58ef01SDimitry Andric /// \returns an error code indicating the status of the created reader.
1896dd58ef01SDimitry Andric ErrorOr<std::unique_ptr<SampleProfileReader>>
create(std::unique_ptr<MemoryBuffer> & B,LLVMContext & C,vfs::FileSystem & FS,FSDiscriminatorPass P,StringRef RemapFilename)18971d5ae102SDimitry Andric SampleProfileReader::create(std::unique_ptr<MemoryBuffer> &B, LLVMContext &C,
18987fa27ce4SDimitry Andric                             vfs::FileSystem &FS, FSDiscriminatorPass P,
1899ac9a064cSDimitry Andric                             StringRef RemapFilename) {
190067c32a98SDimitry Andric   std::unique_ptr<SampleProfileReader> Reader;
1901eb11fae6SDimitry Andric   if (SampleProfileReaderRawBinary::hasFormat(*B))
1902eb11fae6SDimitry Andric     Reader.reset(new SampleProfileReaderRawBinary(std::move(B), C));
19031d5ae102SDimitry Andric   else if (SampleProfileReaderExtBinary::hasFormat(*B))
19041d5ae102SDimitry Andric     Reader.reset(new SampleProfileReaderExtBinary(std::move(B), C));
1905dd58ef01SDimitry Andric   else if (SampleProfileReaderGCC::hasFormat(*B))
1906dd58ef01SDimitry Andric     Reader.reset(new SampleProfileReaderGCC(std::move(B), C));
1907dd58ef01SDimitry Andric   else if (SampleProfileReaderText::hasFormat(*B))
1908dd58ef01SDimitry Andric     Reader.reset(new SampleProfileReaderText(std::move(B), C));
190967c32a98SDimitry Andric   else
1910dd58ef01SDimitry Andric     return sampleprof_error::unrecognized_format;
191167c32a98SDimitry Andric 
19121d5ae102SDimitry Andric   if (!RemapFilename.empty()) {
19137fa27ce4SDimitry Andric     auto ReaderOrErr = SampleProfileReaderItaniumRemapper::create(
19147fa27ce4SDimitry Andric         RemapFilename, FS, *Reader, C);
19151d5ae102SDimitry Andric     if (std::error_code EC = ReaderOrErr.getError()) {
19161d5ae102SDimitry Andric       std::string Msg = "Could not create remapper: " + EC.message();
19171d5ae102SDimitry Andric       C.diagnose(DiagnosticInfoSampleProfile(RemapFilename, Msg));
191867c32a98SDimitry Andric       return EC;
19191d5ae102SDimitry Andric     }
19201d5ae102SDimitry Andric     Reader->Remapper = std::move(ReaderOrErr.get());
19211d5ae102SDimitry Andric   }
19221d5ae102SDimitry Andric 
19231d5ae102SDimitry Andric   if (std::error_code EC = Reader->readHeader()) {
19241d5ae102SDimitry Andric     return EC;
19251d5ae102SDimitry Andric   }
192667c32a98SDimitry Andric 
1927344a3780SDimitry Andric   Reader->setDiscriminatorMaskedBitFrom(P);
1928344a3780SDimitry Andric 
192967c32a98SDimitry Andric   return std::move(Reader);
193067c32a98SDimitry Andric }
193101095a5dSDimitry Andric 
193201095a5dSDimitry Andric // For text and GCC file formats, we compute the summary after reading the
193301095a5dSDimitry Andric // profile. Binary format has the profile summary in its header.
computeSummary()193401095a5dSDimitry Andric void SampleProfileReader::computeSummary() {
193501095a5dSDimitry Andric   SampleProfileSummaryBuilder Builder(ProfileSummaryBuilder::DefaultCutoffs);
1936344a3780SDimitry Andric   Summary = Builder.computeSummaryForProfiles(Profiles);
193701095a5dSDimitry Andric }
1938