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