10b57cec5SDimitry Andric //===- IndirectCallPromotion.cpp - Optimizations based on value profiling -===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the transformation that promotes indirect calls to
100b57cec5SDimitry Andric // conditional direct calls when the indirect-call value profile metadata is
110b57cec5SDimitry Andric // available.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
160b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
170b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/IndirectCallVisitor.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
220b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
230b57cec5SDimitry Andric #include "llvm/IR/Function.h"
240b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
250b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
260b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
270b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
280b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
295f757f3fSDimitry Andric #include "llvm/IR/ProfDataUtils.h"
300b57cec5SDimitry Andric #include "llvm/IR/Value.h"
310b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
320b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
330b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
340b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
350b57cec5SDimitry Andric #include "llvm/Support/Error.h"
360b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
370b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation.h"
380b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
390b57cec5SDimitry Andric #include "llvm/Transforms/Utils/CallPromotionUtils.h"
400b57cec5SDimitry Andric #include <cassert>
410b57cec5SDimitry Andric #include <cstdint>
420b57cec5SDimitry Andric #include <memory>
430b57cec5SDimitry Andric #include <string>
440b57cec5SDimitry Andric #include <utility>
450b57cec5SDimitry Andric #include <vector>
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric using namespace llvm;
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric #define DEBUG_TYPE "pgo-icall-prom"
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric STATISTIC(NumOfPGOICallPromotion, "Number of indirect call promotions.");
520b57cec5SDimitry Andric STATISTIC(NumOfPGOICallsites, "Number of indirect call candidate sites.");
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric // Command line option to disable indirect-call promotion with the default as
550b57cec5SDimitry Andric // false. This is for debug purpose.
560b57cec5SDimitry Andric static cl::opt<bool> DisableICP("disable-icp", cl::init(false), cl::Hidden,
570b57cec5SDimitry Andric                                 cl::desc("Disable indirect call promotion"));
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric // Set the cutoff value for the promotion. If the value is other than 0, we
600b57cec5SDimitry Andric // stop the transformation once the total number of promotions equals the cutoff
610b57cec5SDimitry Andric // value.
620b57cec5SDimitry Andric // For debug use only.
630b57cec5SDimitry Andric static cl::opt<unsigned>
6481ad6265SDimitry Andric     ICPCutOff("icp-cutoff", cl::init(0), cl::Hidden,
650b57cec5SDimitry Andric               cl::desc("Max number of promotions for this compilation"));
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric // If ICPCSSkip is non zero, the first ICPCSSkip callsites will be skipped.
680b57cec5SDimitry Andric // For debug use only.
690b57cec5SDimitry Andric static cl::opt<unsigned>
7081ad6265SDimitry Andric     ICPCSSkip("icp-csskip", cl::init(0), cl::Hidden,
710b57cec5SDimitry Andric               cl::desc("Skip Callsite up to this number for this compilation"));
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric // Set if the pass is called in LTO optimization. The difference for LTO mode
740b57cec5SDimitry Andric // is the pass won't prefix the source module name to the internal linkage
750b57cec5SDimitry Andric // symbols.
760b57cec5SDimitry Andric static cl::opt<bool> ICPLTOMode("icp-lto", cl::init(false), cl::Hidden,
770b57cec5SDimitry Andric                                 cl::desc("Run indirect-call promotion in LTO "
780b57cec5SDimitry Andric                                          "mode"));
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric // Set if the pass is called in SamplePGO mode. The difference for SamplePGO
810b57cec5SDimitry Andric // mode is it will add prof metadatato the created direct call.
820b57cec5SDimitry Andric static cl::opt<bool>
830b57cec5SDimitry Andric     ICPSamplePGOMode("icp-samplepgo", cl::init(false), cl::Hidden,
840b57cec5SDimitry Andric                      cl::desc("Run indirect-call promotion in SamplePGO mode"));
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric // If the option is set to true, only call instructions will be considered for
870b57cec5SDimitry Andric // transformation -- invoke instructions will be ignored.
880b57cec5SDimitry Andric static cl::opt<bool>
890b57cec5SDimitry Andric     ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden,
900b57cec5SDimitry Andric                 cl::desc("Run indirect-call promotion for call instructions "
910b57cec5SDimitry Andric                          "only"));
920b57cec5SDimitry Andric 
930b57cec5SDimitry Andric // If the option is set to true, only invoke instructions will be considered for
940b57cec5SDimitry Andric // transformation -- call instructions will be ignored.
950b57cec5SDimitry Andric static cl::opt<bool> ICPInvokeOnly("icp-invoke-only", cl::init(false),
960b57cec5SDimitry Andric                                    cl::Hidden,
970b57cec5SDimitry Andric                                    cl::desc("Run indirect-call promotion for "
980b57cec5SDimitry Andric                                             "invoke instruction only"));
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric // Dump the function level IR if the transformation happened in this
1010b57cec5SDimitry Andric // function. For debug use only.
1020b57cec5SDimitry Andric static cl::opt<bool>
1030b57cec5SDimitry Andric     ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden,
1040b57cec5SDimitry Andric                  cl::desc("Dump IR after transformation happens"));
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric namespace {
1070b57cec5SDimitry Andric 
10806c3fb27SDimitry Andric // Promote indirect calls to conditional direct calls, keeping track of
10906c3fb27SDimitry Andric // thresholds.
11006c3fb27SDimitry Andric class IndirectCallPromoter {
1110b57cec5SDimitry Andric private:
1120b57cec5SDimitry Andric   Function &F;
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   // Symtab that maps indirect call profile values to function names and
1150b57cec5SDimitry Andric   // defines.
11606c3fb27SDimitry Andric   InstrProfSymtab *const Symtab;
1170b57cec5SDimitry Andric 
11806c3fb27SDimitry Andric   const bool SamplePGO;
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric   OptimizationRemarkEmitter &ORE;
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric   // A struct that records the direct target and it's call count.
1230b57cec5SDimitry Andric   struct PromotionCandidate {
12406c3fb27SDimitry Andric     Function *const TargetFunction;
12506c3fb27SDimitry Andric     const uint64_t Count;
1260b57cec5SDimitry Andric 
PromotionCandidate__anon7888434e0111::IndirectCallPromoter::PromotionCandidate1270b57cec5SDimitry Andric     PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {}
1280b57cec5SDimitry Andric   };
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric   // Check if the indirect-call call site should be promoted. Return the number
1310b57cec5SDimitry Andric   // of promotions. Inst is the candidate indirect call, ValueDataRef
1320b57cec5SDimitry Andric   // contains the array of value profile data for profiled targets,
1330b57cec5SDimitry Andric   // TotalCount is the total profiled count of call executions, and
1340b57cec5SDimitry Andric   // NumCandidates is the number of candidate entries in ValueDataRef.
1350b57cec5SDimitry Andric   std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(
1365ffd83dbSDimitry Andric       const CallBase &CB, const ArrayRef<InstrProfValueData> &ValueDataRef,
1370b57cec5SDimitry Andric       uint64_t TotalCount, uint32_t NumCandidates);
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   // Promote a list of targets for one indirect-call callsite. Return
1400b57cec5SDimitry Andric   // the number of promotions.
1415ffd83dbSDimitry Andric   uint32_t tryToPromote(CallBase &CB,
1420b57cec5SDimitry Andric                         const std::vector<PromotionCandidate> &Candidates,
1430b57cec5SDimitry Andric                         uint64_t &TotalCount);
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric public:
IndirectCallPromoter(Function & Func,InstrProfSymtab * Symtab,bool SamplePGO,OptimizationRemarkEmitter & ORE)14606c3fb27SDimitry Andric   IndirectCallPromoter(Function &Func, InstrProfSymtab *Symtab, bool SamplePGO,
14706c3fb27SDimitry Andric                        OptimizationRemarkEmitter &ORE)
14806c3fb27SDimitry Andric       : F(Func), Symtab(Symtab), SamplePGO(SamplePGO), ORE(ORE) {}
14906c3fb27SDimitry Andric   IndirectCallPromoter(const IndirectCallPromoter &) = delete;
15006c3fb27SDimitry Andric   IndirectCallPromoter &operator=(const IndirectCallPromoter &) = delete;
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   bool processFunction(ProfileSummaryInfo *PSI);
1530b57cec5SDimitry Andric };
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric } // end anonymous namespace
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric // Indirect-call promotion heuristic. The direct targets are sorted based on
1580b57cec5SDimitry Andric // the count. Stop at the first target that is not promoted.
15906c3fb27SDimitry Andric std::vector<IndirectCallPromoter::PromotionCandidate>
getPromotionCandidatesForCallSite(const CallBase & CB,const ArrayRef<InstrProfValueData> & ValueDataRef,uint64_t TotalCount,uint32_t NumCandidates)16006c3fb27SDimitry Andric IndirectCallPromoter::getPromotionCandidatesForCallSite(
1615ffd83dbSDimitry Andric     const CallBase &CB, const ArrayRef<InstrProfValueData> &ValueDataRef,
1620b57cec5SDimitry Andric     uint64_t TotalCount, uint32_t NumCandidates) {
1630b57cec5SDimitry Andric   std::vector<PromotionCandidate> Ret;
1640b57cec5SDimitry Andric 
1655ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << CB
1660b57cec5SDimitry Andric                     << " Num_targets: " << ValueDataRef.size()
1670b57cec5SDimitry Andric                     << " Num_candidates: " << NumCandidates << "\n");
1680b57cec5SDimitry Andric   NumOfPGOICallsites++;
1690b57cec5SDimitry Andric   if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) {
1700b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " Skip: User options.\n");
1710b57cec5SDimitry Andric     return Ret;
1720b57cec5SDimitry Andric   }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   for (uint32_t I = 0; I < NumCandidates; I++) {
1750b57cec5SDimitry Andric     uint64_t Count = ValueDataRef[I].Count;
1760b57cec5SDimitry Andric     assert(Count <= TotalCount);
177fe6060f1SDimitry Andric     (void)TotalCount;
1780b57cec5SDimitry Andric     uint64_t Target = ValueDataRef[I].Value;
1790b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
1800b57cec5SDimitry Andric                       << "  Target_func: " << Target << "\n");
1810b57cec5SDimitry Andric 
1825ffd83dbSDimitry Andric     if (ICPInvokeOnly && isa<CallInst>(CB)) {
1830b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " Not promote: User options.\n");
1840b57cec5SDimitry Andric       ORE.emit([&]() {
1855ffd83dbSDimitry Andric         return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB)
1860b57cec5SDimitry Andric                << " Not promote: User options";
1870b57cec5SDimitry Andric       });
1880b57cec5SDimitry Andric       break;
1890b57cec5SDimitry Andric     }
1905ffd83dbSDimitry Andric     if (ICPCallOnly && isa<InvokeInst>(CB)) {
1910b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " Not promote: User option.\n");
1920b57cec5SDimitry Andric       ORE.emit([&]() {
1935ffd83dbSDimitry Andric         return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB)
1940b57cec5SDimitry Andric                << " Not promote: User options";
1950b57cec5SDimitry Andric       });
1960b57cec5SDimitry Andric       break;
1970b57cec5SDimitry Andric     }
1980b57cec5SDimitry Andric     if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
1990b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " Not promote: Cutoff reached.\n");
2000b57cec5SDimitry Andric       ORE.emit([&]() {
2015ffd83dbSDimitry Andric         return OptimizationRemarkMissed(DEBUG_TYPE, "CutOffReached", &CB)
2020b57cec5SDimitry Andric                << " Not promote: Cutoff reached";
2030b57cec5SDimitry Andric       });
2040b57cec5SDimitry Andric       break;
2050b57cec5SDimitry Andric     }
2060b57cec5SDimitry Andric 
207e8d8bef9SDimitry Andric     // Don't promote if the symbol is not defined in the module. This avoids
208e8d8bef9SDimitry Andric     // creating a reference to a symbol that doesn't exist in the module
209e8d8bef9SDimitry Andric     // This can happen when we compile with a sample profile collected from
210e8d8bef9SDimitry Andric     // one binary but used for another, which may have profiled targets that
211e8d8bef9SDimitry Andric     // aren't used in the new binary. We might have a declaration initially in
212e8d8bef9SDimitry Andric     // the case where the symbol is globally dead in the binary and removed by
213e8d8bef9SDimitry Andric     // ThinLTO.
2140b57cec5SDimitry Andric     Function *TargetFunction = Symtab->getFunction(Target);
215e8d8bef9SDimitry Andric     if (TargetFunction == nullptr || TargetFunction->isDeclaration()) {
2160b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " Not promote: Cannot find the target\n");
2170b57cec5SDimitry Andric       ORE.emit([&]() {
2185ffd83dbSDimitry Andric         return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToFindTarget", &CB)
2190b57cec5SDimitry Andric                << "Cannot promote indirect call: target with md5sum "
2200b57cec5SDimitry Andric                << ore::NV("target md5sum", Target) << " not found";
2210b57cec5SDimitry Andric       });
2220b57cec5SDimitry Andric       break;
2230b57cec5SDimitry Andric     }
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric     const char *Reason = nullptr;
2265ffd83dbSDimitry Andric     if (!isLegalToPromote(CB, TargetFunction, &Reason)) {
2270b57cec5SDimitry Andric       using namespace ore;
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric       ORE.emit([&]() {
2305ffd83dbSDimitry Andric         return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToPromote", &CB)
2310b57cec5SDimitry Andric                << "Cannot promote indirect call to "
2320b57cec5SDimitry Andric                << NV("TargetFunction", TargetFunction) << " with count of "
2330b57cec5SDimitry Andric                << NV("Count", Count) << ": " << Reason;
2340b57cec5SDimitry Andric       });
2350b57cec5SDimitry Andric       break;
2360b57cec5SDimitry Andric     }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric     Ret.push_back(PromotionCandidate(TargetFunction, Count));
2390b57cec5SDimitry Andric     TotalCount -= Count;
2400b57cec5SDimitry Andric   }
2410b57cec5SDimitry Andric   return Ret;
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric 
promoteIndirectCall(CallBase & CB,Function * DirectCallee,uint64_t Count,uint64_t TotalCount,bool AttachProfToDirectCall,OptimizationRemarkEmitter * ORE)2445ffd83dbSDimitry Andric CallBase &llvm::pgo::promoteIndirectCall(CallBase &CB, Function *DirectCallee,
2450b57cec5SDimitry Andric                                          uint64_t Count, uint64_t TotalCount,
2460b57cec5SDimitry Andric                                          bool AttachProfToDirectCall,
2470b57cec5SDimitry Andric                                          OptimizationRemarkEmitter *ORE) {
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   uint64_t ElseCount = TotalCount - Count;
2500b57cec5SDimitry Andric   uint64_t MaxCount = (Count >= ElseCount ? Count : ElseCount);
2510b57cec5SDimitry Andric   uint64_t Scale = calculateCountScale(MaxCount);
2525ffd83dbSDimitry Andric   MDBuilder MDB(CB.getContext());
2530b57cec5SDimitry Andric   MDNode *BranchWeights = MDB.createBranchWeights(
2540b57cec5SDimitry Andric       scaleBranchCount(Count, Scale), scaleBranchCount(ElseCount, Scale));
2550b57cec5SDimitry Andric 
2565ffd83dbSDimitry Andric   CallBase &NewInst =
2575ffd83dbSDimitry Andric       promoteCallWithIfThenElse(CB, DirectCallee, BranchWeights);
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   if (AttachProfToDirectCall) {
2605f757f3fSDimitry Andric     setBranchWeights(NewInst, {static_cast<uint32_t>(Count)});
2610b57cec5SDimitry Andric   }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   using namespace ore;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   if (ORE)
2660b57cec5SDimitry Andric     ORE->emit([&]() {
2675ffd83dbSDimitry Andric       return OptimizationRemark(DEBUG_TYPE, "Promoted", &CB)
2680b57cec5SDimitry Andric              << "Promote indirect call to " << NV("DirectCallee", DirectCallee)
2690b57cec5SDimitry Andric              << " with count " << NV("Count", Count) << " out of "
2700b57cec5SDimitry Andric              << NV("TotalCount", TotalCount);
2710b57cec5SDimitry Andric     });
2720b57cec5SDimitry Andric   return NewInst;
2730b57cec5SDimitry Andric }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric // Promote indirect-call to conditional direct-call for one callsite.
tryToPromote(CallBase & CB,const std::vector<PromotionCandidate> & Candidates,uint64_t & TotalCount)27606c3fb27SDimitry Andric uint32_t IndirectCallPromoter::tryToPromote(
2775ffd83dbSDimitry Andric     CallBase &CB, const std::vector<PromotionCandidate> &Candidates,
2780b57cec5SDimitry Andric     uint64_t &TotalCount) {
2790b57cec5SDimitry Andric   uint32_t NumPromoted = 0;
2800b57cec5SDimitry Andric 
281bdd1243dSDimitry Andric   for (const auto &C : Candidates) {
2820b57cec5SDimitry Andric     uint64_t Count = C.Count;
2835ffd83dbSDimitry Andric     pgo::promoteIndirectCall(CB, C.TargetFunction, Count, TotalCount, SamplePGO,
2845ffd83dbSDimitry Andric                              &ORE);
2850b57cec5SDimitry Andric     assert(TotalCount >= Count);
2860b57cec5SDimitry Andric     TotalCount -= Count;
2870b57cec5SDimitry Andric     NumOfPGOICallPromotion++;
2880b57cec5SDimitry Andric     NumPromoted++;
2890b57cec5SDimitry Andric   }
2900b57cec5SDimitry Andric   return NumPromoted;
2910b57cec5SDimitry Andric }
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric // Traverse all the indirect-call callsite and get the value profile
2940b57cec5SDimitry Andric // annotation to perform indirect-call promotion.
processFunction(ProfileSummaryInfo * PSI)29506c3fb27SDimitry Andric bool IndirectCallPromoter::processFunction(ProfileSummaryInfo *PSI) {
2960b57cec5SDimitry Andric   bool Changed = false;
2970b57cec5SDimitry Andric   ICallPromotionAnalysis ICallAnalysis;
2985ffd83dbSDimitry Andric   for (auto *CB : findIndirectCalls(F)) {
2990b57cec5SDimitry Andric     uint32_t NumVals, NumCandidates;
3000b57cec5SDimitry Andric     uint64_t TotalCount;
3010b57cec5SDimitry Andric     auto ICallProfDataRef = ICallAnalysis.getPromotionCandidatesForInstruction(
3025ffd83dbSDimitry Andric         CB, NumVals, TotalCount, NumCandidates);
3030b57cec5SDimitry Andric     if (!NumCandidates ||
3040b57cec5SDimitry Andric         (PSI && PSI->hasProfileSummary() && !PSI->isHotCount(TotalCount)))
3050b57cec5SDimitry Andric       continue;
3060b57cec5SDimitry Andric     auto PromotionCandidates = getPromotionCandidatesForCallSite(
3075ffd83dbSDimitry Andric         *CB, ICallProfDataRef, TotalCount, NumCandidates);
3085ffd83dbSDimitry Andric     uint32_t NumPromoted = tryToPromote(*CB, PromotionCandidates, TotalCount);
3090b57cec5SDimitry Andric     if (NumPromoted == 0)
3100b57cec5SDimitry Andric       continue;
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric     Changed = true;
3130b57cec5SDimitry Andric     // Adjust the MD.prof metadata. First delete the old one.
3145ffd83dbSDimitry Andric     CB->setMetadata(LLVMContext::MD_prof, nullptr);
3150b57cec5SDimitry Andric     // If all promoted, we don't need the MD.prof metadata.
3160b57cec5SDimitry Andric     if (TotalCount == 0 || NumPromoted == NumVals)
3170b57cec5SDimitry Andric       continue;
3180b57cec5SDimitry Andric     // Otherwise we need update with the un-promoted records back.
31906c3fb27SDimitry Andric     annotateValueSite(*F.getParent(), *CB, ICallProfDataRef.slice(NumPromoted),
32006c3fb27SDimitry Andric                       TotalCount, IPVK_IndirectCallTarget, NumCandidates);
3210b57cec5SDimitry Andric   }
3220b57cec5SDimitry Andric   return Changed;
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric // A wrapper function that does the actual work.
promoteIndirectCalls(Module & M,ProfileSummaryInfo * PSI,bool InLTO,bool SamplePGO,ModuleAnalysisManager & MAM)32606c3fb27SDimitry Andric static bool promoteIndirectCalls(Module &M, ProfileSummaryInfo *PSI, bool InLTO,
32706c3fb27SDimitry Andric                                  bool SamplePGO, ModuleAnalysisManager &MAM) {
3280b57cec5SDimitry Andric   if (DisableICP)
3290b57cec5SDimitry Andric     return false;
3300b57cec5SDimitry Andric   InstrProfSymtab Symtab;
3310b57cec5SDimitry Andric   if (Error E = Symtab.create(M, InLTO)) {
3320b57cec5SDimitry Andric     std::string SymtabFailure = toString(std::move(E));
333fe6060f1SDimitry Andric     M.getContext().emitError("Failed to create symtab: " + SymtabFailure);
3340b57cec5SDimitry Andric     return false;
3350b57cec5SDimitry Andric   }
3360b57cec5SDimitry Andric   bool Changed = false;
3370b57cec5SDimitry Andric   for (auto &F : M) {
3380b57cec5SDimitry Andric     if (F.isDeclaration() || F.hasOptNone())
3390b57cec5SDimitry Andric       continue;
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric     auto &FAM =
34206c3fb27SDimitry Andric         MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
34306c3fb27SDimitry Andric     auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
3440b57cec5SDimitry Andric 
34506c3fb27SDimitry Andric     IndirectCallPromoter CallPromoter(F, &Symtab, SamplePGO, ORE);
34606c3fb27SDimitry Andric     bool FuncChanged = CallPromoter.processFunction(PSI);
3470b57cec5SDimitry Andric     if (ICPDUMPAFTER && FuncChanged) {
3480b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs()));
3490b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
3500b57cec5SDimitry Andric     }
3510b57cec5SDimitry Andric     Changed |= FuncChanged;
3520b57cec5SDimitry Andric     if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
3530b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " Stop: Cutoff reached.\n");
3540b57cec5SDimitry Andric       break;
3550b57cec5SDimitry Andric     }
3560b57cec5SDimitry Andric   }
3570b57cec5SDimitry Andric   return Changed;
3580b57cec5SDimitry Andric }
3590b57cec5SDimitry Andric 
run(Module & M,ModuleAnalysisManager & MAM)3600b57cec5SDimitry Andric PreservedAnalyses PGOIndirectCallPromotion::run(Module &M,
36106c3fb27SDimitry Andric                                                 ModuleAnalysisManager &MAM) {
36206c3fb27SDimitry Andric   ProfileSummaryInfo *PSI = &MAM.getResult<ProfileSummaryAnalysis>(M);
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   if (!promoteIndirectCalls(M, PSI, InLTO | ICPLTOMode,
36506c3fb27SDimitry Andric                             SamplePGO | ICPSamplePGOMode, MAM))
3660b57cec5SDimitry Andric     return PreservedAnalyses::all();
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric   return PreservedAnalyses::none();
3690b57cec5SDimitry Andric }
370