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