[llvm-shlib] Fix the version naming style of libLLVM for Windows (#85710)
[llvm-project.git] / llvm / tools / llvm-profgen / PerfReader.cpp
blob313d40483a2591bf8627e496f539948867a027de
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"
14 #define DEBUG_TYPE "perf-reader"
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."));
21 static cl::opt<bool> ShowMmapEvents("show-mmap-events",
22 cl::desc("Print binary load events."));
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."));
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"));
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."));
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;
48 namespace llvm {
49 namespace sampleprof {
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++;
69 } else {
70 State.popFrame();
72 State.InstPtr.update(Source);
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;
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;
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;
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;
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;
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);
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);
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);
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;
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;
177 template <typename T>
178 void VirtualUnwinder::collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur,
179 T &Stack) {
180 if (Cur->RangeSamples.empty() && Cur->BranchSamples.empty())
181 return;
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));
191 for (auto &I : Cur->BranchSamples)
192 SCounter.recordBranchCount(std::get<0>(I), std::get<1>(I), std::get<2>(I));
195 template <typename T>
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);
210 // Keep note of untracked call site and deduplicate them
211 // for warning later.
212 if (!Cur->isLeafFrame())
213 UntrackedCallsites.insert(Cur->Address);
215 return;
219 collectSamplesFromFrame(Cur, Stack);
220 // Process children frame
221 for (const auto &Item : Cur->Children) {
222 collectSamplesFromFrameTrie(Item.second.get(), Stack);
224 // Recover the call stack
225 Stack.popFrame();
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);
239 void VirtualUnwinder::recordBranchCount(const LBREntry &Branch,
240 UnwindState &State, uint64_t Repeat) {
241 if (Branch.Target == ExternalAddr)
242 return;
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;
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);
263 bool VirtualUnwinder::unwind(const PerfSample *Sample, uint64_t Repeat) {
264 // Capture initial state as starting point for unwinding.
265 UnwindState State(Sample, Binary);
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;
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();
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);
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);
310 State.advanceLBR();
311 // Record `branch` with calling context after unwinding.
312 recordBranchCount(Branch, State, Repeat);
314 // As samples are aggregated on trie, record them into counter map
315 collectSamplesFromFrameTrie(State.getDummyRootPtr());
317 return true;
320 std::unique_ptr<PerfReaderBase>
321 PerfReaderBase::create(ProfiledBinary *Binary, PerfInputFile &PerfInput,
322 std::optional<uint32_t> PIDFilter) {
323 std::unique_ptr<PerfReaderBase> PerfReader;
325 if (PerfInput.Format == PerfFormat::UnsymbolizedProfile) {
326 PerfReader.reset(
327 new UnsymbolizedProfileReader(Binary, PerfInput.InputFile));
328 return PerfReader;
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);
336 assert((PerfInput.Format == PerfFormat::PerfScript) &&
337 "Should be a perfscript!");
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!");
350 return PerfReader;
353 PerfInputFile
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.");
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);
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(",");
387 PIDs.append(utostr(MMap.PID));
390 TraceIt.advance();
393 if (PIDs.empty()) {
394 exitWithError("No relevant mmap event is found in perf data.");
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);
403 return {PerfTraceFile, PerfFormat::PerfScript, PerfContent::UnknownContent};
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;
412 // Drop the event if process does not match pid filter
413 if (PIDFilter && Event.PID != *PIDFilter)
414 return;
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;
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");
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();
472 OContextStr << "0x"
473 << utohexstr(Address,
474 /*LowerCase=*/true);
476 return OContextStr.str();
477 } else {
478 llvm_unreachable("unexpected key type");
482 void HybridPerfReader::unwindSamples() {
483 VirtualUnwinder Unwinder(&SampleCounters, Binary);
484 for (const auto &Item : AggregatedSamples) {
485 const PerfSample *Sample = Item.first.getPtr();
486 Unwinder.unwind(Sample, Item.second);
489 // Warn about untracked frames due to missing probes.
490 if (ShowDetailedWarning) {
491 for (auto Address : Unwinder.getUntrackedCallsites())
492 WithColor::warning() << "Profile context truncated due to missing probe "
493 << "for call instruction at "
494 << format("0x%" PRIx64, Address) << "\n";
497 emitWarningSummary(Unwinder.getUntrackedCallsites().size(),
498 SampleCounters.size(),
499 "of profiled contexts are truncated due to missing probe "
500 "for call instruction.");
502 emitWarningSummary(
503 Unwinder.NumMismatchedExtCallBranch, Unwinder.NumTotalBranches,
504 "of branches'source is a call instruction but doesn't match call frame "
505 "stack, likely due to unwinding error of external frame.");
507 emitWarningSummary(Unwinder.NumPairedExtAddr * 2, Unwinder.NumTotalBranches,
508 "of branches containing paired external address.");
510 emitWarningSummary(Unwinder.NumUnpairedExtAddr, Unwinder.NumTotalBranches,
511 "of branches containing external address but doesn't have "
512 "another external address to pair, likely due to "
513 "interrupt jmp or broken perf script.");
515 emitWarningSummary(
516 Unwinder.NumMismatchedProEpiBranch, Unwinder.NumTotalBranches,
517 "of branches'source is a call instruction but doesn't match call frame "
518 "stack, likely due to frame in prolog/epilog.");
520 emitWarningSummary(Unwinder.NumMissingExternalFrame,
521 Unwinder.NumExtCallBranch,
522 "of artificial call branches but doesn't have an external "
523 "frame to match.");
526 bool PerfScriptReader::extractLBRStack(TraceStream &TraceIt,
527 SmallVectorImpl<LBREntry> &LBRStack) {
528 // The raw format of LBR stack is like:
529 // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
530 // ... 0x4005c8/0x4005dc/P/-/-/0
531 // It's in FIFO order and seperated by whitespace.
532 SmallVector<StringRef, 32> Records;
533 TraceIt.getCurrentLine().split(Records, " ", -1, false);
534 auto WarnInvalidLBR = [](TraceStream &TraceIt) {
535 WithColor::warning() << "Invalid address in LBR record at line "
536 << TraceIt.getLineNumber() << ": "
537 << TraceIt.getCurrentLine() << "\n";
540 // Skip the leading instruction pointer.
541 size_t Index = 0;
542 uint64_t LeadingAddr;
543 if (!Records.empty() && !Records[0].contains('/')) {
544 if (Records[0].getAsInteger(16, LeadingAddr)) {
545 WarnInvalidLBR(TraceIt);
546 TraceIt.advance();
547 return false;
549 Index = 1;
552 // Now extract LBR samples - note that we do not reverse the
553 // LBR entry order so we can unwind the sample stack as we walk
554 // through LBR entries.
555 while (Index < Records.size()) {
556 auto &Token = Records[Index++];
557 if (Token.size() == 0)
558 continue;
560 SmallVector<StringRef, 8> Addresses;
561 Token.split(Addresses, "/");
562 uint64_t Src;
563 uint64_t Dst;
565 // Stop at broken LBR records.
566 if (Addresses.size() < 2 || Addresses[0].substr(2).getAsInteger(16, Src) ||
567 Addresses[1].substr(2).getAsInteger(16, Dst)) {
568 WarnInvalidLBR(TraceIt);
569 break;
572 // Canonicalize to use preferred load address as base address.
573 Src = Binary->canonicalizeVirtualAddress(Src);
574 Dst = Binary->canonicalizeVirtualAddress(Dst);
575 bool SrcIsInternal = Binary->addressIsCode(Src);
576 bool DstIsInternal = Binary->addressIsCode(Dst);
577 if (!SrcIsInternal)
578 Src = ExternalAddr;
579 if (!DstIsInternal)
580 Dst = ExternalAddr;
581 // Filter external-to-external case to reduce LBR trace size.
582 if (!SrcIsInternal && !DstIsInternal)
583 continue;
585 LBRStack.emplace_back(LBREntry(Src, Dst));
587 TraceIt.advance();
588 return !LBRStack.empty();
591 bool PerfScriptReader::extractCallstack(TraceStream &TraceIt,
592 SmallVectorImpl<uint64_t> &CallStack) {
593 // The raw format of call stack is like:
594 // 4005dc # leaf frame
595 // 400634
596 // 400684 # root frame
597 // It's in bottom-up order with each frame in one line.
599 // Extract stack frames from sample
600 while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().starts_with(" 0x")) {
601 StringRef FrameStr = TraceIt.getCurrentLine().ltrim();
602 uint64_t FrameAddr = 0;
603 if (FrameStr.getAsInteger(16, FrameAddr)) {
604 // We might parse a non-perf sample line like empty line and comments,
605 // skip it
606 TraceIt.advance();
607 return false;
609 TraceIt.advance();
611 FrameAddr = Binary->canonicalizeVirtualAddress(FrameAddr);
612 // Currently intermixed frame from different binaries is not supported.
613 if (!Binary->addressIsCode(FrameAddr)) {
614 if (CallStack.empty())
615 NumLeafExternalFrame++;
616 // Push a special value(ExternalAddr) for the external frames so that
617 // unwinder can still work on this with artificial Call/Return branch.
618 // After unwinding, the context will be truncated for external frame.
619 // Also deduplicate the consecutive external addresses.
620 if (CallStack.empty() || CallStack.back() != ExternalAddr)
621 CallStack.emplace_back(ExternalAddr);
622 continue;
625 // We need to translate return address to call address for non-leaf frames.
626 if (!CallStack.empty()) {
627 auto CallAddr = Binary->getCallAddrFromFrameAddr(FrameAddr);
628 if (!CallAddr) {
629 // Stop at an invalid return address caused by bad unwinding. This could
630 // happen to frame-pointer-based unwinding and the callee functions that
631 // do not have the frame pointer chain set up.
632 InvalidReturnAddresses.insert(FrameAddr);
633 break;
635 FrameAddr = CallAddr;
638 CallStack.emplace_back(FrameAddr);
641 // Strip out the bottom external addr.
642 if (CallStack.size() > 1 && CallStack.back() == ExternalAddr)
643 CallStack.pop_back();
645 // Skip other unrelated line, find the next valid LBR line
646 // Note that even for empty call stack, we should skip the address at the
647 // bottom, otherwise the following pass may generate a truncated callstack
648 while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().starts_with(" 0x")) {
649 TraceIt.advance();
651 // Filter out broken stack sample. We may not have complete frame info
652 // if sample end up in prolog/epilog, the result is dangling context not
653 // connected to entry point. This should be relatively rare thus not much
654 // impact on overall profile quality. However we do want to filter them
655 // out to reduce the number of different calling contexts. One instance
656 // of such case - when sample landed in prolog/epilog, somehow stack
657 // walking will be broken in an unexpected way that higher frames will be
658 // missing.
659 return !CallStack.empty() &&
660 !Binary->addressInPrologEpilog(CallStack.front());
663 void PerfScriptReader::warnIfMissingMMap() {
664 if (!Binary->getMissingMMapWarned() && !Binary->getIsLoadedByMMap()) {
665 WithColor::warning() << "No relevant mmap event is matched for "
666 << Binary->getName()
667 << ", will use preferred address ("
668 << format("0x%" PRIx64,
669 Binary->getPreferredBaseAddress())
670 << ") as the base loading address!\n";
671 // Avoid redundant warning, only warn at the first unmatched sample.
672 Binary->setMissingMMapWarned(true);
676 void HybridPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
677 // The raw hybird sample started with call stack in FILO order and followed
678 // intermediately by LBR sample
679 // e.g.
680 // 4005dc # call stack leaf
681 // 400634
682 // 400684 # call stack root
683 // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
684 // ... 0x4005c8/0x4005dc/P/-/-/0 # LBR Entries
686 std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
687 #ifndef NDEBUG
688 Sample->Linenum = TraceIt.getLineNumber();
689 #endif
690 // Parsing call stack and populate into PerfSample.CallStack
691 if (!extractCallstack(TraceIt, Sample->CallStack)) {
692 // Skip the next LBR line matched current call stack
693 if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().starts_with(" 0x"))
694 TraceIt.advance();
695 return;
698 warnIfMissingMMap();
700 if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().starts_with(" 0x")) {
701 // Parsing LBR stack and populate into PerfSample.LBRStack
702 if (extractLBRStack(TraceIt, Sample->LBRStack)) {
703 if (IgnoreStackSamples) {
704 Sample->CallStack.clear();
705 } else {
706 // Canonicalize stack leaf to avoid 'random' IP from leaf frame skew LBR
707 // ranges
708 Sample->CallStack.front() = Sample->LBRStack[0].Target;
710 // Record samples by aggregation
711 AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
713 } else {
714 // LBR sample is encoded in single line after stack sample
715 exitWithError("'Hybrid perf sample is corrupted, No LBR sample line");
719 void PerfScriptReader::writeUnsymbolizedProfile(StringRef Filename) {
720 std::error_code EC;
721 raw_fd_ostream OS(Filename, EC, llvm::sys::fs::OF_TextWithCRLF);
722 if (EC)
723 exitWithError(EC, Filename);
724 writeUnsymbolizedProfile(OS);
727 // Use ordered map to make the output deterministic
728 using OrderedCounterForPrint = std::map<std::string, SampleCounter *>;
730 void PerfScriptReader::writeUnsymbolizedProfile(raw_fd_ostream &OS) {
731 OrderedCounterForPrint OrderedCounters;
732 for (auto &CI : SampleCounters) {
733 OrderedCounters[getContextKeyStr(CI.first.getPtr(), Binary)] = &CI.second;
736 auto SCounterPrinter = [&](RangeSample &Counter, StringRef Separator,
737 uint32_t Indent) {
738 OS.indent(Indent);
739 OS << Counter.size() << "\n";
740 for (auto &I : Counter) {
741 uint64_t Start = I.first.first;
742 uint64_t End = I.first.second;
744 if (UseOffset) {
745 if (UseLoadableSegmentAsBase) {
746 Start -= Binary->getFirstLoadableAddress();
747 End -= Binary->getFirstLoadableAddress();
748 } else {
749 Start -= Binary->getPreferredBaseAddress();
750 End -= Binary->getPreferredBaseAddress();
754 OS.indent(Indent);
755 OS << Twine::utohexstr(Start) << Separator << Twine::utohexstr(End) << ":"
756 << I.second << "\n";
760 for (auto &CI : OrderedCounters) {
761 uint32_t Indent = 0;
762 if (ProfileIsCS) {
763 // Context string key
764 OS << "[" << CI.first << "]\n";
765 Indent = 2;
768 SampleCounter &Counter = *CI.second;
769 SCounterPrinter(Counter.RangeCounter, "-", Indent);
770 SCounterPrinter(Counter.BranchCounter, "->", Indent);
774 // Format of input:
775 // number of entries in RangeCounter
776 // from_1-to_1:count_1
777 // from_2-to_2:count_2
778 // ......
779 // from_n-to_n:count_n
780 // number of entries in BranchCounter
781 // src_1->dst_1:count_1
782 // src_2->dst_2:count_2
783 // ......
784 // src_n->dst_n:count_n
785 void UnsymbolizedProfileReader::readSampleCounters(TraceStream &TraceIt,
786 SampleCounter &SCounters) {
787 auto exitWithErrorForTraceLine = [](TraceStream &TraceIt) {
788 std::string Msg = TraceIt.isAtEoF()
789 ? "Invalid raw profile!"
790 : "Invalid raw profile at line " +
791 Twine(TraceIt.getLineNumber()).str() + ": " +
792 TraceIt.getCurrentLine().str();
793 exitWithError(Msg);
795 auto ReadNumber = [&](uint64_t &Num) {
796 if (TraceIt.isAtEoF())
797 exitWithErrorForTraceLine(TraceIt);
798 if (TraceIt.getCurrentLine().ltrim().getAsInteger(10, Num))
799 exitWithErrorForTraceLine(TraceIt);
800 TraceIt.advance();
803 auto ReadCounter = [&](RangeSample &Counter, StringRef Separator) {
804 uint64_t Num = 0;
805 ReadNumber(Num);
806 while (Num--) {
807 if (TraceIt.isAtEoF())
808 exitWithErrorForTraceLine(TraceIt);
809 StringRef Line = TraceIt.getCurrentLine().ltrim();
811 uint64_t Count = 0;
812 auto LineSplit = Line.split(":");
813 if (LineSplit.second.empty() || LineSplit.second.getAsInteger(10, Count))
814 exitWithErrorForTraceLine(TraceIt);
816 uint64_t Source = 0;
817 uint64_t Target = 0;
818 auto Range = LineSplit.first.split(Separator);
819 if (Range.second.empty() || Range.first.getAsInteger(16, Source) ||
820 Range.second.getAsInteger(16, Target))
821 exitWithErrorForTraceLine(TraceIt);
823 if (UseOffset) {
824 if (UseLoadableSegmentAsBase) {
825 Source += Binary->getFirstLoadableAddress();
826 Target += Binary->getFirstLoadableAddress();
827 } else {
828 Source += Binary->getPreferredBaseAddress();
829 Target += Binary->getPreferredBaseAddress();
833 Counter[{Source, Target}] += Count;
834 TraceIt.advance();
838 ReadCounter(SCounters.RangeCounter, "-");
839 ReadCounter(SCounters.BranchCounter, "->");
842 void UnsymbolizedProfileReader::readUnsymbolizedProfile(StringRef FileName) {
843 TraceStream TraceIt(FileName);
844 while (!TraceIt.isAtEoF()) {
845 std::shared_ptr<StringBasedCtxKey> Key =
846 std::make_shared<StringBasedCtxKey>();
847 StringRef Line = TraceIt.getCurrentLine();
848 // Read context stack for CS profile.
849 if (Line.starts_with("[")) {
850 ProfileIsCS = true;
851 auto I = ContextStrSet.insert(Line.str());
852 SampleContext::createCtxVectorFromStr(*I.first, Key->Context);
853 TraceIt.advance();
855 auto Ret =
856 SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
857 readSampleCounters(TraceIt, Ret.first->second);
861 void UnsymbolizedProfileReader::parsePerfTraces() {
862 readUnsymbolizedProfile(PerfTraceFile);
865 void PerfScriptReader::computeCounterFromLBR(const PerfSample *Sample,
866 uint64_t Repeat) {
867 SampleCounter &Counter = SampleCounters.begin()->second;
868 uint64_t EndAddress = 0;
869 for (const LBREntry &LBR : Sample->LBRStack) {
870 uint64_t SourceAddress = LBR.Source;
871 uint64_t TargetAddress = LBR.Target;
873 // Record the branch if its SourceAddress is external. It can be the case an
874 // external source call an internal function, later this branch will be used
875 // to generate the function's head sample.
876 if (Binary->addressIsCode(TargetAddress)) {
877 Counter.recordBranchCount(SourceAddress, TargetAddress, Repeat);
880 // If this not the first LBR, update the range count between TO of current
881 // LBR and FROM of next LBR.
882 uint64_t StartAddress = TargetAddress;
883 if (Binary->addressIsCode(StartAddress) &&
884 Binary->addressIsCode(EndAddress) &&
885 isValidFallThroughRange(StartAddress, EndAddress, Binary))
886 Counter.recordRangeCount(StartAddress, EndAddress, Repeat);
887 EndAddress = SourceAddress;
891 void LBRPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
892 std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
893 // Parsing LBR stack and populate into PerfSample.LBRStack
894 if (extractLBRStack(TraceIt, Sample->LBRStack)) {
895 warnIfMissingMMap();
896 // Record LBR only samples by aggregation
897 AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
901 void PerfScriptReader::generateUnsymbolizedProfile() {
902 // There is no context for LBR only sample, so initialize one entry with
903 // fake "empty" context key.
904 assert(SampleCounters.empty() &&
905 "Sample counter map should be empty before raw profile generation");
906 std::shared_ptr<StringBasedCtxKey> Key =
907 std::make_shared<StringBasedCtxKey>();
908 SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
909 for (const auto &Item : AggregatedSamples) {
910 const PerfSample *Sample = Item.first.getPtr();
911 computeCounterFromLBR(Sample, Item.second);
915 uint64_t PerfScriptReader::parseAggregatedCount(TraceStream &TraceIt) {
916 // The aggregated count is optional, so do not skip the line and return 1 if
917 // it's unmatched
918 uint64_t Count = 1;
919 if (!TraceIt.getCurrentLine().getAsInteger(10, Count))
920 TraceIt.advance();
921 return Count;
924 void PerfScriptReader::parseSample(TraceStream &TraceIt) {
925 NumTotalSample++;
926 uint64_t Count = parseAggregatedCount(TraceIt);
927 assert(Count >= 1 && "Aggregated count should be >= 1!");
928 parseSample(TraceIt, Count);
931 bool PerfScriptReader::extractMMap2EventForBinary(ProfiledBinary *Binary,
932 StringRef Line,
933 MMapEvent &MMap) {
934 // Parse a line like:
935 // PERF_RECORD_MMAP2 2113428/2113428: [0x7fd4efb57000(0x204000) @ 0
936 // 08:04 19532229 3585508847]: r-xp /usr/lib64/libdl-2.17.so
937 constexpr static const char *const Pattern =
938 "PERF_RECORD_MMAP2 ([0-9]+)/[0-9]+: "
939 "\\[(0x[a-f0-9]+)\\((0x[a-f0-9]+)\\) @ "
940 "(0x[a-f0-9]+|0) .*\\]: [-a-z]+ (.*)";
941 // Field 0 - whole line
942 // Field 1 - PID
943 // Field 2 - base address
944 // Field 3 - mmapped size
945 // Field 4 - page offset
946 // Field 5 - binary path
947 enum EventIndex {
948 WHOLE_LINE = 0,
949 PID = 1,
950 MMAPPED_ADDRESS = 2,
951 MMAPPED_SIZE = 3,
952 PAGE_OFFSET = 4,
953 BINARY_PATH = 5
956 Regex RegMmap2(Pattern);
957 SmallVector<StringRef, 6> Fields;
958 bool R = RegMmap2.match(Line, &Fields);
959 if (!R) {
960 std::string WarningMsg = "Cannot parse mmap event: " + Line.str() + " \n";
961 WithColor::warning() << WarningMsg;
963 Fields[PID].getAsInteger(10, MMap.PID);
964 Fields[MMAPPED_ADDRESS].getAsInteger(0, MMap.Address);
965 Fields[MMAPPED_SIZE].getAsInteger(0, MMap.Size);
966 Fields[PAGE_OFFSET].getAsInteger(0, MMap.Offset);
967 MMap.BinaryPath = Fields[BINARY_PATH];
968 if (ShowMmapEvents) {
969 outs() << "Mmap: Binary " << MMap.BinaryPath << " loaded at "
970 << format("0x%" PRIx64 ":", MMap.Address) << " \n";
973 StringRef BinaryName = llvm::sys::path::filename(MMap.BinaryPath);
974 return Binary->getName() == BinaryName;
977 void PerfScriptReader::parseMMap2Event(TraceStream &TraceIt) {
978 MMapEvent MMap;
979 if (extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap))
980 updateBinaryAddress(MMap);
981 TraceIt.advance();
984 void PerfScriptReader::parseEventOrSample(TraceStream &TraceIt) {
985 if (isMMap2Event(TraceIt.getCurrentLine()))
986 parseMMap2Event(TraceIt);
987 else
988 parseSample(TraceIt);
991 void PerfScriptReader::parseAndAggregateTrace() {
992 // Trace line iterator
993 TraceStream TraceIt(PerfTraceFile);
994 while (!TraceIt.isAtEoF())
995 parseEventOrSample(TraceIt);
998 // A LBR sample is like:
999 // 40062f 0x5c6313f/0x5c63170/P/-/-/0 0x5c630e7/0x5c63130/P/-/-/0 ...
1000 // A heuristic for fast detection by checking whether a
1001 // leading " 0x" and the '/' exist.
1002 bool PerfScriptReader::isLBRSample(StringRef Line) {
1003 // Skip the leading instruction pointer
1004 SmallVector<StringRef, 32> Records;
1005 Line.trim().split(Records, " ", 2, false);
1006 if (Records.size() < 2)
1007 return false;
1008 if (Records[1].starts_with("0x") && Records[1].contains('/'))
1009 return true;
1010 return false;
1013 bool PerfScriptReader::isMMap2Event(StringRef Line) {
1014 // Short cut to avoid string find is possible.
1015 if (Line.empty() || Line.size() < 50)
1016 return false;
1018 if (std::isdigit(Line[0]))
1019 return false;
1021 // PERF_RECORD_MMAP2 does not appear at the beginning of the line
1022 // for ` perf script --show-mmap-events -i ...`
1023 return Line.contains("PERF_RECORD_MMAP2");
1026 // The raw hybird sample is like
1027 // e.g.
1028 // 4005dc # call stack leaf
1029 // 400634
1030 // 400684 # call stack root
1031 // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
1032 // ... 0x4005c8/0x4005dc/P/-/-/0 # LBR Entries
1033 // Determine the perfscript contains hybrid samples(call stack + LBRs) by
1034 // checking whether there is a non-empty call stack immediately followed by
1035 // a LBR sample
1036 PerfContent PerfScriptReader::checkPerfScriptType(StringRef FileName) {
1037 TraceStream TraceIt(FileName);
1038 uint64_t FrameAddr = 0;
1039 while (!TraceIt.isAtEoF()) {
1040 // Skip the aggregated count
1041 if (!TraceIt.getCurrentLine().getAsInteger(10, FrameAddr))
1042 TraceIt.advance();
1044 // Detect sample with call stack
1045 int32_t Count = 0;
1046 while (!TraceIt.isAtEoF() &&
1047 !TraceIt.getCurrentLine().ltrim().getAsInteger(16, FrameAddr)) {
1048 Count++;
1049 TraceIt.advance();
1051 if (!TraceIt.isAtEoF()) {
1052 if (isLBRSample(TraceIt.getCurrentLine())) {
1053 if (Count > 0)
1054 return PerfContent::LBRStack;
1055 else
1056 return PerfContent::LBR;
1058 TraceIt.advance();
1062 exitWithError("Invalid perf script input!");
1063 return PerfContent::UnknownContent;
1066 void HybridPerfReader::generateUnsymbolizedProfile() {
1067 ProfileIsCS = !IgnoreStackSamples;
1068 if (ProfileIsCS)
1069 unwindSamples();
1070 else
1071 PerfScriptReader::generateUnsymbolizedProfile();
1074 void PerfScriptReader::warnTruncatedStack() {
1075 if (ShowDetailedWarning) {
1076 for (auto Address : InvalidReturnAddresses) {
1077 WithColor::warning()
1078 << "Truncated stack sample due to invalid return address at "
1079 << format("0x%" PRIx64, Address)
1080 << ", likely caused by frame pointer omission\n";
1083 emitWarningSummary(
1084 InvalidReturnAddresses.size(), AggregatedSamples.size(),
1085 "of truncated stack samples due to invalid return address, "
1086 "likely caused by frame pointer omission.");
1089 void PerfScriptReader::warnInvalidRange() {
1090 std::unordered_map<std::pair<uint64_t, uint64_t>, uint64_t,
1091 pair_hash<uint64_t, uint64_t>>
1092 Ranges;
1094 for (const auto &Item : AggregatedSamples) {
1095 const PerfSample *Sample = Item.first.getPtr();
1096 uint64_t Count = Item.second;
1097 uint64_t EndAddress = 0;
1098 for (const LBREntry &LBR : Sample->LBRStack) {
1099 uint64_t SourceAddress = LBR.Source;
1100 uint64_t StartAddress = LBR.Target;
1101 if (EndAddress != 0)
1102 Ranges[{StartAddress, EndAddress}] += Count;
1103 EndAddress = SourceAddress;
1107 if (Ranges.empty()) {
1108 WithColor::warning() << "No samples in perf script!\n";
1109 return;
1112 auto WarnInvalidRange = [&](uint64_t StartAddress, uint64_t EndAddress,
1113 StringRef Msg) {
1114 if (!ShowDetailedWarning)
1115 return;
1116 WithColor::warning() << "[" << format("%8" PRIx64, StartAddress) << ","
1117 << format("%8" PRIx64, EndAddress) << "]: " << Msg
1118 << "\n";
1121 const char *EndNotBoundaryMsg = "Range is not on instruction boundary, "
1122 "likely due to profile and binary mismatch.";
1123 const char *DanglingRangeMsg = "Range does not belong to any functions, "
1124 "likely from PLT, .init or .fini section.";
1125 const char *RangeCrossFuncMsg =
1126 "Fall through range should not cross function boundaries, likely due to "
1127 "profile and binary mismatch.";
1128 const char *BogusRangeMsg = "Range start is after or too far from range end.";
1130 uint64_t TotalRangeNum = 0;
1131 uint64_t InstNotBoundary = 0;
1132 uint64_t UnmatchedRange = 0;
1133 uint64_t RangeCrossFunc = 0;
1134 uint64_t BogusRange = 0;
1136 for (auto &I : Ranges) {
1137 uint64_t StartAddress = I.first.first;
1138 uint64_t EndAddress = I.first.second;
1139 TotalRangeNum += I.second;
1141 if (!Binary->addressIsCode(StartAddress) &&
1142 !Binary->addressIsCode(EndAddress))
1143 continue;
1145 if (!Binary->addressIsCode(StartAddress) ||
1146 !Binary->addressIsTransfer(EndAddress)) {
1147 InstNotBoundary += I.second;
1148 WarnInvalidRange(StartAddress, EndAddress, EndNotBoundaryMsg);
1151 auto *FRange = Binary->findFuncRange(StartAddress);
1152 if (!FRange) {
1153 UnmatchedRange += I.second;
1154 WarnInvalidRange(StartAddress, EndAddress, DanglingRangeMsg);
1155 continue;
1158 if (EndAddress >= FRange->EndAddress) {
1159 RangeCrossFunc += I.second;
1160 WarnInvalidRange(StartAddress, EndAddress, RangeCrossFuncMsg);
1163 if (Binary->addressIsCode(StartAddress) &&
1164 Binary->addressIsCode(EndAddress) &&
1165 !isValidFallThroughRange(StartAddress, EndAddress, Binary)) {
1166 BogusRange += I.second;
1167 WarnInvalidRange(StartAddress, EndAddress, BogusRangeMsg);
1171 emitWarningSummary(
1172 InstNotBoundary, TotalRangeNum,
1173 "of samples are from ranges that are not on instruction boundary.");
1174 emitWarningSummary(
1175 UnmatchedRange, TotalRangeNum,
1176 "of samples are from ranges that do not belong to any functions.");
1177 emitWarningSummary(
1178 RangeCrossFunc, TotalRangeNum,
1179 "of samples are from ranges that do cross function boundaries.");
1180 emitWarningSummary(
1181 BogusRange, TotalRangeNum,
1182 "of samples are from ranges that have range start after or too far from "
1183 "range end acrossing the unconditinal jmp.");
1186 void PerfScriptReader::parsePerfTraces() {
1187 // Parse perf traces and do aggregation.
1188 parseAndAggregateTrace();
1190 emitWarningSummary(NumLeafExternalFrame, NumTotalSample,
1191 "of samples have leaf external frame in call stack.");
1192 emitWarningSummary(NumLeadingOutgoingLBR, NumTotalSample,
1193 "of samples have leading external LBR.");
1195 // Generate unsymbolized profile.
1196 warnTruncatedStack();
1197 warnInvalidRange();
1198 generateUnsymbolizedProfile();
1199 AggregatedSamples.clear();
1201 if (SkipSymbolization)
1202 writeUnsymbolizedProfile(OutputFilename);
1205 } // end namespace sampleprof
1206 } // end namespace llvm