Skip to content
Open
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
f34ab2d
[llvm-profgen] Loading binary functions from .symtab when DWARF info …
HighW4y2H3ll Oct 9, 2025
a1f32b5
Merge branch 'main' into fix-profgen-symbol
HighW4y2H3ll Oct 15, 2025
0fd352d
formatting
HighW4y2H3ll Oct 15, 2025
c097d37
Fix branch target check when an instruction branches to itself. (i.e.…
HighW4y2H3ll Oct 16, 2025
a19064d
Making the API compatible with non-ELF binaries
HighW4y2H3ll Oct 17, 2025
e12e694
Fix
HighW4y2H3ll Oct 20, 2025
5eead6b
Clean up getSymbolSize API and warnings
HighW4y2H3ll Oct 22, 2025
8f59bfa
Add cmdline option --load-function-from-symbol
HighW4y2H3ll Oct 23, 2025
a967994
Get symbol size only for ELFObjectFile
HighW4y2H3ll Oct 23, 2025
0dc2c66
Add unit test
HighW4y2H3ll Oct 23, 2025
75dc996
Nit
HighW4y2H3ll Oct 24, 2025
5600e83
Cleanup loggings and comments
HighW4y2H3ll Oct 30, 2025
0df504e
Mark function FromSymtab too if new range is found
HighW4y2H3ll Oct 31, 2025
644fce9
Formatting
HighW4y2H3ll Oct 31, 2025
9188eff
Fix suffix strip && refactor the function checks
HighW4y2H3ll Nov 1, 2025
b6ae0ba
Fixup corrupted DWARF function names using symbol table info
HighW4y2H3ll Nov 12, 2025
b1cbdd0
Fixup overwritten DWARF symbol name when decoding pseudo probe
HighW4y2H3ll Nov 14, 2025
8927a27
Fixup GuidFilter && Pseudo probe callee mismatch
HighW4y2H3ll Nov 16, 2025
108bc08
format
HighW4y2H3ll Nov 17, 2025
6e3a5ac
Clean up fixup logic in pseudo probe
HighW4y2H3ll Nov 17, 2025
3d8ad53
Further cleanup and add more GuidFilters
HighW4y2H3ll Nov 18, 2025
1344cdd
Infer callee name with pseudo probe names
HighW4y2H3ll Nov 21, 2025
2978e21
promote eligible entry point functions
HighW4y2H3ll Nov 22, 2025
eaab9df
Update pseudo probe search range && range checks
HighW4y2H3ll Nov 22, 2025
c53e0ae
Iterate through ProfiledFunctions to reduce scope
HighW4y2H3ll Nov 24, 2025
b707e80
Add usePseudoProbes() guard and comments
HighW4y2H3ll Nov 25, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions llvm/include/llvm/ProfileData/SampleProf.h
Original file line number Diff line number Diff line change
Expand Up @@ -1214,13 +1214,19 @@ class FunctionSamples {
// Note the sequence of the suffixes in the knownSuffixes array matters.
// If suffix "A" is appended after the suffix "B", "A" should be in front
// of "B" in knownSuffixes.
const char *KnownSuffixes[] = {LLVMSuffix, PartSuffix, UniqSuffix};
const SmallVector<StringRef> KnownSuffixes{LLVMSuffix, PartSuffix,
UniqSuffix};
return getCanonicalFnName(FnName, KnownSuffixes, Attr);
}

static StringRef getCanonicalFnName(StringRef FnName,
ArrayRef<StringRef> Suffixes,
StringRef Attr = "selected") {
if (Attr == "" || Attr == "all")
return FnName.split('.').first;
if (Attr == "selected") {
StringRef Cand(FnName);
for (const auto &Suf : KnownSuffixes) {
StringRef Suffix(Suf);
for (const auto Suffix : Suffixes) {
// If the profile contains ".__uniq." suffix, don't strip the
// suffix for names in the IR.
if (Suffix == UniqSuffix && FunctionSamples::HasUniqSuffix)
Expand All @@ -1229,7 +1235,7 @@ class FunctionSamples {
if (It == StringRef::npos)
continue;
auto Dit = Cand.rfind('.');
if (Dit == It + Suffix.size() - 1)
if (Dit == It || Dit == It + Suffix.size() - 1)
Cand = Cand.substr(0, It);
}
return Cand;
Expand Down
Binary file not shown.
37 changes: 37 additions & 0 deletions llvm/test/tools/llvm-profgen/missing-dwarf.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
; RUN: rm -rf %t
; RUN: mkdir -p %t
; RUN: cd %t

; RUN: echo -e "1\n401120-40113b:1\n1\n40112f->401110:1" > %t.prof

; Test --load-function-from-symbol=0
; RUN: llvm-profgen --format=text --unsymbolized-profile=%t.prof --binary=%S/Inputs/missing-dwarf.exe --output=%t1 --fill-zero-for-all-funcs --show-detailed-warning --use-offset=0 --load-function-from-symbol=0 2>&1 | FileCheck %s --check-prefix=CHECK-NO-LOAD-SYMTAB

; CHECK-NO-LOAD-SYMTAB: warning: Loading of DWARF info completed, but no binary functions have been retrieved.

; Test --load-function-from-symbol=1
; RUN: llvm-profgen --format=text --unsymbolized-profile=%t.prof --binary=%S/Inputs/missing-dwarf.exe --output=%t2 --fill-zero-for-all-funcs --show-detailed-warning --use-offset=0 --load-function-from-symbol=1
; RUN: FileCheck %s --input-file %t2 --check-prefix=CHECK-LOAD-SYMTAB

; CHECK-LOAD-SYMTAB: main:2:1
; CHECK-LOAD-SYMTAB-NEXT: 1: 1
; CHECK-LOAD-SYMTAB-NEXT: 2: 1 foo:1
; CHECK-LOAD-SYMTAB-NEXT: !CFGChecksum: 281479271677951
; CHECK-LOAD-SYMTAB-NEXT: foo:0:0
; CHECK-LOAD-SYMTAB-NEXT: 1: 0
; CHECK-LOAD-SYMTAB-NEXT: !CFGChecksum: 4294967295

; Build instructions:
; missing-dwarf.o: clang -gsplit-dwarf=split -fdebug-compilation-dir=. test.c -fdebug-info-for-profiling -fpseudo-probe-for-profiling -O0 -g -o missing-dwarf.o -c
; missing-dwarf.exe: clang -fdebug-compilation-dir=. missing-dwarf.o -o missing-dwarf.exe -fdebug-info-for-profiling -fpseudo-probe-for-profiling -O0 -g

; Source code:

int foo() {
return 1;
}

int main() {
foo();
return 0;
}
7 changes: 7 additions & 0 deletions llvm/tools/llvm-profgen/PerfReader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,7 @@ void PerfScriptReader::warnInvalidRange() {
uint64_t TotalRangeNum = 0;
uint64_t InstNotBoundary = 0;
uint64_t UnmatchedRange = 0;
uint64_t RecoveredRange = 0;
uint64_t RangeCrossFunc = 0;
uint64_t BogusRange = 0;

Expand All @@ -1309,6 +1310,9 @@ void PerfScriptReader::warnInvalidRange() {
continue;
}

if (FRange->Func->HasSymtabName)
RecoveredRange += I.second;

if (EndAddress >= FRange->EndAddress) {
RangeCrossFunc += I.second;
WarnInvalidRange(StartAddress, EndAddress, RangeCrossFuncMsg);
Expand All @@ -1328,6 +1332,9 @@ void PerfScriptReader::warnInvalidRange() {
emitWarningSummary(
UnmatchedRange, TotalRangeNum,
"of samples are from ranges that do not belong to any functions.");
emitWarningSummary(RecoveredRange, TotalRangeNum,
"of samples are from ranges that belong to functions "
"recovered from symbol table.");
emitWarningSummary(
RangeCrossFunc, TotalRangeNum,
"of samples are from ranges that do cross function boundaries.");
Expand Down
14 changes: 12 additions & 2 deletions llvm/tools/llvm-profgen/ProfileGenerator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,8 @@ void ProfileGenerator::populateBodySamplesForAllFunctions(
}

StringRef
ProfileGeneratorBase::getCalleeNameForAddress(uint64_t TargetAddress) {
ProfileGeneratorBase::getCalleeNameForAddress(uint64_t TargetAddress,
bool RestoreSymbolName) {
// Get the function range by branch target if it's a call branch.
auto *FRange = Binary->findFuncRangeForStartAddr(TargetAddress);

Expand All @@ -732,6 +733,15 @@ ProfileGeneratorBase::getCalleeNameForAddress(uint64_t TargetAddress) {
if (!FRange || !FRange->IsFuncEntry)
return StringRef();

if (RestoreSymbolName && FRange->Func->HasSymtabName) {
const AddressProbesMap &Address2ProbesMap = Binary->getAddress2ProbesMap();
for (const MCDecodedPseudoProbe &Probe :
Address2ProbesMap.find(TargetAddress)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(I'm not 100% sure) but I feel this approach might not work.

IIUC, the pseudo probe is not attached to the prologue instruction of the function, so we won't get the probes for the TargetAddress(unless the prologues are optimized away). Did you see if this condition is hit in your test?

I guess then we need another way to find the first/entry probe from the range.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also I wonder if we can just fix the FRange-->Func--> funcName in a early time(maybe a central place), the function getCalleeNameForAddress here is called for every branch sample, it would be costly. I'm thinking if we can do it earlier by iterating the function ranges just once, say if the range's function is a dwarf-symbol mismatch(i.e. theHasSymtabName), we can find the entry/first probe and use the probe GUID --> function name to fix the function name in the range, then we can avoid the fix here.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. Thanks for checking on that! I updated with a loadSymbolsFromPseudoProbe function. That loads the pseudo probe names based on the function range start address and pseudo probe address. I used a lower_bound to get the first pseudo probe of the function address, and traverse up through the inline tree to get the top-level function.

if (const auto *ProbeDesc = Binary->getFuncDescForGUID(Probe.getGuid()))
return FunctionSamples::getCanonicalFnName(ProbeDesc->FuncName);
}
}

return FunctionSamples::getCanonicalFnName(FRange->getFuncName());
}

Expand Down Expand Up @@ -1352,7 +1362,7 @@ void CSProfileGenerator::populateBoundarySamplesWithProbes(
getFunctionProfileForLeafProbe(CtxKey, CallProbe);
FunctionProfile.addBodySamples(CallProbe->getIndex(), 0, Count);
FunctionProfile.addTotalSamples(Count);
StringRef CalleeName = getCalleeNameForAddress(TargetAddress);
StringRef CalleeName = getCalleeNameForAddress(TargetAddress, true);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also need to support the probe-only(non-cs probe) path.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed! I added loadSymbolsFromPseudoProbe after each decodePseudoProbe call, and looking up the pseudo probe name is now by default in getCalleeNameForAddress

if (CalleeName.size() == 0)
continue;
FunctionProfile.addCalledTargetSamples(CallProbe->getIndex(),
Expand Down
3 changes: 2 additions & 1 deletion llvm/tools/llvm-profgen/ProfileGenerator.h
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@ class ProfileGeneratorBase {

bool filterAmbiguousProfile(FunctionSamples &FS);

StringRef getCalleeNameForAddress(uint64_t TargetAddress);
StringRef getCalleeNameForAddress(uint64_t TargetAddress,
bool RestoreSymbolName = false);

void computeSummaryAndThreshold(SampleProfileMap &ProfileMap);

Expand Down
106 changes: 104 additions & 2 deletions llvm/tools/llvm-profgen/ProfiledBinary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ static cl::list<std::string> DisassembleFunctions(
"names only. Only work with show-disassembly-only"),
cl::cat(ProfGenCategory));

static cl::opt<bool>
LoadFunctionFromSymbol("load-function-from-symbol", cl::init(true),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wlei-llvm somehow i remember we had something like that before (long time ago)? did we remove the symbol table loading code in the past?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, iirc, we initially only loaded the function ranges from symbol table, then after we found the issue with the multi-version function(foo.cold, foo.resume...), we redesigned and fully switched to load the symbol from dwarf.

At that time, the code was implemented inside the dissassembleSymbol(which also iterates the symbols),
https://github.com/llvm/llvm-project/blob/main/llvm/tools/llvm-profgen/ProfiledBinary.cpp#L529

Copy link
Contributor

@wlei-llvm wlei-llvm Oct 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For reference, this is the patch https://reviews.llvm.org/D112282 we did the switch to use dwarf symbol.

cl::desc("Gather additional binary function info "
"from symbols (e.g. .symtab) in case "
"dwarf info is incomplete."),
cl::cat(ProfGenCategory));

static cl::opt<bool>
KernelBinary("kernel",
cl::desc("Generate the profile for Linux kernel binary."),
Expand Down Expand Up @@ -257,6 +264,9 @@ void ProfiledBinary::load() {
if (ShowDisassemblyOnly)
decodePseudoProbe(Obj);

if (LoadFunctionFromSymbol && UsePseudoProbes)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is pseudo-probe required here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohh, this is to be compatible with the code here:

if (Binary->usePseudoProbes()) {
generateProbeBasedProfile();
} else {
generateLineNumBasedProfile();
}

UsePseudoProbes is needed so we won't use line numbers to generate profile, which won't work with symtab because symtab only have addresses

loadSymbolsFromSymtab(Obj);

// Disassemble the text sections.
disassemble(Obj);

Expand Down Expand Up @@ -461,6 +471,11 @@ void ProfiledBinary::decodePseudoProbe(const ObjectFile *Obj) {
} else {
for (auto *F : ProfiledFunctions) {
GuidFilter.insert(Function::getGUIDAssumingExternalLinkage(F->FuncName));
// Function may have different names in symbol table. Adding
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function may have different names in symbol table. this is not very accurate?(before the fix, we also have the different names). Please make the comment explicit about the problem and the fix.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the comment now, making it explicit that this is to solve the DWARF32 debug_str section exceeding 4GB, and causing an integer overflow..

// back all the GUIDs if possible
auto AltGUIDs = AlternativeFunctionGUIDs.equal_range(F);
for (const auto &[_, Func] : make_range(AltGUIDs))
GuidFilter.insert(Func);
for (auto &Range : F->Ranges) {
auto GUIDs = StartAddrToSymMap.equal_range(Range.first);
for (const auto &[StartAddr, Func] : make_range(GUIDs))
Expand Down Expand Up @@ -604,13 +619,13 @@ bool ProfiledBinary::dissassembleSymbol(std::size_t SI, ArrayRef<uint8_t> Bytes,
// Record potential call targets for tail frame inference later-on.
if (InferMissingFrames && FRange) {
uint64_t Target = 0;
MIA->evaluateBranch(Inst, Address, Size, Target);
bool Err = MIA->evaluateBranch(Inst, Address, Size, Target);
if (MCDesc.isCall()) {
// Indirect call targets are unknown at this point. Recording the
// unknown target (zero) for further LBR-based refinement.
MissingContextInferrer->CallEdges[Address].insert(Target);
} else if (MCDesc.isUnconditionalBranch()) {
assert(Target &&
assert(Err &&
"target should be known for unconditional direct branch");
// Any inter-function unconditional jump is considered tail call at
// this point. This is not 100% accurate and could further be
Expand Down Expand Up @@ -820,6 +835,93 @@ void ProfiledBinary::populateSymbolAddressList(const ObjectFile *Obj) {
}
}

void ProfiledBinary::loadSymbolsFromSymtab(const ObjectFile *Obj) {
// Load binary functions from symbol table when Debug info is incomplete.
// Strip the internal suffixes which are not reflected in the DWARF info.
const SmallVector<StringRef, 10> Suffixes(
{// Internal suffixes from CoroSplit pass
".cleanup", ".destroy", ".resume",
// Internal suffixes from Bolt
".cold", ".warm",
// Compiler/LTO internal
".llvm.", ".part.", ".isra.", ".constprop.", ".lto_priv."});
StringRef FileName = Obj->getFileName();
for (const SymbolRef &Symbol : Obj->symbols()) {
const SymbolRef::Type Type = unwrapOrError(Symbol.getType(), FileName);
const uint64_t StartAddr = unwrapOrError(Symbol.getAddress(), FileName);
const StringRef Name = unwrapOrError(Symbol.getName(), FileName);
uint64_t Size = 0;
if (isa<ELFObjectFileBase>(Symbol.getObject())) {
ELFSymbolRef ElfSymbol(Symbol);
Size = ElfSymbol.getSize();
}

if (Size == 0 || Type != SymbolRef::ST_Function)
continue;

const uint64_t EndAddr = StartAddr + Size;
const StringRef SymName =
FunctionSamples::getCanonicalFnName(Name, Suffixes);
assert(StartAddr < EndAddr && StartAddr >= getPreferredBaseAddress());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Add the assertion message, same to other assertions


auto Range = findFuncRange(StartAddr);
if (!Range) {
assert(findFuncRange(EndAddr - 1) == nullptr);
// Function from symbol table not found previously in DWARF, store ranges.
auto Ret = BinaryFunctions.emplace(SymName, BinaryFunction());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If a range is found, we should expect function to be found. probably want to assert(!Range || !Ret.second).

auto &Func = Ret.first->second;
if (Ret.second) {
Func.FuncName = Ret.first->first;
HashBinaryFunctions[MD5Hash(StringRef(SymName))] = &Func;
}

Func.HasSymtabName = true;
Func.Ranges.emplace_back(StartAddr, EndAddr);

auto R = StartAddrToFuncRangeMap.emplace(StartAddr, FuncRange());
FuncRange &FRange = R.first->second;

FRange.Func = &Func;
FRange.StartAddress = StartAddr;
FRange.EndAddress = EndAddr;

} else if (SymName != Range->getFuncName()) {
// Function range already found from DWARF, but the symbol name from
// symbol table is inconsistent with debug info. Log this discrepaency and
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

discrepaency --> discrepancy

// the alternative function GUID.
if (ShowDetailedWarning)
WithColor::warning()
<< "Conflicting name for symbol " << Name << " with range ("
<< format("%8" PRIx64, StartAddr) << ", "
<< format("%8" PRIx64, EndAddr) << ")"
<< ", but the DWARF symbol " << Range->getFuncName()
<< " indicates an overlapping range ("
<< format("%8" PRIx64, Range->StartAddress) << ", "
<< format("%8" PRIx64, Range->EndAddress) << ")\n";

assert(StartAddr == Range->StartAddress && EndAddr == Range->EndAddress &&
"Mismatched function range");

Range->Func->HasSymtabName = true;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HasSymtabName might be confusing. I think every the binaryfunction has the symtab name(it's just whether we use it or not).

How about use an enum instead of the bool to represent the status of symbol name and dwarf name match. Like:

enum class DwarfNameStatus : {
  Match,
  Missing, 
  Mismatch,
};

Then iiuc:

  1. if the dwarf name is missing, we load the symtab name as the name of binaryfunction
  2. if the dwarf name exists but mismatches symtab name, we still use the dwarf name(possibly invalid), but we store the alternative symtab used later for the Guidfilter.
  3. other invalid cases.

Either way, please update the comments to clarify this. Right now it’s confusing that with HasSymtabName setting to true, but sometimes the name comes from symtab and sometimes from DWARF.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Updated with this in the new commit! :)

AlternativeFunctionGUIDs.emplace(Range->Func,
MD5Hash(StringRef(SymName)));

} else if (StartAddr != Range->StartAddress &&
EndAddr != Range->EndAddress) {
// Function already found in DWARF, but the address range from symbol
// table conflicts/overlaps with the debug info.
WithColor::warning() << "Conflicting range for symbol " << Name
<< " with range (" << format("%8" PRIx64, StartAddr)
<< ", " << format("%8" PRIx64, EndAddr) << ")"
<< ", but the DWARF symbol " << Range->getFuncName()
<< " indicates another range ("
<< format("%8" PRIx64, Range->StartAddress) << ", "
<< format("%8" PRIx64, Range->EndAddress) << ")\n";
llvm_unreachable("invalid function range");
}
}
}

void ProfiledBinary::loadSymbolsFromDWARFUnit(DWARFUnit &CompilationUnit) {
for (const auto &DieInfo : CompilationUnit.dies()) {
llvm::DWARFDie Die(&CompilationUnit, &DieInfo);
Expand Down
9 changes: 9 additions & 0 deletions llvm/tools/llvm-profgen/ProfiledBinary.h
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ struct BinaryFunction {
StringRef FuncName;
// End of range is an exclusive bound.
RangesTy Ranges;
bool HasSymtabName = false;

uint64_t getFuncSize() {
uint64_t Sum = 0;
Expand Down Expand Up @@ -231,6 +232,11 @@ class ProfiledBinary {
// GUID to symbol start address map
DenseMap<uint64_t, uint64_t> SymbolStartAddrs;

// Binary function to GUID mapping that stores the alternative names in symbol
// table, despite the original name from DWARF info
std::unordered_multimap<const BinaryFunction *, uint64_t>
AlternativeFunctionGUIDs;

// These maps are for temporary use of warning diagnosis.
DenseSet<int64_t> AddrsWithMultipleSymbols;
DenseSet<std::pair<uint64_t, uint64_t>> AddrsWithInvalidInstruction;
Expand Down Expand Up @@ -356,6 +362,9 @@ class ProfiledBinary {
// Create symbol to its start address mapping.
void populateSymbolAddressList(const object::ObjectFile *O);

// Load functions from its symbol table (when DWARF info is missing).
void loadSymbolsFromSymtab(const object::ObjectFile *O);

// A function may be spilt into multiple non-continuous address ranges. We use
// this to set whether start a function range is the real entry of the
// function and also set false to the non-function label.
Expand Down
Loading