blob: 49b8a67a6c14cd9eb744ba52cc980c229ad2783d [file] [log] [blame]
Eugene Zelenkofce43572017-10-21 00:57:46 +00001//===- IndirectCallPromotion.cpp - Optimizations based on value profiling -===//
Rong Xu6e34c492016-04-27 23:20:27 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the transformation that promotes indirect calls to
11// conditional direct calls when the indirect-call value profile metadata is
12// available.
13//
14//===----------------------------------------------------------------------===//
15
Eugene Zelenkocdc71612016-08-11 17:20:18 +000016#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000017#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
Rong Xu6e34c492016-04-27 23:20:27 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/StringRef.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000021#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
22#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Adam Nemet0965da22017-10-09 23:19:02 +000023#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Dehao Chen34cfcb22017-08-08 20:57:33 +000024#include "llvm/Analysis/ProfileSummaryInfo.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000025#include "llvm/IR/Attributes.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000026#include "llvm/IR/BasicBlock.h"
Rong Xu6e34c492016-04-27 23:20:27 +000027#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/IR/DerivedTypes.h"
Rong Xu6e34c492016-04-27 23:20:27 +000029#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000030#include "llvm/IR/Function.h"
Rong Xu6e34c492016-04-27 23:20:27 +000031#include "llvm/IR/IRBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000032#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
Rong Xu6e34c492016-04-27 23:20:27 +000034#include "llvm/IR/Instructions.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000035#include "llvm/IR/LLVMContext.h"
Rong Xu6e34c492016-04-27 23:20:27 +000036#include "llvm/IR/MDBuilder.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000037#include "llvm/IR/PassManager.h"
38#include "llvm/IR/Type.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000039#include "llvm/IR/Value.h"
Rong Xu6e34c492016-04-27 23:20:27 +000040#include "llvm/Pass.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000041#include "llvm/ProfileData/InstrProf.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/CommandLine.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000044#include "llvm/Support/Error.h"
Rong Xu6e34c492016-04-27 23:20:27 +000045#include "llvm/Support/Debug.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000046#include "llvm/Support/raw_ostream.h"
Rong Xu6e34c492016-04-27 23:20:27 +000047#include "llvm/Transforms/Instrumentation.h"
Xinliang David Lif3c7a352016-05-16 16:31:07 +000048#include "llvm/Transforms/PGOInstrumentation.h"
Rong Xu6e34c492016-04-27 23:20:27 +000049#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Matthew Simpsone363d2c2017-12-06 21:22:54 +000050#include "llvm/Transforms/Utils/CallPromotionUtils.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000051#include <cassert>
52#include <cstdint>
Eugene Zelenkofce43572017-10-21 00:57:46 +000053#include <memory>
54#include <string>
55#include <utility>
Rong Xu6e34c492016-04-27 23:20:27 +000056#include <vector>
57
58using namespace llvm;
59
Xinliang David Li0b293302016-06-02 01:52:05 +000060#define DEBUG_TYPE "pgo-icall-prom"
Rong Xu6e34c492016-04-27 23:20:27 +000061
62STATISTIC(NumOfPGOICallPromotion, "Number of indirect call promotions.");
63STATISTIC(NumOfPGOICallsites, "Number of indirect call candidate sites.");
64
65// Command line option to disable indirect-call promotion with the default as
66// false. This is for debug purpose.
67static cl::opt<bool> DisableICP("disable-icp", cl::init(false), cl::Hidden,
68 cl::desc("Disable indirect call promotion"));
69
Rong Xu6e34c492016-04-27 23:20:27 +000070// Set the cutoff value for the promotion. If the value is other than 0, we
71// stop the transformation once the total number of promotions equals the cutoff
72// value.
73// For debug use only.
74static cl::opt<unsigned>
75 ICPCutOff("icp-cutoff", cl::init(0), cl::Hidden, cl::ZeroOrMore,
Craig Toppera49e7682017-05-05 22:31:11 +000076 cl::desc("Max number of promotions for this compilation"));
Rong Xu6e34c492016-04-27 23:20:27 +000077
78// If ICPCSSkip is non zero, the first ICPCSSkip callsites will be skipped.
79// For debug use only.
80static cl::opt<unsigned>
81 ICPCSSkip("icp-csskip", cl::init(0), cl::Hidden, cl::ZeroOrMore,
Craig Toppera49e7682017-05-05 22:31:11 +000082 cl::desc("Skip Callsite up to this number for this compilation"));
Rong Xu6e34c492016-04-27 23:20:27 +000083
84// Set if the pass is called in LTO optimization. The difference for LTO mode
85// is the pass won't prefix the source module name to the internal linkage
86// symbols.
87static cl::opt<bool> ICPLTOMode("icp-lto", cl::init(false), cl::Hidden,
88 cl::desc("Run indirect-call promotion in LTO "
89 "mode"));
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000090
Dehao Chencc75d242017-02-23 22:15:18 +000091// Set if the pass is called in SamplePGO mode. The difference for SamplePGO
92// mode is it will add prof metadatato the created direct call.
93static cl::opt<bool>
94 ICPSamplePGOMode("icp-samplepgo", cl::init(false), cl::Hidden,
95 cl::desc("Run indirect-call promotion in SamplePGO mode"));
96
Rong Xu6e34c492016-04-27 23:20:27 +000097// If the option is set to true, only call instructions will be considered for
98// transformation -- invoke instructions will be ignored.
99static cl::opt<bool>
100 ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden,
101 cl::desc("Run indirect-call promotion for call instructions "
102 "only"));
103
104// If the option is set to true, only invoke instructions will be considered for
105// transformation -- call instructions will be ignored.
106static cl::opt<bool> ICPInvokeOnly("icp-invoke-only", cl::init(false),
107 cl::Hidden,
108 cl::desc("Run indirect-call promotion for "
109 "invoke instruction only"));
110
111// Dump the function level IR if the transformation happened in this
112// function. For debug use only.
113static cl::opt<bool>
114 ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden,
115 cl::desc("Dump IR after transformation happens"));
116
117namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000118
Xinliang David Li72616182016-05-15 01:04:24 +0000119class PGOIndirectCallPromotionLegacyPass : public ModulePass {
Rong Xu6e34c492016-04-27 23:20:27 +0000120public:
121 static char ID;
122
Dehao Chencc75d242017-02-23 22:15:18 +0000123 PGOIndirectCallPromotionLegacyPass(bool InLTO = false, bool SamplePGO = false)
124 : ModulePass(ID), InLTO(InLTO), SamplePGO(SamplePGO) {
Xinliang David Li72616182016-05-15 01:04:24 +0000125 initializePGOIndirectCallPromotionLegacyPassPass(
126 *PassRegistry::getPassRegistry());
Rong Xu6e34c492016-04-27 23:20:27 +0000127 }
128
Dehao Chen34cfcb22017-08-08 20:57:33 +0000129 void getAnalysisUsage(AnalysisUsage &AU) const override {
130 AU.addRequired<ProfileSummaryInfoWrapperPass>();
131 }
132
Mehdi Amini117296c2016-10-01 02:56:57 +0000133 StringRef getPassName() const override { return "PGOIndirectCallPromotion"; }
Rong Xu6e34c492016-04-27 23:20:27 +0000134
135private:
136 bool runOnModule(Module &M) override;
137
138 // If this pass is called in LTO. We need to special handling the PGOFuncName
139 // for the static variables due to LTO's internalization.
140 bool InLTO;
Dehao Chencc75d242017-02-23 22:15:18 +0000141
142 // If this pass is called in SamplePGO. We need to add the prof metadata to
143 // the promoted direct call.
144 bool SamplePGO;
Rong Xu6e34c492016-04-27 23:20:27 +0000145};
Eugene Zelenkofce43572017-10-21 00:57:46 +0000146
Rong Xu6e34c492016-04-27 23:20:27 +0000147} // end anonymous namespace
148
Xinliang David Li72616182016-05-15 01:04:24 +0000149char PGOIndirectCallPromotionLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000150
Dehao Chen45847d32017-08-14 23:25:21 +0000151INITIALIZE_PASS_BEGIN(PGOIndirectCallPromotionLegacyPass, "pgo-icall-prom",
152 "Use PGO instrumentation profile to promote indirect "
153 "calls to direct calls.",
154 false, false)
155INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
156INITIALIZE_PASS_END(PGOIndirectCallPromotionLegacyPass, "pgo-icall-prom",
157 "Use PGO instrumentation profile to promote indirect "
158 "calls to direct calls.",
159 false, false)
Rong Xu6e34c492016-04-27 23:20:27 +0000160
Dehao Chencc75d242017-02-23 22:15:18 +0000161ModulePass *llvm::createPGOIndirectCallPromotionLegacyPass(bool InLTO,
162 bool SamplePGO) {
163 return new PGOIndirectCallPromotionLegacyPass(InLTO, SamplePGO);
Rong Xu6e34c492016-04-27 23:20:27 +0000164}
165
Benjamin Kramera65b6102016-05-15 15:18:11 +0000166namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000167
Rong Xu6e34c492016-04-27 23:20:27 +0000168// The class for main data structure to promote indirect calls to conditional
169// direct calls.
170class ICallPromotionFunc {
171private:
172 Function &F;
173 Module *M;
174
175 // Symtab that maps indirect call profile values to function names and
176 // defines.
177 InstrProfSymtab *Symtab;
178
Dehao Chencc75d242017-02-23 22:15:18 +0000179 bool SamplePGO;
180
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000181 OptimizationRemarkEmitter &ORE;
Rong Xu6e34c492016-04-27 23:20:27 +0000182
183 // A struct that records the direct target and it's call count.
184 struct PromotionCandidate {
185 Function *TargetFunction;
186 uint64_t Count;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000187
Rong Xu6e34c492016-04-27 23:20:27 +0000188 PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {}
189 };
190
191 // Check if the indirect-call call site should be promoted. Return the number
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000192 // of promotions. Inst is the candidate indirect call, ValueDataRef
193 // contains the array of value profile data for profiled targets,
194 // TotalCount is the total profiled count of call executions, and
195 // NumCandidates is the number of candidate entries in ValueDataRef.
Rong Xu6e34c492016-04-27 23:20:27 +0000196 std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(
197 Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000198 uint64_t TotalCount, uint32_t NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000199
Rong Xu6e34c492016-04-27 23:20:27 +0000200 // Promote a list of targets for one indirect-call callsite. Return
201 // the number of promotions.
202 uint32_t tryToPromote(Instruction *Inst,
203 const std::vector<PromotionCandidate> &Candidates,
204 uint64_t &TotalCount);
205
Rong Xu6e34c492016-04-27 23:20:27 +0000206public:
Dehao Chencc75d242017-02-23 22:15:18 +0000207 ICallPromotionFunc(Function &Func, Module *Modu, InstrProfSymtab *Symtab,
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000208 bool SamplePGO, OptimizationRemarkEmitter &ORE)
209 : F(Func), M(Modu), Symtab(Symtab), SamplePGO(SamplePGO), ORE(ORE) {}
Eugene Zelenkofce43572017-10-21 00:57:46 +0000210 ICallPromotionFunc(const ICallPromotionFunc &) = delete;
211 ICallPromotionFunc &operator=(const ICallPromotionFunc &) = delete;
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000212
Dehao Chen34cfcb22017-08-08 20:57:33 +0000213 bool processFunction(ProfileSummaryInfo *PSI);
Rong Xu6e34c492016-04-27 23:20:27 +0000214};
Eugene Zelenkofce43572017-10-21 00:57:46 +0000215
Benjamin Kramera65b6102016-05-15 15:18:11 +0000216} // end anonymous namespace
Rong Xu6e34c492016-04-27 23:20:27 +0000217
Rong Xu6e34c492016-04-27 23:20:27 +0000218// Indirect-call promotion heuristic. The direct targets are sorted based on
219// the count. Stop at the first target that is not promoted.
220std::vector<ICallPromotionFunc::PromotionCandidate>
221ICallPromotionFunc::getPromotionCandidatesForCallSite(
222 Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000223 uint64_t TotalCount, uint32_t NumCandidates) {
Rong Xu6e34c492016-04-27 23:20:27 +0000224 std::vector<PromotionCandidate> Ret;
225
226 DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << *Inst
Teresa Johnson8950ad12016-07-12 21:29:05 +0000227 << " Num_targets: " << ValueDataRef.size()
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000228 << " Num_candidates: " << NumCandidates << "\n");
Rong Xu6e34c492016-04-27 23:20:27 +0000229 NumOfPGOICallsites++;
230 if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) {
231 DEBUG(dbgs() << " Skip: User options.\n");
232 return Ret;
233 }
234
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000235 for (uint32_t I = 0; I < NumCandidates; I++) {
Rong Xu6e34c492016-04-27 23:20:27 +0000236 uint64_t Count = ValueDataRef[I].Count;
237 assert(Count <= TotalCount);
238 uint64_t Target = ValueDataRef[I].Value;
239 DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
240 << " Target_func: " << Target << "\n");
241
Teresa Johnsonce7de9b2016-07-17 14:46:58 +0000242 if (ICPInvokeOnly && dyn_cast<CallInst>(Inst)) {
243 DEBUG(dbgs() << " Not promote: User options.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000244 ORE.emit([&]() {
245 return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", Inst)
246 << " Not promote: User options";
247 });
Teresa Johnsonce7de9b2016-07-17 14:46:58 +0000248 break;
249 }
250 if (ICPCallOnly && dyn_cast<InvokeInst>(Inst)) {
251 DEBUG(dbgs() << " Not promote: User option.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000252 ORE.emit([&]() {
253 return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", Inst)
254 << " Not promote: User options";
255 });
Teresa Johnsonce7de9b2016-07-17 14:46:58 +0000256 break;
257 }
Rong Xu6e34c492016-04-27 23:20:27 +0000258 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
259 DEBUG(dbgs() << " Not promote: Cutoff reached.\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000260 ORE.emit([&]() {
261 return OptimizationRemarkMissed(DEBUG_TYPE, "CutOffReached", Inst)
262 << " Not promote: Cutoff reached";
263 });
Rong Xu6e34c492016-04-27 23:20:27 +0000264 break;
265 }
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000266
267 Function *TargetFunction = Symtab->getFunction(Target);
268 if (TargetFunction == nullptr) {
269 DEBUG(dbgs() << " Not promote: Cannot find the target\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000270 ORE.emit([&]() {
271 return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToFindTarget", Inst)
272 << "Cannot promote indirect call: target not found";
273 });
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000274 break;
275 }
276
Dehao Chen6775f5d2017-01-30 22:46:37 +0000277 const char *Reason = nullptr;
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000278 if (!isLegalToPromote(CallSite(Inst), TargetFunction, &Reason)) {
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000279 using namespace ore;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000280
Vivek Pandya95906582017-10-11 17:12:59 +0000281 ORE.emit([&]() {
282 return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToPromote", Inst)
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000283 << "Cannot promote indirect call to "
284 << NV("TargetFunction", TargetFunction) << " with count of "
Vivek Pandya95906582017-10-11 17:12:59 +0000285 << NV("Count", Count) << ": " << Reason;
286 });
Rong Xu6e34c492016-04-27 23:20:27 +0000287 break;
288 }
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000289
Rong Xu6e34c492016-04-27 23:20:27 +0000290 Ret.push_back(PromotionCandidate(TargetFunction, Count));
291 TotalCount -= Count;
292 }
293 return Ret;
294}
295
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000296Instruction *llvm::pgo::promoteIndirectCall(Instruction *Inst,
297 Function *DirectCallee,
298 uint64_t Count, uint64_t TotalCount,
299 bool AttachProfToDirectCall,
300 OptimizationRemarkEmitter *ORE) {
Rong Xu6e34c492016-04-27 23:20:27 +0000301
302 uint64_t ElseCount = TotalCount - Count;
303 uint64_t MaxCount = (Count >= ElseCount ? Count : ElseCount);
304 uint64_t Scale = calculateCountScale(MaxCount);
305 MDBuilder MDB(Inst->getContext());
306 MDNode *BranchWeights = MDB.createBranchWeights(
307 scaleBranchCount(Count, Scale), scaleBranchCount(ElseCount, Scale));
Rong Xu6e34c492016-04-27 23:20:27 +0000308
Rong Xu6e34c492016-04-27 23:20:27 +0000309 Instruction *NewInst =
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000310 promoteCallWithIfThenElse(CallSite(Inst), DirectCallee, BranchWeights);
Rong Xu6e34c492016-04-27 23:20:27 +0000311
Dehao Chencc75d242017-02-23 22:15:18 +0000312 if (AttachProfToDirectCall) {
313 SmallVector<uint32_t, 1> Weights;
314 Weights.push_back(Count);
315 MDBuilder MDB(NewInst->getContext());
Dehao Chen9bd60422017-10-06 17:04:55 +0000316 NewInst->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Dehao Chencc75d242017-02-23 22:15:18 +0000317 }
318
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000319 using namespace ore;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000320
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000321 if (ORE)
Vivek Pandya95906582017-10-11 17:12:59 +0000322 ORE->emit([&]() {
323 return OptimizationRemark(DEBUG_TYPE, "Promoted", Inst)
324 << "Promote indirect call to " << NV("DirectCallee", DirectCallee)
325 << " with count " << NV("Count", Count) << " out of "
326 << NV("TotalCount", TotalCount);
327 });
Dehao Chen14bf0292017-01-23 23:18:24 +0000328 return NewInst;
Rong Xu6e34c492016-04-27 23:20:27 +0000329}
330
331// Promote indirect-call to conditional direct-call for one callsite.
332uint32_t ICallPromotionFunc::tryToPromote(
333 Instruction *Inst, const std::vector<PromotionCandidate> &Candidates,
334 uint64_t &TotalCount) {
335 uint32_t NumPromoted = 0;
336
337 for (auto &C : Candidates) {
338 uint64_t Count = C.Count;
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000339 pgo::promoteIndirectCall(Inst, C.TargetFunction, Count, TotalCount,
340 SamplePGO, &ORE);
Rong Xu6e34c492016-04-27 23:20:27 +0000341 assert(TotalCount >= Count);
342 TotalCount -= Count;
343 NumOfPGOICallPromotion++;
344 NumPromoted++;
345 }
346 return NumPromoted;
347}
348
349// Traverse all the indirect-call callsite and get the value profile
350// annotation to perform indirect-call promotion.
Dehao Chen34cfcb22017-08-08 20:57:33 +0000351bool ICallPromotionFunc::processFunction(ProfileSummaryInfo *PSI) {
Rong Xu6e34c492016-04-27 23:20:27 +0000352 bool Changed = false;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000353 ICallPromotionAnalysis ICallAnalysis;
Rong Xu6e34c492016-04-27 23:20:27 +0000354 for (auto &I : findIndirectCallSites(F)) {
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000355 uint32_t NumVals, NumCandidates;
Rong Xu6e34c492016-04-27 23:20:27 +0000356 uint64_t TotalCount;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000357 auto ICallProfDataRef = ICallAnalysis.getPromotionCandidatesForInstruction(
358 I, NumVals, TotalCount, NumCandidates);
Dehao Chen34cfcb22017-08-08 20:57:33 +0000359 if (!NumCandidates ||
360 (PSI && PSI->hasProfileSummary() && !PSI->isHotCount(TotalCount)))
Rong Xu6e34c492016-04-27 23:20:27 +0000361 continue;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000362 auto PromotionCandidates = getPromotionCandidatesForCallSite(
363 I, ICallProfDataRef, TotalCount, NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000364 uint32_t NumPromoted = tryToPromote(I, PromotionCandidates, TotalCount);
365 if (NumPromoted == 0)
366 continue;
367
368 Changed = true;
369 // Adjust the MD.prof metadata. First delete the old one.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000370 I->setMetadata(LLVMContext::MD_prof, nullptr);
Rong Xu6e34c492016-04-27 23:20:27 +0000371 // If all promoted, we don't need the MD.prof metadata.
372 if (TotalCount == 0 || NumPromoted == NumVals)
373 continue;
374 // Otherwise we need update with the un-promoted records back.
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000375 annotateValueSite(*M, *I, ICallProfDataRef.slice(NumPromoted), TotalCount,
376 IPVK_IndirectCallTarget, NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000377 }
378 return Changed;
379}
380
381// A wrapper function that does the actual work.
Dehao Chen34cfcb22017-08-08 20:57:33 +0000382static bool promoteIndirectCalls(Module &M, ProfileSummaryInfo *PSI,
383 bool InLTO, bool SamplePGO,
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000384 ModuleAnalysisManager *AM = nullptr) {
Rong Xu6e34c492016-04-27 23:20:27 +0000385 if (DisableICP)
386 return false;
387 InstrProfSymtab Symtab;
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000388 if (Error E = Symtab.create(M, InLTO)) {
389 std::string SymtabFailure = toString(std::move(E));
390 DEBUG(dbgs() << "Failed to create symtab: " << SymtabFailure << "\n");
391 (void)SymtabFailure;
392 return false;
393 }
Rong Xu6e34c492016-04-27 23:20:27 +0000394 bool Changed = false;
395 for (auto &F : M) {
396 if (F.isDeclaration())
397 continue;
398 if (F.hasFnAttribute(Attribute::OptimizeNone))
399 continue;
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000400
401 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
402 OptimizationRemarkEmitter *ORE;
403 if (AM) {
404 auto &FAM =
405 AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
406 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
407 } else {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000408 OwnedORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
Adam Nemet0d8b5d62017-07-27 16:54:15 +0000409 ORE = OwnedORE.get();
410 }
411
412 ICallPromotionFunc ICallPromotion(F, &M, &Symtab, SamplePGO, *ORE);
Dehao Chen34cfcb22017-08-08 20:57:33 +0000413 bool FuncChanged = ICallPromotion.processFunction(PSI);
Rong Xu6e34c492016-04-27 23:20:27 +0000414 if (ICPDUMPAFTER && FuncChanged) {
415 DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs()));
416 DEBUG(dbgs() << "\n");
417 }
418 Changed |= FuncChanged;
419 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
420 DEBUG(dbgs() << " Stop: Cutoff reached.\n");
421 break;
422 }
423 }
424 return Changed;
425}
426
Xinliang David Li72616182016-05-15 01:04:24 +0000427bool PGOIndirectCallPromotionLegacyPass::runOnModule(Module &M) {
Dehao Chen34cfcb22017-08-08 20:57:33 +0000428 ProfileSummaryInfo *PSI =
429 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
430
Rong Xu6e34c492016-04-27 23:20:27 +0000431 // Command-line option has the priority for InLTO.
Dehao Chen34cfcb22017-08-08 20:57:33 +0000432 return promoteIndirectCalls(M, PSI, InLTO | ICPLTOMode,
Dehao Chencc75d242017-02-23 22:15:18 +0000433 SamplePGO | ICPSamplePGOMode);
Rong Xu6e34c492016-04-27 23:20:27 +0000434}
Xinliang David Lif3c7a352016-05-16 16:31:07 +0000435
Dehao Chencc75d242017-02-23 22:15:18 +0000436PreservedAnalyses PGOIndirectCallPromotion::run(Module &M,
437 ModuleAnalysisManager &AM) {
Dehao Chen34cfcb22017-08-08 20:57:33 +0000438 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
439
440 if (!promoteIndirectCalls(M, PSI, InLTO | ICPLTOMode,
441 SamplePGO | ICPSamplePGOMode, &AM))
Xinliang David Lif3c7a352016-05-16 16:31:07 +0000442 return PreservedAnalyses::all();
443
444 return PreservedAnalyses::none();
445}