23#define DEBUG_TYPE "correlator"
37 std::string ExpectedSectionName =
40 ExpectedSectionName = StripSuffix(ExpectedSectionName);
41 for (
auto &Section : Obj.sections()) {
48 "could not find section (" +
Twine(ExpectedSectionName) +
")");
60 auto C = std::make_unique<Context>();
62 if (
auto Err = CountersSection.takeError())
63 return std::move(Err);
67 if (
auto Err = DataSection.takeError())
68 return std::move(Err);
69 auto DataOrErr = DataSection->getContents();
71 return DataOrErr.takeError();
73 if (
auto Err = NameSection.takeError())
74 return std::move(Err);
75 auto NameOrErr = NameSection->getContents();
77 return NameOrErr.takeError();
78 C->DataStart = DataOrErr->data();
79 C->DataEnd = DataOrErr->data() + DataOrErr->size();
80 C->NameStart = NameOrErr->data();
81 C->NameSize = NameOrErr->size();
84 std::string FullSectionName =
91 MachO->fixupTable(Err)) {
92 if (Entry.isRebase() && Entry.segmentName() == SegmentAndSection[0] &&
93 Entry.sectionName() == SegmentAndSection[1]) {
94 C->MachOFixups[Entry.address() - DataSection->getAddress()] =
99 return std::move(Err);
103 C->CountersSectionStart = CountersSection->getAddress();
104 C->CountersSectionEnd =
C->CountersSectionStart + CountersSection->getSize();
107 if (
auto E = BitmapSection.takeError()) {
110 C->BitmapSectionStart = 0;
111 C->BitmapSectionEnd = 0;
113 C->BitmapSectionStart = BitmapSection->getAddress();
114 C->BitmapSectionEnd =
C->BitmapSectionStart + BitmapSection->getSize();
119 ++
C->CountersSectionStart;
120 if (
C->BitmapSectionStart)
121 ++
C->BitmapSectionStart;
133 std::string EffectiveFilename =
Filename.str();
138 "unsupported profile binary correlation when there is no build ID "
143 "unsupported profile binary correlation when there are multiple "
144 "build IDs in a profile");
155 EffectiveFilename = *Path;
159 auto DsymObjectsOrErr =
161 if (
auto Err = DsymObjectsOrErr.takeError())
162 return std::move(Err);
163 if (!DsymObjectsOrErr->empty()) {
166 if (DsymObjectsOrErr->size() > 1)
169 "using multiple objects is not yet supported");
170 EffectiveFilename = *DsymObjectsOrErr->begin();
174 if (
auto Err = BufferOrErr.takeError())
175 return std::move(Err);
177 return get(std::move(*BufferOrErr), FileKind);
181 if (
auto Err = BufferOrErr.takeError())
182 return std::move(Err);
183 return get(std::move(*BufferOrErr), FileKind);
190 if (
auto Err = BinOrErr.takeError())
191 return std::move(Err);
194 auto CtxOrErr =
Context::get(std::move(Buffer), *Obj, FileKind);
195 if (
auto Err = CtxOrErr.takeError())
196 return std::move(Err);
197 auto T = Obj->makeTriple();
211 return C->getDataSize();
213 return C->getDataSize();
221 std::unique_ptr<InstrProfCorrelator::Context>
Ctx)
226 std::unique_ptr<InstrProfCorrelator::Context>
Ctx)
240template <
class IntPtrT>
243 std::unique_ptr<InstrProfCorrelator::Context>
Ctx,
246 if (Obj.isELF() || Obj.isMachO()) {
248 return std::make_unique<DwarfInstrProfCorrelator<IntPtrT>>(
249 std::move(DICtx), std::move(
Ctx));
253 "unsupported debug info format (only DWARF is supported)");
255 if (Obj.isELF() || Obj.isCOFF() || Obj.isMachO())
256 return std::make_unique<BinaryInstrProfCorrelator<IntPtrT>>(std::move(
Ctx));
259 "unsupported binary format (only ELF, COFF, and Mach-O are supported)");
262template <
class IntPtrT>
266 if (this->
Data.empty())
269 "could not find any profile data metadata in correlated file");
271 this->CounterOffsets.clear();
272 this->BitmapOffsets.clear();
299 static const bool flow =
false;
302template <
class IntPtrT>
307 if (
Data.Probes.empty())
310 "could not find any profile data metadata in debug info");
316template <
class IntPtrT>
318 uint64_t NameRef, uint64_t CFGHash, IntPtrT CounterOffset,
319 IntPtrT BitmapOffset, IntPtrT FunctionPtr,
uint32_t NumCounters,
322 if (NumCounters && !CounterOffsets.insert(CounterOffset).second)
345template <
class IntPtrT>
346std::optional<uint64_t>
347DwarfInstrProfCorrelator<IntPtrT>::getLocation(
const DWARFDie &Die)
const {
348 auto Locations = Die.
getLocations(dwarf::DW_AT_location);
355 for (
auto &Location : *Locations) {
358 for (
auto &
Op : Expr) {
359 if (
Op.getCode() == dwarf::DW_OP_addr)
360 return Op.getRawOperand(0);
361 if (
Op.getCode() == dwarf::DW_OP_addrx) {
363 if (
auto SA = DU.getAddrOffsetSectionItem(Index))
371template <
class IntPtrT>
372bool DwarfInstrProfCorrelator<IntPtrT>::isDIEOfProbe(
const DWARFDie &Die,
377 if (Die.
getTag() != dwarf::DW_TAG_variable)
379 if (!ParentDie.isSubprogramDIE())
388template <
class IntPtrT>
389std::optional<std::pair<InstrProfCorrelator::Probe, IntPtrT>>
390DwarfInstrProfCorrelator<IntPtrT>::addCountersToDataProbe(
391 const DWARFDie &Die,
const bool UnlimitedWarnings,
392 int &NumSuppressedWarnings) {
393 std::optional<const char *> FunctionName;
394 std::optional<uint64_t> CFGHash;
395 std::optional<uint64_t> CounterPtr =
getLocation(Die);
398 std::optional<uint64_t> NumCounters;
400 if (Child.getTag() != dwarf::DW_TAG_LLVM_annotation)
402 auto AnnotationFormName = Child.find(dwarf::DW_AT_name);
403 auto AnnotationFormValue = Child.find(dwarf::DW_AT_const_value);
404 if (!AnnotationFormName || !AnnotationFormValue)
406 auto AnnotationNameOrErr = AnnotationFormName->getAsCString();
407 if (
auto Err = AnnotationNameOrErr.takeError()) {
411 StringRef AnnotationName = *AnnotationNameOrErr;
413 if (
auto EC = AnnotationFormValue->getAsCString().moveInto(FunctionName))
416 CFGHash = AnnotationFormValue->getAsUnsignedConstant();
417 }
else if (AnnotationName ==
419 NumCounters = AnnotationFormValue->getAsUnsignedConstant();
423 if (!FunctionPtr && !CounterPtr)
425 if (!FunctionName || !CFGHash || !CounterPtr || !NumCounters) {
426 if (UnlimitedWarnings || ++NumSuppressedWarnings < 1) {
428 <<
": CFGHash=" << CFGHash
429 <<
" CounterPtr=" << CounterPtr
430 <<
" NumCounters=" << NumCounters <<
"\n";
436 uint64_t CountersEnd = this->Ctx->CountersSectionEnd;
437 if (*CounterPtr < CountersStart || *CounterPtr >= CountersEnd) {
438 if (UnlimitedWarnings || ++NumSuppressedWarnings < 1) {
440 "CounterPtr out of range for function %s: Actual=0x%x "
441 "Expected=[0x%x, 0x%x)\n",
447 if (!FunctionPtr && (UnlimitedWarnings || ++NumSuppressedWarnings < 1)) {
457 P.FunctionName = *FunctionName;
459 P.LinkageName =
Name;
460 P.CFGHash = *CFGHash;
461 P.CounterOffset = CounterOffset;
462 P.NumCounters = *NumCounters;
463 auto FilePath = FnDie.getDeclFile(
465 if (!FilePath.empty())
466 P.FilePath = FilePath;
467 if (
auto LineNumber = FnDie.getDeclLine())
468 P.LineNumber = LineNumber;
470 return std::optional<std::pair<InstrProfCorrelator::Probe, IntPtrT>>(
471 {
P, FunctionPtr.value_or(0)});
474template <
class IntPtrT>
475std::optional<std::pair<InstrProfCorrelator::Probe, IntPtrT>>
476DwarfInstrProfCorrelator<IntPtrT>::addBitmapToDataProbe(
477 const DWARFDie &Die,
const bool UnlimitedWarnings,
478 int &NumSuppressedWarnings) {
479 std::optional<const char *> FunctionName;
480 std::optional<uint64_t> BitmapPtr =
getLocation(Die);
483 if (Child.getTag() != dwarf::DW_TAG_LLVM_annotation)
485 auto AnnotationFormName = Child.find(dwarf::DW_AT_name);
486 auto AnnotationFormValue = Child.find(dwarf::DW_AT_const_value);
487 if (!AnnotationFormName || !AnnotationFormValue)
489 auto AnnotationNameOrErr = AnnotationFormName->getAsCString();
490 if (
auto Err = AnnotationNameOrErr.takeError()) {
494 StringRef AnnotationName = *AnnotationNameOrErr;
496 if (
auto EC = AnnotationFormValue->getAsCString().moveInto(FunctionName))
498 }
else if (AnnotationName ==
500 std::optional<uint64_t> NumBitmapBits =
501 AnnotationFormValue->getAsUnsignedConstant();
506 if (UnlimitedWarnings || ++NumSuppressedWarnings < 1) {
508 <<
" BitmapPtr=" << BitmapPtr
514 uint64_t BitmapStart = this->Ctx->BitmapSectionStart;
515 uint64_t BitmapEnd = this->Ctx->BitmapSectionEnd;
519 "could not find profile bitmap section in correlated file");
522 if (*BitmapPtr < BitmapStart || (*BitmapPtr >= BitmapEnd &&
NumBitmapBytes)) {
523 if (UnlimitedWarnings || ++NumSuppressedWarnings < 1) {
525 "BitmapPtr out of range for function %s: Actual=0x%x "
526 "Expected=[0x%x, 0x%x)\n",
527 *FunctionName, *BitmapPtr, BitmapStart, BitmapEnd);
534 IntPtrT BitmapOffset = *BitmapPtr - BitmapStart;
536 P.FunctionName = *FunctionName;
537 P.BitmapOffset = BitmapOffset;
540 return std::optional<std::pair<InstrProfCorrelator::Probe, IntPtrT>>({
P, 0});
543template <
class IntPtrT>
544void DwarfInstrProfCorrelator<IntPtrT>::correlateProfileDataImpl(
551 bool UnlimitedWarnings = (MaxWarnings == 0);
553 int NumSuppressedWarnings = -MaxWarnings;
555 auto MaybeAddProbe = [&](
DWARFDie Die) {
556 std::optional<std::pair<InstrProfCorrelator::Probe, IntPtrT>> ProbeData;
559 addCountersToDataProbe(Die, UnlimitedWarnings, NumSuppressedWarnings);
562 addBitmapToDataProbe(Die, UnlimitedWarnings, NumSuppressedWarnings);
565 auto [Probe, FunctionPtr] = *ProbeData;
568 Probes.
try_emplace(Probe.FunctionName, Probe, FunctionPtr);
570 auto &
P = It->second.first;
572 P.LinkageName = Probe.LinkageName;
573 P.CFGHash = Probe.CFGHash;
574 P.CounterOffset = Probe.CounterOffset;
575 P.NumCounters = Probe.NumCounters;
576 P.FilePath = Probe.FilePath;
577 P.LineNumber = Probe.LineNumber;
579 P.BitmapOffset = Probe.BitmapOffset;
580 P.NumBitmapBytes = Probe.NumBitmapBytes;
584 for (
auto &
CU : DICtx->normal_units())
585 for (
const auto &Entry :
CU->dies())
587 for (
auto &
CU : DICtx->dwo_units())
588 for (
const auto &Entry :
CU->dies())
591 for (
const auto &[FunctionName, ProbeData] : Probes) {
592 const auto &[Probe, FunctionPtr] = ProbeData;
594 Data->Probes.push_back(Probe);
596 this->NamesVec.push_back(FunctionName);
598 this->addDataProbe(NameRef, Probe.CFGHash, Probe.CounterOffset,
599 Probe.BitmapOffset, FunctionPtr, Probe.NumCounters,
600 Probe.NumBitmapBytes);
603 if (!UnlimitedWarnings && NumSuppressedWarnings > 0)
605 NumSuppressedWarnings);
608template <
class IntPtrT>
609Error DwarfInstrProfCorrelator<IntPtrT>::correlateProfileNameImpl() {
610 if (this->NamesVec.empty()) {
613 "could not find any profile name metadata in debug info");
621template <
class IntPtrT>
622void BinaryInstrProfCorrelator<IntPtrT>::correlateProfileDataImpl(
625 bool UnlimitedWarnings = (MaxWarnings == 0);
627 int NumSuppressedWarnings = -MaxWarnings;
629 const RawProfData *
DataStart = (
const RawProfData *)this->Ctx->DataStart;
630 const RawProfData *DataEnd = (
const RawProfData *)this->Ctx->DataEnd;
632 for (
const RawProfData *
I =
DataStart;
I < DataEnd; ++
I) {
633 uint64_t CounterPtr = this->
template maybeSwap<IntPtrT>(
I->CounterPtr);
635 uint64_t CountersEnd = this->Ctx->CountersSectionEnd;
637 uint64_t BitmapPtr = this->
template maybeSwap<IntPtrT>(
I->BitmapPtr);
638 uint64_t BitmapStart = this->Ctx->BitmapSectionStart;
639 uint64_t BitmapEnd = this->Ctx->BitmapSectionEnd;
640 if (!BitmapStart && !BitmapEnd &&
I->NumBitmapBytes) {
643 "could not find profile bitmap section in correlated file");
646 if (!this->Ctx->MachOFixups.empty()) {
648 auto It = this->Ctx->MachOFixups.find(
Offset);
649 if (It != this->Ctx->MachOFixups.end()) {
651 }
else if (UnlimitedWarnings || ++NumSuppressedWarnings < 1) {
653 "Mach-O fixup not found for covdata offset 0x%llx\n",
Offset);
658 GetPtrByOffset(CounterOffset, CounterPtr);
659 GetPtrByOffset(BitmapOffset, BitmapPtr);
661 if (CounterPtr < CountersStart || CounterPtr >= CountersEnd) {
662 if (UnlimitedWarnings || ++NumSuppressedWarnings < 1) {
664 <<
format(
"CounterPtr out of range for function: Actual=0x%x "
665 "Expected=[0x%x, 0x%x) at data offset=0x%x\n",
670 if (
I->NumBitmapBytes &&
671 (BitmapPtr < BitmapStart || BitmapPtr >= BitmapEnd)) {
672 if (UnlimitedWarnings || ++NumSuppressedWarnings < 1) {
674 <<
format(
"BitmapPtr out of range for function: Actual=0x%x "
675 "Expected=[0x%x, 0x%x) at data offset=0x%x\n",
676 BitmapPtr, BitmapStart, BitmapEnd,
683 IntPtrT BitmapOffset = BitmapPtr - BitmapStart;
684 this->addDataProbe(
I->NameRef,
I->FuncHash, CounterOffset, BitmapOffset,
685 I->FunctionPointer,
I->NumCounters,
I->NumBitmapBytes);
689template <
class IntPtrT>
690Error BinaryInstrProfCorrelator<IntPtrT>::correlateProfileNameImpl() {
691 if (this->Ctx->NameSize == 0) {
694 "could not find any profile data metadata in object file");
696 this->Names.append(this->Ctx->NameStart, this->Ctx->NameSize);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static Expected< object::SectionRef > getInstrProfSection(const object::ObjectFile &Obj, InstrProfSectKind IPSK)
Get profile section.
static constexpr StringLiteral Filename
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
Get the first element.
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
static std::unique_ptr< DWARFContext > create(const object::ObjectFile &Obj, ProcessDebugRelocations RelocAction=ProcessDebugRelocations::Process, const LoadedObjectInfo *L=nullptr, std::string DWPName="", std::function< void(Error)> RecoverableErrorHandler=WithColor::defaultErrorHandler, std::function< void(Error)> WarningHandler=WithColor::defaultWarningHandler, bool ThreadSafe=false)
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
iterator_range< iterator > children() const
LLVM_ABI DWARFDie getParent() const
Get the parent of this DIE object.
DWARFUnit * getDwarfUnit() const
LLVM_ABI const char * getName(DINameKind Kind) const
Return the DIE name resolving DW_AT_specification or DW_AT_abstract_origin references if necessary.
dwarf::Tag getTag() const
LLVM_ABI Expected< DWARFLocationExpressionsVector > getLocations(dwarf::Attribute Attr) const
bool isNULL() const
Returns true for a valid DIE that terminates a sibling chain.
LLVM_ABI void dump(raw_ostream &OS, unsigned indent=0, DIDumpOptions DumpOpts=DIDumpOptions()) const
Dump the DIE and all of its attributes to the supplied stream.
uint8_t getAddressByteSize() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
InstrProfCorrelatorImpl - A child of InstrProfCorrelator with a template pointer type so that the Pro...
static llvm::Expected< std::unique_ptr< InstrProfCorrelatorImpl< IntPtrT > > > get(std::unique_ptr< InstrProfCorrelator::Context > Ctx, const object::ObjectFile &Obj, ProfCorrelatorKind FileKind)
virtual Error correlateProfileNameImpl()=0
virtual void correlateProfileDataImpl(int MaxWarnings, InstrProfCorrelator::CorrelationData *Data=nullptr)=0
std::vector< RawInstrProf::ProfileData< IntPtrT > > Data
Error correlateProfileData(int MaxWarnings) override
Construct a ProfileData vector used to correlate raw instrumentation data to their functions.
static bool classof(const InstrProfCorrelator *C)
InstrProfCorrelatorImpl(std::unique_ptr< InstrProfCorrelator::Context > Ctx)
void addDataProbe(uint64_t FunctionName, uint64_t CFGHash, IntPtrT CounterOffset, IntPtrT BitmapOffset, IntPtrT FunctionPtr, uint32_t NumCounters, uint32_t NumBitmapBytes)
T maybeSwap(T Value) const
Error dumpYaml(int MaxWarnings, raw_ostream &OS) override
Process debug info and dump the correlation data.
InstrProfCorrelator - A base class used to create raw instrumentation data to their functions.
static LLVM_ABI const char * FunctionNameAttributeName
static LLVM_ABI const char * CFGHashAttributeName
InstrProfCorrelator(InstrProfCorrelatorKind K, std::unique_ptr< Context > Ctx)
std::vector< std::string > NamesVec
static LLVM_ABI const char * NumCountersAttributeName
const std::unique_ptr< Context > Ctx
LLVM_ABI std::optional< size_t > getDataSize() const
Return the number of ProfileData elements.
static LLVM_ABI llvm::Expected< std::unique_ptr< InstrProfCorrelator > > get(StringRef Filename, ProfCorrelatorKind FileKind, const object::BuildIDFetcher *BIDFetcher=nullptr, const ArrayRef< llvm::object::BuildID > BIs={})
static LLVM_ABI const char * NumBitmapBitsAttributeName
This class implements a map that also provides access to all stored values in a deterministic order.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static LLVM_ABI raw_ostream & warning()
Convenience method for printing "warning: " to stderr.
BuildIDFetcher searches local cache directories for debug info.
virtual Expected< std::string > fetch(BuildIDRef BuildID) const
Returns the path to the debug file with the given build ID.
static Expected< std::vector< std::string > > findDsymObjectMembers(StringRef Path)
If the input path is a .dSYM bundle (as created by the dsymutil tool), return the paths to the object...
This class is the base class for all object file types.
This class implements an extremely fast bulk output stream that can only output to a stream.
void mapOptional(StringRef Key, T &Val)
void mapRequired(StringRef Key, T &Val)
The Output class is used to generate a yaml document from in-memory structs and vectors.
uint64_t ComputeHash(StringRef K)
std::optional< uint64_t > toAddress(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an address.
LLVM_ABI Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
MemoryLocation getLocation(Instruction *I)
constexpr bool IsLittleEndianHost
This is an optimization pass for GlobalISel generic memory operations.
RelativeUniformCounterPtr ValuesPtrExpr NumBitmapBytes
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
StringRef getInstrProfBitmapVarPrefix()
Return the name prefix of profile bitmap variables.
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr CountersStart
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
ProfCorrelatorKind
Whether the debug info or the profile metadata sections correlate raw profile data to functions.
@ unable_to_correlate_profile
DWARFExpression::Operation Op
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
LLVM_ABI Error collectGlobalObjectNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (names of global objects like functions or, virtual tables) NameStrs,...
void toHex(ArrayRef< uint8_t > Input, bool LowerCase, SmallVectorImpl< char > &Output)
Convert buffer Input to its hexadecimal representation. The returned string is double the size of Inp...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr DataStart
void consumeError(Error Err)
Consume a Error without doing anything.
Implement std::hash so that hash_code can be used in STL containers.
std::unique_ptr< MemoryBuffer > Buffer
static LLVM_ABI llvm::Expected< std::unique_ptr< Context > > get(std::unique_ptr< MemoryBuffer > Buffer, object::ObjectFile &Obj, ProfCorrelatorKind FileKind)
This class should be specialized by any type that needs to be converted to/from a YAML mapping.
This class should be specialized by any type for which vectors of that type need to be converted to/f...
static void mapping(yaml::IO &io, InstrProfCorrelator::CorrelationData &Data)
static void mapping(yaml::IO &io, InstrProfCorrelator::Probe &P)