1 //===-- PerfReader.cpp - perfscript reader  ---------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "PerfReader.h"
9 #include "ProfileGenerator.h"
10 #include "llvm/Support/FileSystem.h"
11 #include "llvm/Support/Process.h"
12 
13 #define DEBUG_TYPE "perf-reader"
14 
15 cl::opt<bool> SkipSymbolization("skip-symbolization", cl::init(false),
16                                 cl::ZeroOrMore,
17                                 cl::desc("Dump the unsymbolized profile to the "
18                                          "output file. It will show unwinder "
19                                          "output for CS profile generation."));
20 
21 static cl::opt<bool> ShowMmapEvents("show-mmap-events", cl::init(false),
22                                     cl::ZeroOrMore,
23                                     cl::desc("Print binary load events."));
24 
25 static cl::opt<bool>
26     UseOffset("use-offset", cl::init(true), cl::ZeroOrMore,
27               cl::desc("Work with `--skip-symbolization` or "
28                        "`--unsymbolized-profile` to write/read the "
29                        "offset instead of virtual address."));
30 static cl::opt<bool>
31     IgnoreStackSamples("ignore-stack-samples", cl::init(false), cl::ZeroOrMore,
32                        cl::desc("Ignore call stack samples for hybrid samples "
33                                 "and produce context-insensitive profile."));
34 
35 extern cl::opt<std::string> PerfTraceFilename;
36 extern cl::opt<bool> ShowDisassemblyOnly;
37 extern cl::opt<bool> ShowSourceLocations;
38 extern cl::opt<std::string> OutputFilename;
39 
40 namespace llvm {
41 namespace sampleprof {
42 
43 void VirtualUnwinder::unwindCall(UnwindState &State) {
44   // The 2nd frame after leaf could be missing if stack sample is
45   // taken when IP is within prolog/epilog, as frame chain isn't
46   // setup yet. Fill in the missing frame in that case.
47   // TODO: Currently we just assume all the addr that can't match the
48   // 2nd frame is in prolog/epilog. In the future, we will switch to
49   // pro/epi tracker(Dwarf CFI) for the precise check.
50   uint64_t Source = State.getCurrentLBRSource();
51   auto *ParentFrame = State.getParentFrame();
52   if (ParentFrame == State.getDummyRootPtr() ||
53       ParentFrame->Address != Source) {
54     State.switchToFrame(Source);
55   } else {
56     State.popFrame();
57   }
58   State.InstPtr.update(Source);
59 }
60 
61 void VirtualUnwinder::unwindLinear(UnwindState &State, uint64_t Repeat) {
62   InstructionPointer &IP = State.InstPtr;
63   uint64_t Target = State.getCurrentLBRTarget();
64   uint64_t End = IP.Address;
65   if (Binary->usePseudoProbes()) {
66     // We don't need to top frame probe since it should be extracted
67     // from the range.
68     // The outcome of the virtual unwinding with pseudo probes is a
69     // map from a context key to the address range being unwound.
70     // This means basically linear unwinding is not needed for pseudo
71     // probes. The range will be simply recorded here and will be
72     // converted to a list of pseudo probes to report in ProfileGenerator.
73     State.getParentFrame()->recordRangeCount(Target, End, Repeat);
74   } else {
75     // Unwind linear execution part.
76     // Split and record the range by different inline context. For example:
77     // [0x01] ... main:1          # Target
78     // [0x02] ... main:2
79     // [0x03] ... main:3 @ foo:1
80     // [0x04] ... main:3 @ foo:2
81     // [0x05] ... main:3 @ foo:3
82     // [0x06] ... main:4
83     // [0x07] ... main:5          # End
84     // It will be recorded:
85     // [main:*]         : [0x06, 0x07], [0x01, 0x02]
86     // [main:3 @ foo:*] : [0x03, 0x05]
87     while (IP.Address > Target) {
88       uint64_t PrevIP = IP.Address;
89       IP.backward();
90       // Break into segments for implicit call/return due to inlining
91       bool SameInlinee = Binary->inlineContextEqual(PrevIP, IP.Address);
92       if (!SameInlinee) {
93         State.switchToFrame(PrevIP);
94         State.CurrentLeafFrame->recordRangeCount(PrevIP, End, Repeat);
95         End = IP.Address;
96       }
97     }
98     assert(IP.Address == Target && "The last one must be the target address.");
99     // Record the remaining range, [0x01, 0x02] in the example
100     State.switchToFrame(IP.Address);
101     State.CurrentLeafFrame->recordRangeCount(IP.Address, End, Repeat);
102   }
103 }
104 
105 void VirtualUnwinder::unwindReturn(UnwindState &State) {
106   // Add extra frame as we unwind through the return
107   const LBREntry &LBR = State.getCurrentLBR();
108   uint64_t CallAddr = Binary->getCallAddrFromFrameAddr(LBR.Target);
109   State.switchToFrame(CallAddr);
110   State.pushFrame(LBR.Source);
111   State.InstPtr.update(LBR.Source);
112 }
113 
114 void VirtualUnwinder::unwindBranchWithinFrame(UnwindState &State) {
115   // TODO: Tolerate tail call for now, as we may see tail call from libraries.
116   // This is only for intra function branches, excluding tail calls.
117   uint64_t Source = State.getCurrentLBRSource();
118   State.switchToFrame(Source);
119   State.InstPtr.update(Source);
120 }
121 
122 std::shared_ptr<StringBasedCtxKey> FrameStack::getContextKey() {
123   std::shared_ptr<StringBasedCtxKey> KeyStr =
124       std::make_shared<StringBasedCtxKey>();
125   KeyStr->Context = Binary->getExpandedContext(Stack, KeyStr->WasLeafInlined);
126   if (KeyStr->Context.empty())
127     return nullptr;
128   KeyStr->genHashCode();
129   return KeyStr;
130 }
131 
132 std::shared_ptr<ProbeBasedCtxKey> ProbeStack::getContextKey() {
133   std::shared_ptr<ProbeBasedCtxKey> ProbeBasedKey =
134       std::make_shared<ProbeBasedCtxKey>();
135   for (auto CallProbe : Stack) {
136     ProbeBasedKey->Probes.emplace_back(CallProbe);
137   }
138   CSProfileGenerator::compressRecursionContext<const MCDecodedPseudoProbe *>(
139       ProbeBasedKey->Probes);
140   CSProfileGenerator::trimContext<const MCDecodedPseudoProbe *>(
141       ProbeBasedKey->Probes);
142 
143   ProbeBasedKey->genHashCode();
144   return ProbeBasedKey;
145 }
146 
147 template <typename T>
148 void VirtualUnwinder::collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur,
149                                               T &Stack) {
150   if (Cur->RangeSamples.empty() && Cur->BranchSamples.empty())
151     return;
152 
153   std::shared_ptr<ContextKey> Key = Stack.getContextKey();
154   if (Key == nullptr)
155     return;
156   auto Ret = CtxCounterMap->emplace(Hashable<ContextKey>(Key), SampleCounter());
157   SampleCounter &SCounter = Ret.first->second;
158   for (auto &Item : Cur->RangeSamples) {
159     uint64_t StartOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
160     uint64_t EndOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
161     SCounter.recordRangeCount(StartOffset, EndOffset, std::get<2>(Item));
162   }
163 
164   for (auto &Item : Cur->BranchSamples) {
165     uint64_t SourceOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
166     uint64_t TargetOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
167     SCounter.recordBranchCount(SourceOffset, TargetOffset, std::get<2>(Item));
168   }
169 }
170 
171 template <typename T>
172 void VirtualUnwinder::collectSamplesFromFrameTrie(
173     UnwindState::ProfiledFrame *Cur, T &Stack) {
174   if (!Cur->isDummyRoot()) {
175     if (!Stack.pushFrame(Cur)) {
176       // Process truncated context
177       // Start a new traversal ignoring its bottom context
178       T EmptyStack(Binary);
179       collectSamplesFromFrame(Cur, EmptyStack);
180       for (const auto &Item : Cur->Children) {
181         collectSamplesFromFrameTrie(Item.second.get(), EmptyStack);
182       }
183 
184       // Keep note of untracked call site and deduplicate them
185       // for warning later.
186       if (!Cur->isLeafFrame())
187         UntrackedCallsites.insert(Cur->Address);
188 
189       return;
190     }
191   }
192 
193   collectSamplesFromFrame(Cur, Stack);
194   // Process children frame
195   for (const auto &Item : Cur->Children) {
196     collectSamplesFromFrameTrie(Item.second.get(), Stack);
197   }
198   // Recover the call stack
199   Stack.popFrame();
200 }
201 
202 void VirtualUnwinder::collectSamplesFromFrameTrie(
203     UnwindState::ProfiledFrame *Cur) {
204   if (Binary->usePseudoProbes()) {
205     ProbeStack Stack(Binary);
206     collectSamplesFromFrameTrie<ProbeStack>(Cur, Stack);
207   } else {
208     FrameStack Stack(Binary);
209     collectSamplesFromFrameTrie<FrameStack>(Cur, Stack);
210   }
211 }
212 
213 void VirtualUnwinder::recordBranchCount(const LBREntry &Branch,
214                                         UnwindState &State, uint64_t Repeat) {
215   if (Branch.IsArtificial)
216     return;
217 
218   if (Binary->usePseudoProbes()) {
219     // Same as recordRangeCount, We don't need to top frame probe since we will
220     // extract it from branch's source address
221     State.getParentFrame()->recordBranchCount(Branch.Source, Branch.Target,
222                                               Repeat);
223   } else {
224     State.CurrentLeafFrame->recordBranchCount(Branch.Source, Branch.Target,
225                                               Repeat);
226   }
227 }
228 
229 bool VirtualUnwinder::unwind(const PerfSample *Sample, uint64_t Repeat) {
230   // Capture initial state as starting point for unwinding.
231   UnwindState State(Sample, Binary);
232 
233   // Sanity check - making sure leaf of LBR aligns with leaf of stack sample
234   // Stack sample sometimes can be unreliable, so filter out bogus ones.
235   if (!State.validateInitialState())
236     return false;
237 
238   // Also do not attempt linear unwind for the leaf range as it's incomplete.
239   bool IsLeaf = true;
240 
241   // Now process the LBR samples in parrallel with stack sample
242   // Note that we do not reverse the LBR entry order so we can
243   // unwind the sample stack as we walk through LBR entries.
244   while (State.hasNextLBR()) {
245     State.checkStateConsistency();
246 
247     // Unwind implicit calls/returns from inlining, along the linear path,
248     // break into smaller sub section each with its own calling context.
249     if (!IsLeaf) {
250       unwindLinear(State, Repeat);
251     }
252     IsLeaf = false;
253 
254     // Save the LBR branch before it gets unwound.
255     const LBREntry &Branch = State.getCurrentLBR();
256 
257     if (isCallState(State)) {
258       // Unwind calls - we know we encountered call if LBR overlaps with
259       // transition between leaf the 2nd frame. Note that for calls that
260       // were not in the original stack sample, we should have added the
261       // extra frame when processing the return paired with this call.
262       unwindCall(State);
263     } else if (isReturnState(State)) {
264       // Unwind returns - check whether the IP is indeed at a return instruction
265       unwindReturn(State);
266     } else {
267       // Unwind branches - for regular intra function branches, we only
268       // need to record branch with context.
269       unwindBranchWithinFrame(State);
270     }
271     State.advanceLBR();
272     // Record `branch` with calling context after unwinding.
273     recordBranchCount(Branch, State, Repeat);
274   }
275   // As samples are aggregated on trie, record them into counter map
276   collectSamplesFromFrameTrie(State.getDummyRootPtr());
277 
278   return true;
279 }
280 
281 std::unique_ptr<PerfReaderBase>
282 PerfReaderBase::create(ProfiledBinary *Binary, PerfInputFile &PerfInput) {
283   std::unique_ptr<PerfReaderBase> PerfReader;
284 
285   if (PerfInput.Format == PerfFormat::UnsymbolizedProfile) {
286     PerfReader.reset(
287         new UnsymbolizedProfileReader(Binary, PerfInput.InputFile));
288     return PerfReader;
289   }
290 
291   // For perf data input, we need to convert them into perf script first.
292   if (PerfInput.Format == PerfFormat::PerfData)
293     PerfInput = PerfScriptReader::convertPerfDataToTrace(Binary, PerfInput);
294 
295   assert((PerfInput.Format == PerfFormat::PerfScript) &&
296          "Should be a perfscript!");
297 
298   PerfInput.Content =
299       PerfScriptReader::checkPerfScriptType(PerfInput.InputFile);
300   if (PerfInput.Content == PerfContent::LBRStack) {
301     PerfReader.reset(new HybridPerfReader(Binary, PerfInput.InputFile));
302   } else if (PerfInput.Content == PerfContent::LBR) {
303     PerfReader.reset(new LBRPerfReader(Binary, PerfInput.InputFile));
304   } else {
305     exitWithError("Unsupported perfscript!");
306   }
307 
308   return PerfReader;
309 }
310 
311 PerfInputFile PerfScriptReader::convertPerfDataToTrace(ProfiledBinary *Binary,
312                                                        PerfInputFile &File) {
313   StringRef PerfData = File.InputFile;
314   // Run perf script to retrieve PIDs matching binary we're interested in.
315   auto PerfExecutable = sys::Process::FindInEnvPath("PATH", "perf");
316   if (!PerfExecutable) {
317     exitWithError("Perf not found.");
318   }
319   std::string PerfPath = *PerfExecutable;
320   std::string PerfTraceFile = PerfData.str() + ".script.tmp";
321   StringRef ScriptMMapArgs[] = {PerfPath, "script",   "--show-mmap-events",
322                                 "-F",     "comm,pid", "-i",
323                                 PerfData};
324   Optional<StringRef> Redirects[] = {llvm::None,                // Stdin
325                                      StringRef(PerfTraceFile),  // Stdout
326                                      StringRef(PerfTraceFile)}; // Stderr
327   sys::ExecuteAndWait(PerfPath, ScriptMMapArgs, llvm::None, Redirects);
328 
329   // Collect the PIDs
330   TraceStream TraceIt(PerfTraceFile);
331   std::string PIDs;
332   std::unordered_set<uint32_t> PIDSet;
333   while (!TraceIt.isAtEoF()) {
334     MMapEvent MMap;
335     if (isMMap2Event(TraceIt.getCurrentLine()) &&
336         extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap)) {
337       auto It = PIDSet.emplace(MMap.PID);
338       if (It.second) {
339         if (!PIDs.empty()) {
340           PIDs.append(",");
341         }
342         PIDs.append(utostr(MMap.PID));
343       }
344     }
345     TraceIt.advance();
346   }
347 
348   if (PIDs.empty()) {
349     exitWithError("No relevant mmap event is found in perf data.");
350   }
351 
352   // Run perf script again to retrieve events for PIDs collected above
353   StringRef ScriptSampleArgs[] = {PerfPath, "script",     "--show-mmap-events",
354                                   "-F",     "ip,brstack", "--pid",
355                                   PIDs,     "-i",         PerfData};
356   sys::ExecuteAndWait(PerfPath, ScriptSampleArgs, llvm::None, Redirects);
357 
358   return {PerfTraceFile, PerfFormat::PerfScript, PerfContent::UnknownContent};
359 }
360 
361 void PerfScriptReader::updateBinaryAddress(const MMapEvent &Event) {
362   // Drop the event which doesn't belong to user-provided binary
363   StringRef BinaryName = llvm::sys::path::filename(Event.BinaryPath);
364   if (Binary->getName() != BinaryName)
365     return;
366 
367   // Drop the event if its image is loaded at the same address
368   if (Event.Address == Binary->getBaseAddress()) {
369     Binary->setIsLoadedByMMap(true);
370     return;
371   }
372 
373   if (Event.Offset == Binary->getTextSegmentOffset()) {
374     // A binary image could be unloaded and then reloaded at different
375     // place, so update binary load address.
376     // Only update for the first executable segment and assume all other
377     // segments are loaded at consecutive memory addresses, which is the case on
378     // X64.
379     Binary->setBaseAddress(Event.Address);
380     Binary->setIsLoadedByMMap(true);
381   } else {
382     // Verify segments are loaded consecutively.
383     const auto &Offsets = Binary->getTextSegmentOffsets();
384     auto It = std::lower_bound(Offsets.begin(), Offsets.end(), Event.Offset);
385     if (It != Offsets.end() && *It == Event.Offset) {
386       // The event is for loading a separate executable segment.
387       auto I = std::distance(Offsets.begin(), It);
388       const auto &PreferredAddrs = Binary->getPreferredTextSegmentAddresses();
389       if (PreferredAddrs[I] - Binary->getPreferredBaseAddress() !=
390           Event.Address - Binary->getBaseAddress())
391         exitWithError("Executable segments not loaded consecutively");
392     } else {
393       if (It == Offsets.begin())
394         exitWithError("File offset not found");
395       else {
396         // Find the segment the event falls in. A large segment could be loaded
397         // via multiple mmap calls with consecutive memory addresses.
398         --It;
399         assert(*It < Event.Offset);
400         if (Event.Offset - *It != Event.Address - Binary->getBaseAddress())
401           exitWithError("Segment not loaded by consecutive mmaps");
402       }
403     }
404   }
405 }
406 
407 static std::string getContextKeyStr(ContextKey *K,
408                                     const ProfiledBinary *Binary) {
409   if (const auto *CtxKey = dyn_cast<StringBasedCtxKey>(K)) {
410     return SampleContext::getContextString(CtxKey->Context);
411   } else if (const auto *CtxKey = dyn_cast<ProbeBasedCtxKey>(K)) {
412     SampleContextFrameVector ContextStack;
413     for (const auto *Probe : CtxKey->Probes) {
414       Binary->getInlineContextForProbe(Probe, ContextStack, true);
415     }
416     // Probe context key at this point does not have leaf probe, so do not
417     // include the leaf inline location.
418     return SampleContext::getContextString(ContextStack, true);
419   } else {
420     llvm_unreachable("unexpected key type");
421   }
422 }
423 
424 void HybridPerfReader::unwindSamples() {
425   std::set<uint64_t> AllUntrackedCallsites;
426   for (const auto &Item : AggregatedSamples) {
427     const PerfSample *Sample = Item.first.getPtr();
428     VirtualUnwinder Unwinder(&SampleCounters, Binary);
429     Unwinder.unwind(Sample, Item.second);
430     auto &CurrUntrackedCallsites = Unwinder.getUntrackedCallsites();
431     AllUntrackedCallsites.insert(CurrUntrackedCallsites.begin(),
432                                  CurrUntrackedCallsites.end());
433   }
434 
435   // Warn about untracked frames due to missing probes.
436   for (auto Address : AllUntrackedCallsites)
437     WithColor::warning() << "Profile context truncated due to missing probe "
438                          << "for call instruction at "
439                          << format("0x%" PRIx64, Address) << "\n";
440 }
441 
442 bool PerfScriptReader::extractLBRStack(TraceStream &TraceIt,
443                                        SmallVectorImpl<LBREntry> &LBRStack) {
444   // The raw format of LBR stack is like:
445   // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
446   //                           ... 0x4005c8/0x4005dc/P/-/-/0
447   // It's in FIFO order and seperated by whitespace.
448   SmallVector<StringRef, 32> Records;
449   TraceIt.getCurrentLine().split(Records, " ", -1, false);
450   auto WarnInvalidLBR = [](TraceStream &TraceIt) {
451     WithColor::warning() << "Invalid address in LBR record at line "
452                          << TraceIt.getLineNumber() << ": "
453                          << TraceIt.getCurrentLine() << "\n";
454   };
455 
456   // Skip the leading instruction pointer.
457   size_t Index = 0;
458   uint64_t LeadingAddr;
459   if (!Records.empty() && !Records[0].contains('/')) {
460     if (Records[0].getAsInteger(16, LeadingAddr)) {
461       WarnInvalidLBR(TraceIt);
462       TraceIt.advance();
463       return false;
464     }
465     Index = 1;
466   }
467   // Now extract LBR samples - note that we do not reverse the
468   // LBR entry order so we can unwind the sample stack as we walk
469   // through LBR entries.
470   uint64_t PrevTrDst = 0;
471 
472   while (Index < Records.size()) {
473     auto &Token = Records[Index++];
474     if (Token.size() == 0)
475       continue;
476 
477     SmallVector<StringRef, 8> Addresses;
478     Token.split(Addresses, "/");
479     uint64_t Src;
480     uint64_t Dst;
481 
482     // Stop at broken LBR records.
483     if (Addresses.size() < 2 || Addresses[0].substr(2).getAsInteger(16, Src) ||
484         Addresses[1].substr(2).getAsInteger(16, Dst)) {
485       WarnInvalidLBR(TraceIt);
486       break;
487     }
488 
489     bool SrcIsInternal = Binary->addressIsCode(Src);
490     bool DstIsInternal = Binary->addressIsCode(Dst);
491     bool IsExternal = !SrcIsInternal && !DstIsInternal;
492     bool IsIncoming = !SrcIsInternal && DstIsInternal;
493     bool IsOutgoing = SrcIsInternal && !DstIsInternal;
494     bool IsArtificial = false;
495 
496     // Ignore branches outside the current binary. Ignore all remaining branches
497     // if there's no incoming branch before the external branch in reverse
498     // order.
499     if (IsExternal) {
500       if (PrevTrDst)
501         continue;
502       if (!LBRStack.empty()) {
503         WithColor::warning()
504             << "Invalid transfer to external code in LBR record at line "
505             << TraceIt.getLineNumber() << ": " << TraceIt.getCurrentLine()
506             << "\n";
507       }
508       break;
509     }
510 
511     if (IsOutgoing) {
512       if (!PrevTrDst) {
513         // This is unpaired outgoing jump which is likely due to interrupt or
514         // incomplete LBR trace. Ignore current and subsequent entries since
515         // they are likely in different contexts.
516         break;
517       }
518 
519       if (Binary->addressIsReturn(Src)) {
520         // In a callback case, a return from internal code, say A, to external
521         // runtime can happen. The external runtime can then call back to
522         // another internal routine, say B. Making an artificial branch that
523         // looks like a return from A to B can confuse the unwinder to treat
524         // the instruction before B as the call instruction.
525         break;
526       }
527 
528       // For transition to external code, group the Source with the next
529       // availabe transition target.
530       Dst = PrevTrDst;
531       PrevTrDst = 0;
532       IsArtificial = true;
533     } else {
534       if (PrevTrDst) {
535         // If we have seen an incoming transition from external code to internal
536         // code, but not a following outgoing transition, the incoming
537         // transition is likely due to interrupt which is usually unpaired.
538         // Ignore current and subsequent entries since they are likely in
539         // different contexts.
540         break;
541       }
542 
543       if (IsIncoming) {
544         // For transition from external code (such as dynamic libraries) to
545         // the current binary, keep track of the branch target which will be
546         // grouped with the Source of the last transition from the current
547         // binary.
548         PrevTrDst = Dst;
549         continue;
550       }
551     }
552 
553     // TODO: filter out buggy duplicate branches on Skylake
554 
555     LBRStack.emplace_back(LBREntry(Src, Dst, IsArtificial));
556   }
557   TraceIt.advance();
558   return !LBRStack.empty();
559 }
560 
561 bool PerfScriptReader::extractCallstack(TraceStream &TraceIt,
562                                         SmallVectorImpl<uint64_t> &CallStack) {
563   // The raw format of call stack is like:
564   //            4005dc      # leaf frame
565   //	          400634
566   //	          400684      # root frame
567   // It's in bottom-up order with each frame in one line.
568 
569   // Extract stack frames from sample
570   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
571     StringRef FrameStr = TraceIt.getCurrentLine().ltrim();
572     uint64_t FrameAddr = 0;
573     if (FrameStr.getAsInteger(16, FrameAddr)) {
574       // We might parse a non-perf sample line like empty line and comments,
575       // skip it
576       TraceIt.advance();
577       return false;
578     }
579     TraceIt.advance();
580     // Currently intermixed frame from different binaries is not supported.
581     // Ignore caller frames not from binary of interest.
582     if (!Binary->addressIsCode(FrameAddr))
583       break;
584 
585     // We need to translate return address to call address for non-leaf frames.
586     if (!CallStack.empty()) {
587       auto CallAddr = Binary->getCallAddrFromFrameAddr(FrameAddr);
588       if (!CallAddr) {
589         // Stop at an invalid return address caused by bad unwinding. This could
590         // happen to frame-pointer-based unwinding and the callee functions that
591         // do not have the frame pointer chain set up.
592         InvalidReturnAddresses.insert(FrameAddr);
593         break;
594       }
595       FrameAddr = CallAddr;
596     }
597 
598     CallStack.emplace_back(FrameAddr);
599   }
600 
601   // Skip other unrelated line, find the next valid LBR line
602   // Note that even for empty call stack, we should skip the address at the
603   // bottom, otherwise the following pass may generate a truncated callstack
604   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
605     TraceIt.advance();
606   }
607   // Filter out broken stack sample. We may not have complete frame info
608   // if sample end up in prolog/epilog, the result is dangling context not
609   // connected to entry point. This should be relatively rare thus not much
610   // impact on overall profile quality. However we do want to filter them
611   // out to reduce the number of different calling contexts. One instance
612   // of such case - when sample landed in prolog/epilog, somehow stack
613   // walking will be broken in an unexpected way that higher frames will be
614   // missing.
615   return !CallStack.empty() &&
616          !Binary->addressInPrologEpilog(CallStack.front());
617 }
618 
619 void PerfScriptReader::warnIfMissingMMap() {
620   if (!Binary->getMissingMMapWarned() && !Binary->getIsLoadedByMMap()) {
621     WithColor::warning() << "No relevant mmap event is matched for "
622                          << Binary->getName()
623                          << ", will use preferred address ("
624                          << format("0x%" PRIx64,
625                                    Binary->getPreferredBaseAddress())
626                          << ") as the base loading address!\n";
627     // Avoid redundant warning, only warn at the first unmatched sample.
628     Binary->setMissingMMapWarned(true);
629   }
630 }
631 
632 void HybridPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
633   // The raw hybird sample started with call stack in FILO order and followed
634   // intermediately by LBR sample
635   // e.g.
636   // 	          4005dc    # call stack leaf
637   //	          400634
638   //	          400684    # call stack root
639   // 0x4005c8/0x4005dc/P/-/-/0   0x40062f/0x4005b0/P/-/-/0 ...
640   //          ... 0x4005c8/0x4005dc/P/-/-/0    # LBR Entries
641   //
642   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
643 
644   // Parsing call stack and populate into PerfSample.CallStack
645   if (!extractCallstack(TraceIt, Sample->CallStack)) {
646     // Skip the next LBR line matched current call stack
647     if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x"))
648       TraceIt.advance();
649     return;
650   }
651 
652   warnIfMissingMMap();
653 
654   if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x")) {
655     // Parsing LBR stack and populate into PerfSample.LBRStack
656     if (extractLBRStack(TraceIt, Sample->LBRStack)) {
657       if (IgnoreStackSamples) {
658         Sample->CallStack.clear();
659       } else {
660         // Canonicalize stack leaf to avoid 'random' IP from leaf frame skew LBR
661         // ranges
662         Sample->CallStack.front() = Sample->LBRStack[0].Target;
663       }
664       // Record samples by aggregation
665       AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
666     }
667   } else {
668     // LBR sample is encoded in single line after stack sample
669     exitWithError("'Hybrid perf sample is corrupted, No LBR sample line");
670   }
671 }
672 
673 void PerfScriptReader::writeUnsymbolizedProfile(StringRef Filename) {
674   std::error_code EC;
675   raw_fd_ostream OS(Filename, EC, llvm::sys::fs::OF_TextWithCRLF);
676   if (EC)
677     exitWithError(EC, Filename);
678   writeUnsymbolizedProfile(OS);
679 }
680 
681 // Use ordered map to make the output deterministic
682 using OrderedCounterForPrint = std::map<std::string, SampleCounter *>;
683 
684 void PerfScriptReader::writeUnsymbolizedProfile(raw_fd_ostream &OS) {
685   OrderedCounterForPrint OrderedCounters;
686   for (auto &CI : SampleCounters) {
687     OrderedCounters[getContextKeyStr(CI.first.getPtr(), Binary)] = &CI.second;
688   }
689 
690   auto SCounterPrinter = [&](RangeSample &Counter, StringRef Separator,
691                              uint32_t Indent) {
692     OS.indent(Indent);
693     OS << Counter.size() << "\n";
694     for (auto &I : Counter) {
695       uint64_t Start = UseOffset ? I.first.first
696                                  : Binary->offsetToVirtualAddr(I.first.first);
697       uint64_t End = UseOffset ? I.first.second
698                                : Binary->offsetToVirtualAddr(I.first.second);
699       OS.indent(Indent);
700       OS << Twine::utohexstr(Start) << Separator << Twine::utohexstr(End) << ":"
701          << I.second << "\n";
702     }
703   };
704 
705   for (auto &CI : OrderedCounters) {
706     uint32_t Indent = 0;
707     if (ProfileIsCS) {
708       // Context string key
709       OS << "[" << CI.first << "]\n";
710       Indent = 2;
711     }
712 
713     SampleCounter &Counter = *CI.second;
714     SCounterPrinter(Counter.RangeCounter, "-", Indent);
715     SCounterPrinter(Counter.BranchCounter, "->", Indent);
716   }
717 }
718 
719 // Format of input:
720 // number of entries in RangeCounter
721 // from_1-to_1:count_1
722 // from_2-to_2:count_2
723 // ......
724 // from_n-to_n:count_n
725 // number of entries in BranchCounter
726 // src_1->dst_1:count_1
727 // src_2->dst_2:count_2
728 // ......
729 // src_n->dst_n:count_n
730 void UnsymbolizedProfileReader::readSampleCounters(TraceStream &TraceIt,
731                                                    SampleCounter &SCounters) {
732   auto exitWithErrorForTraceLine = [](TraceStream &TraceIt) {
733     std::string Msg = TraceIt.isAtEoF()
734                           ? "Invalid raw profile!"
735                           : "Invalid raw profile at line " +
736                                 Twine(TraceIt.getLineNumber()).str() + ": " +
737                                 TraceIt.getCurrentLine().str();
738     exitWithError(Msg);
739   };
740   auto ReadNumber = [&](uint64_t &Num) {
741     if (TraceIt.isAtEoF())
742       exitWithErrorForTraceLine(TraceIt);
743     if (TraceIt.getCurrentLine().ltrim().getAsInteger(10, Num))
744       exitWithErrorForTraceLine(TraceIt);
745     TraceIt.advance();
746   };
747 
748   auto ReadCounter = [&](RangeSample &Counter, StringRef Separator) {
749     uint64_t Num = 0;
750     ReadNumber(Num);
751     while (Num--) {
752       if (TraceIt.isAtEoF())
753         exitWithErrorForTraceLine(TraceIt);
754       StringRef Line = TraceIt.getCurrentLine().ltrim();
755 
756       uint64_t Count = 0;
757       auto LineSplit = Line.split(":");
758       if (LineSplit.second.empty() || LineSplit.second.getAsInteger(10, Count))
759         exitWithErrorForTraceLine(TraceIt);
760 
761       uint64_t Source = 0;
762       uint64_t Target = 0;
763       auto Range = LineSplit.first.split(Separator);
764       if (Range.second.empty() || Range.first.getAsInteger(16, Source) ||
765           Range.second.getAsInteger(16, Target))
766         exitWithErrorForTraceLine(TraceIt);
767 
768       if (!UseOffset) {
769         Source = Binary->virtualAddrToOffset(Source);
770         Target = Binary->virtualAddrToOffset(Target);
771       }
772 
773       Counter[{Source, Target}] += Count;
774       TraceIt.advance();
775     }
776   };
777 
778   ReadCounter(SCounters.RangeCounter, "-");
779   ReadCounter(SCounters.BranchCounter, "->");
780 }
781 
782 void UnsymbolizedProfileReader::readUnsymbolizedProfile(StringRef FileName) {
783   TraceStream TraceIt(FileName);
784   while (!TraceIt.isAtEoF()) {
785     std::shared_ptr<StringBasedCtxKey> Key =
786         std::make_shared<StringBasedCtxKey>();
787     StringRef Line = TraceIt.getCurrentLine();
788     // Read context stack for CS profile.
789     if (Line.startswith("[")) {
790       ProfileIsCS = true;
791       auto I = ContextStrSet.insert(Line.str());
792       SampleContext::createCtxVectorFromStr(*I.first, Key->Context);
793       TraceIt.advance();
794     }
795     Key->genHashCode();
796     auto Ret =
797         SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
798     readSampleCounters(TraceIt, Ret.first->second);
799   }
800 }
801 
802 void UnsymbolizedProfileReader::parsePerfTraces() {
803   readUnsymbolizedProfile(PerfTraceFile);
804 }
805 
806 void PerfScriptReader::computeCounterFromLBR(const PerfSample *Sample,
807                                              uint64_t Repeat) {
808   SampleCounter &Counter = SampleCounters.begin()->second;
809   uint64_t EndOffeset = 0;
810   for (const LBREntry &LBR : Sample->LBRStack) {
811     uint64_t SourceOffset = Binary->virtualAddrToOffset(LBR.Source);
812     uint64_t TargetOffset = Binary->virtualAddrToOffset(LBR.Target);
813 
814     if (!LBR.IsArtificial) {
815       Counter.recordBranchCount(SourceOffset, TargetOffset, Repeat);
816     }
817 
818     // If this not the first LBR, update the range count between TO of current
819     // LBR and FROM of next LBR.
820     uint64_t StartOffset = TargetOffset;
821     if (EndOffeset != 0)
822       Counter.recordRangeCount(StartOffset, EndOffeset, Repeat);
823     EndOffeset = SourceOffset;
824   }
825 }
826 
827 void LBRPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
828   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
829   // Parsing LBR stack and populate into PerfSample.LBRStack
830   if (extractLBRStack(TraceIt, Sample->LBRStack)) {
831     warnIfMissingMMap();
832     // Record LBR only samples by aggregation
833     AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
834   }
835 }
836 
837 void PerfScriptReader::generateUnsymbolizedProfile() {
838   // There is no context for LBR only sample, so initialize one entry with
839   // fake "empty" context key.
840   assert(SampleCounters.empty() &&
841          "Sample counter map should be empty before raw profile generation");
842   std::shared_ptr<StringBasedCtxKey> Key =
843       std::make_shared<StringBasedCtxKey>();
844   Key->genHashCode();
845   SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
846   for (const auto &Item : AggregatedSamples) {
847     const PerfSample *Sample = Item.first.getPtr();
848     computeCounterFromLBR(Sample, Item.second);
849   }
850 }
851 
852 uint64_t PerfScriptReader::parseAggregatedCount(TraceStream &TraceIt) {
853   // The aggregated count is optional, so do not skip the line and return 1 if
854   // it's unmatched
855   uint64_t Count = 1;
856   if (!TraceIt.getCurrentLine().getAsInteger(10, Count))
857     TraceIt.advance();
858   return Count;
859 }
860 
861 void PerfScriptReader::parseSample(TraceStream &TraceIt) {
862   uint64_t Count = parseAggregatedCount(TraceIt);
863   assert(Count >= 1 && "Aggregated count should be >= 1!");
864   parseSample(TraceIt, Count);
865 }
866 
867 bool PerfScriptReader::extractMMap2EventForBinary(ProfiledBinary *Binary,
868                                                   StringRef Line,
869                                                   MMapEvent &MMap) {
870   // Parse a line like:
871   //  PERF_RECORD_MMAP2 2113428/2113428: [0x7fd4efb57000(0x204000) @ 0
872   //  08:04 19532229 3585508847]: r-xp /usr/lib64/libdl-2.17.so
873   constexpr static const char *const Pattern =
874       "PERF_RECORD_MMAP2 ([0-9]+)/[0-9]+: "
875       "\\[(0x[a-f0-9]+)\\((0x[a-f0-9]+)\\) @ "
876       "(0x[a-f0-9]+|0) .*\\]: [-a-z]+ (.*)";
877   // Field 0 - whole line
878   // Field 1 - PID
879   // Field 2 - base address
880   // Field 3 - mmapped size
881   // Field 4 - page offset
882   // Field 5 - binary path
883   enum EventIndex {
884     WHOLE_LINE = 0,
885     PID = 1,
886     MMAPPED_ADDRESS = 2,
887     MMAPPED_SIZE = 3,
888     PAGE_OFFSET = 4,
889     BINARY_PATH = 5
890   };
891 
892   Regex RegMmap2(Pattern);
893   SmallVector<StringRef, 6> Fields;
894   bool R = RegMmap2.match(Line, &Fields);
895   if (!R) {
896     std::string ErrorMsg = "Cannot parse mmap event: " + Line.str() + " \n";
897     exitWithError(ErrorMsg);
898   }
899   Fields[PID].getAsInteger(10, MMap.PID);
900   Fields[MMAPPED_ADDRESS].getAsInteger(0, MMap.Address);
901   Fields[MMAPPED_SIZE].getAsInteger(0, MMap.Size);
902   Fields[PAGE_OFFSET].getAsInteger(0, MMap.Offset);
903   MMap.BinaryPath = Fields[BINARY_PATH];
904   if (ShowMmapEvents) {
905     outs() << "Mmap: Binary " << MMap.BinaryPath << " loaded at "
906            << format("0x%" PRIx64 ":", MMap.Address) << " \n";
907   }
908 
909   StringRef BinaryName = llvm::sys::path::filename(MMap.BinaryPath);
910   return Binary->getName() == BinaryName;
911 }
912 
913 void PerfScriptReader::parseMMap2Event(TraceStream &TraceIt) {
914   MMapEvent MMap;
915   if (extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap))
916     updateBinaryAddress(MMap);
917   TraceIt.advance();
918 }
919 
920 void PerfScriptReader::parseEventOrSample(TraceStream &TraceIt) {
921   if (isMMap2Event(TraceIt.getCurrentLine()))
922     parseMMap2Event(TraceIt);
923   else
924     parseSample(TraceIt);
925 }
926 
927 void PerfScriptReader::parseAndAggregateTrace() {
928   // Trace line iterator
929   TraceStream TraceIt(PerfTraceFile);
930   while (!TraceIt.isAtEoF())
931     parseEventOrSample(TraceIt);
932 }
933 
934 // A LBR sample is like:
935 // 40062f 0x5c6313f/0x5c63170/P/-/-/0  0x5c630e7/0x5c63130/P/-/-/0 ...
936 // A heuristic for fast detection by checking whether a
937 // leading "  0x" and the '/' exist.
938 bool PerfScriptReader::isLBRSample(StringRef Line) {
939   // Skip the leading instruction pointer
940   SmallVector<StringRef, 32> Records;
941   Line.trim().split(Records, " ", 2, false);
942   if (Records.size() < 2)
943     return false;
944   if (Records[1].startswith("0x") && Records[1].contains('/'))
945     return true;
946   return false;
947 }
948 
949 bool PerfScriptReader::isMMap2Event(StringRef Line) {
950   // Short cut to avoid string find is possible.
951   if (Line.empty() || Line.size() < 50)
952     return false;
953 
954   if (std::isdigit(Line[0]))
955     return false;
956 
957   // PERF_RECORD_MMAP2 does not appear at the beginning of the line
958   // for ` perf script  --show-mmap-events  -i ...`
959   return Line.contains("PERF_RECORD_MMAP2");
960 }
961 
962 // The raw hybird sample is like
963 // e.g.
964 // 	          4005dc    # call stack leaf
965 //	          400634
966 //	          400684    # call stack root
967 // 0x4005c8/0x4005dc/P/-/-/0   0x40062f/0x4005b0/P/-/-/0 ...
968 //          ... 0x4005c8/0x4005dc/P/-/-/0    # LBR Entries
969 // Determine the perfscript contains hybrid samples(call stack + LBRs) by
970 // checking whether there is a non-empty call stack immediately followed by
971 // a LBR sample
972 PerfContent PerfScriptReader::checkPerfScriptType(StringRef FileName) {
973   TraceStream TraceIt(FileName);
974   uint64_t FrameAddr = 0;
975   while (!TraceIt.isAtEoF()) {
976     // Skip the aggregated count
977     if (!TraceIt.getCurrentLine().getAsInteger(10, FrameAddr))
978       TraceIt.advance();
979 
980     // Detect sample with call stack
981     int32_t Count = 0;
982     while (!TraceIt.isAtEoF() &&
983            !TraceIt.getCurrentLine().ltrim().getAsInteger(16, FrameAddr)) {
984       Count++;
985       TraceIt.advance();
986     }
987     if (!TraceIt.isAtEoF()) {
988       if (isLBRSample(TraceIt.getCurrentLine())) {
989         if (Count > 0)
990           return PerfContent::LBRStack;
991         else
992           return PerfContent::LBR;
993       }
994       TraceIt.advance();
995     }
996   }
997 
998   exitWithError("Invalid perf script input!");
999   return PerfContent::UnknownContent;
1000 }
1001 
1002 void HybridPerfReader::generateUnsymbolizedProfile() {
1003   ProfileIsCS = !IgnoreStackSamples;
1004   if (ProfileIsCS)
1005     unwindSamples();
1006   else
1007     PerfScriptReader::generateUnsymbolizedProfile();
1008 }
1009 
1010 void PerfScriptReader::warnTruncatedStack() {
1011   for (auto Address : InvalidReturnAddresses) {
1012     WithColor::warning()
1013         << "Truncated stack sample due to invalid return address at "
1014         << format("0x%" PRIx64, Address)
1015         << ", likely caused by frame pointer omission\n";
1016   }
1017 }
1018 
1019 void PerfScriptReader::parsePerfTraces() {
1020   // Parse perf traces and do aggregation.
1021   parseAndAggregateTrace();
1022 
1023   // Generate unsymbolized profile.
1024   warnTruncatedStack();
1025   generateUnsymbolizedProfile();
1026 
1027   if (SkipSymbolization)
1028     writeUnsymbolizedProfile(OutputFilename);
1029 }
1030 
1031 } // end namespace sampleprof
1032 } // end namespace llvm
1033