3939
4040using namespace llvm ;
4141
42+ #define DEBUG_TYPE " ctx_prof_flatten"
43+
4244namespace {
4345
4446class ProfileAnnotator final {
@@ -414,6 +416,52 @@ void removeInstrumentation(Function &F) {
414416 I.eraseFromParent ();
415417}
416418
419+ void annotateIndirectCall (
420+ Module &M, CallBase &CB,
421+ const DenseMap<uint32_t , FlatIndirectTargets> &FlatProf,
422+ const InstrProfCallsite &Ins) {
423+ auto Idx = Ins.getIndex ()->getZExtValue ();
424+ auto FIt = FlatProf.find (Idx);
425+ if (FIt == FlatProf.end ())
426+ return ;
427+ const auto &Targets = FIt->second ;
428+ SmallVector<InstrProfValueData, 2 > Data;
429+ uint64_t Sum = 0 ;
430+ for (auto &[Guid, Count] : Targets) {
431+ Data.push_back ({/* .Value=*/ Guid, /* .Count=*/ Count});
432+ Sum += Count;
433+ }
434+ llvm::annotateValueSite (M, CB, Data, Sum,
435+ InstrProfValueKind::IPVK_IndirectCallTarget,
436+ Data.size ());
437+ LLVM_DEBUG (dbgs () << " [ctxprof] flat indirect call prof: " << CB
438+ << CB.getMetadata (LLVMContext::MD_prof) << " \n " );
439+ }
440+
441+ // We normally return a "Changed" bool, but the calling pass' run assumes
442+ // something will change - some profile will be added - so this won't add much
443+ // by returning false when applicable.
444+ void annotateIndCalls (Module &M, const CtxProfAnalysis::Result &CtxProf) {
445+ const auto FlatIndCalls = CtxProf.flattenVirtCalls ();
446+ for (auto &F : M) {
447+ if (F.isDeclaration ())
448+ continue ;
449+ auto FlatProfIter = FlatIndCalls.find (AssignGUIDPass::getGUID (F));
450+ if (FlatProfIter == FlatIndCalls.end ())
451+ continue ;
452+ const auto &FlatProf = FlatProfIter->second ;
453+ for (auto &BB : F) {
454+ for (auto &I : BB) {
455+ auto *CB = dyn_cast<CallBase>(&I);
456+ if (!CB || !CB->isIndirectCall ())
457+ continue ;
458+ if (auto *Ins = CtxProfAnalysis::getCallsiteInstrumentation (*CB))
459+ annotateIndirectCall (M, *CB, FlatProf, *Ins);
460+ }
461+ }
462+ }
463+ }
464+
417465} // namespace
418466
419467PreservedAnalyses PGOCtxProfFlatteningPass::run (Module &M,
@@ -437,6 +485,8 @@ PreservedAnalyses PGOCtxProfFlatteningPass::run(Module &M,
437485 if (!IsPreThinlink && !CtxProf.isInSpecializedModule ())
438486 return PreservedAnalyses::none ();
439487
488+ if (IsPreThinlink)
489+ annotateIndCalls (M, CtxProf);
440490 const auto FlattenedProfile = CtxProf.flatten ();
441491
442492 for (auto &F : M) {
0 commit comments