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