blob: c9bc7db38cad63573f5d8ae98c758bff63b1bb76 [file] [log] [blame]
Rong Xu6e34c492016-04-27 23:20:27 +00001//===-- IndirectCallPromotion.cpp - Promote indirect calls to direct calls ===//
2//
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
Rong Xu6e34c492016-04-27 23:20:27 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/Statistic.h"
18#include "llvm/ADT/Triple.h"
19#include "llvm/Analysis/CFG.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000020#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
21#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Rong Xu6e34c492016-04-27 23:20:27 +000022#include "llvm/IR/CallSite.h"
23#include "llvm/IR/DiagnosticInfo.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/InstIterator.h"
26#include "llvm/IR/InstVisitor.h"
27#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
29#include "llvm/IR/MDBuilder.h"
30#include "llvm/IR/Module.h"
31#include "llvm/Pass.h"
32#include "llvm/ProfileData/InstrProfReader.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Transforms/Instrumentation.h"
Xinliang David Lif3c7a352016-05-16 16:31:07 +000035#include "llvm/Transforms/PGOInstrumentation.h"
Rong Xu6e34c492016-04-27 23:20:27 +000036#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include <string>
38#include <utility>
39#include <vector>
40
41using namespace llvm;
42
Xinliang David Li0b293302016-06-02 01:52:05 +000043#define DEBUG_TYPE "pgo-icall-prom"
Rong Xu6e34c492016-04-27 23:20:27 +000044
45STATISTIC(NumOfPGOICallPromotion, "Number of indirect call promotions.");
46STATISTIC(NumOfPGOICallsites, "Number of indirect call candidate sites.");
47
48// Command line option to disable indirect-call promotion with the default as
49// false. This is for debug purpose.
50static cl::opt<bool> DisableICP("disable-icp", cl::init(false), cl::Hidden,
51 cl::desc("Disable indirect call promotion"));
52
Rong Xu6e34c492016-04-27 23:20:27 +000053// Set the cutoff value for the promotion. If the value is other than 0, we
54// stop the transformation once the total number of promotions equals the cutoff
55// value.
56// For debug use only.
57static cl::opt<unsigned>
58 ICPCutOff("icp-cutoff", cl::init(0), cl::Hidden, cl::ZeroOrMore,
59 cl::desc("Max number of promotions for this compilaiton"));
60
61// If ICPCSSkip is non zero, the first ICPCSSkip callsites will be skipped.
62// For debug use only.
63static cl::opt<unsigned>
64 ICPCSSkip("icp-csskip", cl::init(0), cl::Hidden, cl::ZeroOrMore,
65 cl::desc("Skip Callsite up to this number for this compilaiton"));
66
67// Set if the pass is called in LTO optimization. The difference for LTO mode
68// is the pass won't prefix the source module name to the internal linkage
69// symbols.
70static cl::opt<bool> ICPLTOMode("icp-lto", cl::init(false), cl::Hidden,
71 cl::desc("Run indirect-call promotion in LTO "
72 "mode"));
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000073
Rong Xu6e34c492016-04-27 23:20:27 +000074// If the option is set to true, only call instructions will be considered for
75// transformation -- invoke instructions will be ignored.
76static cl::opt<bool>
77 ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden,
78 cl::desc("Run indirect-call promotion for call instructions "
79 "only"));
80
81// If the option is set to true, only invoke instructions will be considered for
82// transformation -- call instructions will be ignored.
83static cl::opt<bool> ICPInvokeOnly("icp-invoke-only", cl::init(false),
84 cl::Hidden,
85 cl::desc("Run indirect-call promotion for "
86 "invoke instruction only"));
87
88// Dump the function level IR if the transformation happened in this
89// function. For debug use only.
90static cl::opt<bool>
91 ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden,
92 cl::desc("Dump IR after transformation happens"));
93
94namespace {
Xinliang David Li72616182016-05-15 01:04:24 +000095class PGOIndirectCallPromotionLegacyPass : public ModulePass {
Rong Xu6e34c492016-04-27 23:20:27 +000096public:
97 static char ID;
98
Xinliang David Li72616182016-05-15 01:04:24 +000099 PGOIndirectCallPromotionLegacyPass(bool InLTO = false)
100 : ModulePass(ID), InLTO(InLTO) {
101 initializePGOIndirectCallPromotionLegacyPassPass(
102 *PassRegistry::getPassRegistry());
Rong Xu6e34c492016-04-27 23:20:27 +0000103 }
104
105 const char *getPassName() const override {
106 return "PGOIndirectCallPromotion";
107 }
108
109private:
110 bool runOnModule(Module &M) override;
111
112 // If this pass is called in LTO. We need to special handling the PGOFuncName
113 // for the static variables due to LTO's internalization.
114 bool InLTO;
115};
116} // end anonymous namespace
117
Xinliang David Li72616182016-05-15 01:04:24 +0000118char PGOIndirectCallPromotionLegacyPass::ID = 0;
119INITIALIZE_PASS(PGOIndirectCallPromotionLegacyPass, "pgo-icall-prom",
Rong Xu6e34c492016-04-27 23:20:27 +0000120 "Use PGO instrumentation profile to promote indirect calls to "
121 "direct calls.",
122 false, false)
123
Xinliang David Li72616182016-05-15 01:04:24 +0000124ModulePass *llvm::createPGOIndirectCallPromotionLegacyPass(bool InLTO) {
125 return new PGOIndirectCallPromotionLegacyPass(InLTO);
Rong Xu6e34c492016-04-27 23:20:27 +0000126}
127
Benjamin Kramera65b6102016-05-15 15:18:11 +0000128namespace {
Rong Xu6e34c492016-04-27 23:20:27 +0000129// The class for main data structure to promote indirect calls to conditional
130// direct calls.
131class ICallPromotionFunc {
132private:
133 Function &F;
134 Module *M;
135
136 // Symtab that maps indirect call profile values to function names and
137 // defines.
138 InstrProfSymtab *Symtab;
139
Rong Xu6e34c492016-04-27 23:20:27 +0000140 enum TargetStatus {
141 OK, // Should be able to promote.
142 NotAvailableInModule, // Cannot find the target in current module.
143 ReturnTypeMismatch, // Return type mismatch b/w target and indirect-call.
144 NumArgsMismatch, // Number of arguments does not match.
145 ArgTypeMismatch // Type mismatch in the arguments (cannot bitcast).
146 };
147
148 // Test if we can legally promote this direct-call of Target.
149 TargetStatus isPromotionLegal(Instruction *Inst, uint64_t Target,
150 Function *&F);
151
152 // A struct that records the direct target and it's call count.
153 struct PromotionCandidate {
154 Function *TargetFunction;
155 uint64_t Count;
156 PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {}
157 };
158
159 // Check if the indirect-call call site should be promoted. Return the number
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000160 // of promotions. Inst is the candidate indirect call, ValueDataRef
161 // contains the array of value profile data for profiled targets,
162 // TotalCount is the total profiled count of call executions, and
163 // NumCandidates is the number of candidate entries in ValueDataRef.
Rong Xu6e34c492016-04-27 23:20:27 +0000164 std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(
165 Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000166 uint64_t TotalCount, uint32_t NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000167
168 // Main function that transforms Inst (either a indirect-call instruction, or
169 // an invoke instruction , to a conditional call to F. This is like:
170 // if (Inst.CalledValue == F)
171 // F(...);
172 // else
173 // Inst(...);
174 // end
175 // TotalCount is the profile count value that the instruction executes.
176 // Count is the profile count value that F is the target function.
177 // These two values are being used to update the branch weight.
178 void promote(Instruction *Inst, Function *F, uint64_t Count,
179 uint64_t TotalCount);
180
181 // Promote a list of targets for one indirect-call callsite. Return
182 // the number of promotions.
183 uint32_t tryToPromote(Instruction *Inst,
184 const std::vector<PromotionCandidate> &Candidates,
185 uint64_t &TotalCount);
186
187 static const char *StatusToString(const TargetStatus S) {
188 switch (S) {
189 case OK:
190 return "OK to promote";
191 case NotAvailableInModule:
192 return "Cannot find the target";
193 case ReturnTypeMismatch:
194 return "Return type mismatch";
195 case NumArgsMismatch:
196 return "The number of arguments mismatch";
197 case ArgTypeMismatch:
198 return "Argument Type mismatch";
199 }
200 llvm_unreachable("Should not reach here");
201 }
202
203 // Noncopyable
204 ICallPromotionFunc(const ICallPromotionFunc &other) = delete;
205 ICallPromotionFunc &operator=(const ICallPromotionFunc &other) = delete;
206
207public:
208 ICallPromotionFunc(Function &Func, Module *Modu, InstrProfSymtab *Symtab)
209 : F(Func), M(Modu), Symtab(Symtab) {
Rong Xu6e34c492016-04-27 23:20:27 +0000210 }
211 bool processFunction();
212};
Benjamin Kramera65b6102016-05-15 15:18:11 +0000213} // end anonymous namespace
Rong Xu6e34c492016-04-27 23:20:27 +0000214
Rong Xu6e34c492016-04-27 23:20:27 +0000215ICallPromotionFunc::TargetStatus
216ICallPromotionFunc::isPromotionLegal(Instruction *Inst, uint64_t Target,
217 Function *&TargetFunction) {
218 Function *DirectCallee = Symtab->getFunction(Target);
219 if (DirectCallee == nullptr)
220 return NotAvailableInModule;
221 // Check the return type.
222 Type *CallRetType = Inst->getType();
223 if (!CallRetType->isVoidTy()) {
224 Type *FuncRetType = DirectCallee->getReturnType();
225 if (FuncRetType != CallRetType &&
226 !CastInst::isBitCastable(FuncRetType, CallRetType))
227 return ReturnTypeMismatch;
228 }
229
230 // Check if the arguments are compatible with the parameters
231 FunctionType *DirectCalleeType = DirectCallee->getFunctionType();
232 unsigned ParamNum = DirectCalleeType->getFunctionNumParams();
233 CallSite CS(Inst);
234 unsigned ArgNum = CS.arg_size();
235
236 if (ParamNum != ArgNum && !DirectCalleeType->isVarArg())
237 return NumArgsMismatch;
238
239 for (unsigned I = 0; I < ParamNum; ++I) {
240 Type *PTy = DirectCalleeType->getFunctionParamType(I);
241 Type *ATy = CS.getArgument(I)->getType();
242 if (PTy == ATy)
243 continue;
244 if (!CastInst::castIsValid(Instruction::BitCast, CS.getArgument(I), PTy))
245 return ArgTypeMismatch;
246 }
247
248 DEBUG(dbgs() << " #" << NumOfPGOICallPromotion << " Promote the icall to "
249 << Symtab->getFuncName(Target) << "\n");
250 TargetFunction = DirectCallee;
251 return OK;
252}
253
254// Indirect-call promotion heuristic. The direct targets are sorted based on
255// the count. Stop at the first target that is not promoted.
256std::vector<ICallPromotionFunc::PromotionCandidate>
257ICallPromotionFunc::getPromotionCandidatesForCallSite(
258 Instruction *Inst, const ArrayRef<InstrProfValueData> &ValueDataRef,
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000259 uint64_t TotalCount, uint32_t NumCandidates) {
Rong Xu6e34c492016-04-27 23:20:27 +0000260 uint32_t NumVals = ValueDataRef.size();
261 std::vector<PromotionCandidate> Ret;
262
263 DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << *Inst
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000264 << " Num_targets: " << NumVals
265 << " Num_candidates: " << NumCandidates << "\n");
Rong Xu6e34c492016-04-27 23:20:27 +0000266 NumOfPGOICallsites++;
267 if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) {
268 DEBUG(dbgs() << " Skip: User options.\n");
269 return Ret;
270 }
271
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000272 for (uint32_t I = 0; I < NumCandidates; I++) {
Rong Xu6e34c492016-04-27 23:20:27 +0000273 uint64_t Count = ValueDataRef[I].Count;
274 assert(Count <= TotalCount);
275 uint64_t Target = ValueDataRef[I].Value;
276 DEBUG(dbgs() << " Candidate " << I << " Count=" << Count
277 << " Target_func: " << Target << "\n");
278
279 if (ICPInvokeOnly && dyn_cast<CallInst>(Inst)) {
280 DEBUG(dbgs() << " Not promote: User options.\n");
281 break;
282 }
283 if (ICPCallOnly && dyn_cast<InvokeInst>(Inst)) {
284 DEBUG(dbgs() << " Not promote: User option.\n");
285 break;
286 }
287 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
288 DEBUG(dbgs() << " Not promote: Cutoff reached.\n");
289 break;
290 }
Rong Xu6e34c492016-04-27 23:20:27 +0000291 Function *TargetFunction = nullptr;
292 TargetStatus Status = isPromotionLegal(Inst, Target, TargetFunction);
293 if (Status != OK) {
294 StringRef TargetFuncName = Symtab->getFuncName(Target);
295 const char *Reason = StatusToString(Status);
296 DEBUG(dbgs() << " Not promote: " << Reason << "\n");
Rong Xu62d5e472016-04-28 17:49:56 +0000297 emitOptimizationRemarkMissed(
Xinliang David Li0b293302016-06-02 01:52:05 +0000298 F.getContext(), "pgo-icall-prom", F, Inst->getDebugLoc(),
Rong Xu6e34c492016-04-27 23:20:27 +0000299 Twine("Cannot promote indirect call to ") +
Rong Xu62d5e472016-04-28 17:49:56 +0000300 (TargetFuncName.empty() ? Twine(Target) : Twine(TargetFuncName)) +
301 Twine(" with count of ") + Twine(Count) + ": " + Reason);
Rong Xu6e34c492016-04-27 23:20:27 +0000302 break;
303 }
304 Ret.push_back(PromotionCandidate(TargetFunction, Count));
305 TotalCount -= Count;
306 }
307 return Ret;
308}
309
310// Create a diamond structure for If_Then_Else. Also update the profile
311// count. Do the fix-up for the invoke instruction.
312static void createIfThenElse(Instruction *Inst, Function *DirectCallee,
313 uint64_t Count, uint64_t TotalCount,
314 BasicBlock **DirectCallBB,
315 BasicBlock **IndirectCallBB,
316 BasicBlock **MergeBB) {
317 CallSite CS(Inst);
318 Value *OrigCallee = CS.getCalledValue();
319
320 IRBuilder<> BBBuilder(Inst);
321 LLVMContext &Ctx = Inst->getContext();
322 Value *BCI1 =
323 BBBuilder.CreateBitCast(OrigCallee, Type::getInt8PtrTy(Ctx), "");
324 Value *BCI2 =
325 BBBuilder.CreateBitCast(DirectCallee, Type::getInt8PtrTy(Ctx), "");
326 Value *PtrCmp = BBBuilder.CreateICmpEQ(BCI1, BCI2, "");
327
328 uint64_t ElseCount = TotalCount - Count;
329 uint64_t MaxCount = (Count >= ElseCount ? Count : ElseCount);
330 uint64_t Scale = calculateCountScale(MaxCount);
331 MDBuilder MDB(Inst->getContext());
332 MDNode *BranchWeights = MDB.createBranchWeights(
333 scaleBranchCount(Count, Scale), scaleBranchCount(ElseCount, Scale));
334 TerminatorInst *ThenTerm, *ElseTerm;
335 SplitBlockAndInsertIfThenElse(PtrCmp, Inst, &ThenTerm, &ElseTerm,
336 BranchWeights);
337 *DirectCallBB = ThenTerm->getParent();
338 (*DirectCallBB)->setName("if.true.direct_targ");
339 *IndirectCallBB = ElseTerm->getParent();
340 (*IndirectCallBB)->setName("if.false.orig_indirect");
341 *MergeBB = Inst->getParent();
342 (*MergeBB)->setName("if.end.icp");
343
344 // Special handing of Invoke instructions.
345 InvokeInst *II = dyn_cast<InvokeInst>(Inst);
346 if (!II)
347 return;
348
349 // We don't need branch instructions for invoke.
350 ThenTerm->eraseFromParent();
351 ElseTerm->eraseFromParent();
352
353 // Add jump from Merge BB to the NormalDest. This is needed for the newly
354 // created direct invoke stmt -- as its NormalDst will be fixed up to MergeBB.
355 BranchInst::Create(II->getNormalDest(), *MergeBB);
356}
357
358// Find the PHI in BB that have the CallResult as the operand.
359static bool getCallRetPHINode(BasicBlock *BB, Instruction *Inst) {
360 BasicBlock *From = Inst->getParent();
361 for (auto &I : *BB) {
362 PHINode *PHI = dyn_cast<PHINode>(&I);
363 if (!PHI)
364 continue;
365 int IX = PHI->getBasicBlockIndex(From);
366 if (IX == -1)
367 continue;
368 Value *V = PHI->getIncomingValue(IX);
369 if (dyn_cast<Instruction>(V) == Inst)
370 return true;
371 }
372 return false;
373}
374
375// This method fixes up PHI nodes in BB where BB is the UnwindDest of an
376// invoke instruction. In BB, there may be PHIs with incoming block being
377// OrigBB (the MergeBB after if-then-else splitting). After moving the invoke
378// instructions to its own BB, OrigBB is no longer the predecessor block of BB.
379// Instead two new predecessors are added: IndirectCallBB and DirectCallBB,
380// so the PHI node's incoming BBs need to be fixed up accordingly.
381static void fixupPHINodeForUnwind(Instruction *Inst, BasicBlock *BB,
382 BasicBlock *OrigBB,
383 BasicBlock *IndirectCallBB,
384 BasicBlock *DirectCallBB) {
385 for (auto &I : *BB) {
386 PHINode *PHI = dyn_cast<PHINode>(&I);
387 if (!PHI)
388 continue;
389 int IX = PHI->getBasicBlockIndex(OrigBB);
390 if (IX == -1)
391 continue;
392 Value *V = PHI->getIncomingValue(IX);
393 PHI->addIncoming(V, IndirectCallBB);
394 PHI->setIncomingBlock(IX, DirectCallBB);
395 }
396}
397
398// This method fixes up PHI nodes in BB where BB is the NormalDest of an
399// invoke instruction. In BB, there may be PHIs with incoming block being
400// OrigBB (the MergeBB after if-then-else splitting). After moving the invoke
401// instructions to its own BB, a new incoming edge will be added to the original
402// NormalDstBB from the IndirectCallBB.
403static void fixupPHINodeForNormalDest(Instruction *Inst, BasicBlock *BB,
404 BasicBlock *OrigBB,
405 BasicBlock *IndirectCallBB,
406 Instruction *NewInst) {
407 for (auto &I : *BB) {
408 PHINode *PHI = dyn_cast<PHINode>(&I);
409 if (!PHI)
410 continue;
411 int IX = PHI->getBasicBlockIndex(OrigBB);
412 if (IX == -1)
413 continue;
414 Value *V = PHI->getIncomingValue(IX);
415 if (dyn_cast<Instruction>(V) == Inst) {
416 PHI->setIncomingBlock(IX, IndirectCallBB);
417 PHI->addIncoming(NewInst, OrigBB);
418 continue;
419 }
420 PHI->addIncoming(V, IndirectCallBB);
421 }
422}
423
424// Add a bitcast instruction to the direct-call return value if needed.
Rong Xu6e34c492016-04-27 23:20:27 +0000425static Instruction *insertCallRetCast(const Instruction *Inst,
426 Instruction *DirectCallInst,
427 Function *DirectCallee) {
428 if (Inst->getType()->isVoidTy())
429 return DirectCallInst;
430
431 Type *CallRetType = Inst->getType();
432 Type *FuncRetType = DirectCallee->getReturnType();
433 if (FuncRetType == CallRetType)
434 return DirectCallInst;
435
436 BasicBlock *InsertionBB;
437 if (CallInst *CI = dyn_cast<CallInst>(DirectCallInst))
438 InsertionBB = CI->getParent();
439 else
440 InsertionBB = (dyn_cast<InvokeInst>(DirectCallInst))->getNormalDest();
441
442 return (new BitCastInst(DirectCallInst, CallRetType, "",
443 InsertionBB->getTerminator()));
444}
445
446// Create a DirectCall instruction in the DirectCallBB.
447// Parameter Inst is the indirect-call (invoke) instruction.
448// DirectCallee is the decl of the direct-call (invoke) target.
449// DirecallBB is the BB that the direct-call (invoke) instruction is inserted.
450// MergeBB is the bottom BB of the if-then-else-diamond after the
451// transformation. For invoke instruction, the edges from DirectCallBB and
452// IndirectCallBB to MergeBB are removed before this call (during
453// createIfThenElse).
454static Instruction *createDirectCallInst(const Instruction *Inst,
455 Function *DirectCallee,
456 BasicBlock *DirectCallBB,
457 BasicBlock *MergeBB) {
458 Instruction *NewInst = Inst->clone();
459 if (CallInst *CI = dyn_cast<CallInst>(NewInst)) {
460 CI->setCalledFunction(DirectCallee);
461 CI->mutateFunctionType(DirectCallee->getFunctionType());
462 } else {
463 // Must be an invoke instruction. Direct invoke's normal destination is
464 // fixed up to MergeBB. MergeBB is the place where return cast is inserted.
465 // Also since IndirectCallBB does not have an edge to MergeBB, there is no
466 // need to insert new PHIs into MergeBB.
467 InvokeInst *II = dyn_cast<InvokeInst>(NewInst);
468 assert(II);
469 II->setCalledFunction(DirectCallee);
470 II->mutateFunctionType(DirectCallee->getFunctionType());
471 II->setNormalDest(MergeBB);
472 }
473
474 DirectCallBB->getInstList().insert(DirectCallBB->getFirstInsertionPt(),
475 NewInst);
476
477 // Clear the value profile data.
478 NewInst->setMetadata(LLVMContext::MD_prof, 0);
479 CallSite NewCS(NewInst);
480 FunctionType *DirectCalleeType = DirectCallee->getFunctionType();
481 unsigned ParamNum = DirectCalleeType->getFunctionNumParams();
482 for (unsigned I = 0; I < ParamNum; ++I) {
483 Type *ATy = NewCS.getArgument(I)->getType();
484 Type *PTy = DirectCalleeType->getParamType(I);
485 if (ATy != PTy) {
486 BitCastInst *BI = new BitCastInst(NewCS.getArgument(I), PTy, "", NewInst);
487 NewCS.setArgument(I, BI);
488 }
489 }
490
491 return insertCallRetCast(Inst, NewInst, DirectCallee);
492}
493
494// Create a PHI to unify the return values of calls.
495static void insertCallRetPHI(Instruction *Inst, Instruction *CallResult,
496 Function *DirectCallee) {
497 if (Inst->getType()->isVoidTy())
498 return;
499
500 BasicBlock *RetValBB = CallResult->getParent();
501
502 BasicBlock *PHIBB;
503 if (InvokeInst *II = dyn_cast<InvokeInst>(CallResult))
504 RetValBB = II->getNormalDest();
505
506 PHIBB = RetValBB->getSingleSuccessor();
507 if (getCallRetPHINode(PHIBB, Inst))
508 return;
509
510 PHINode *CallRetPHI = PHINode::Create(Inst->getType(), 0);
511 PHIBB->getInstList().push_front(CallRetPHI);
512 Inst->replaceAllUsesWith(CallRetPHI);
513 CallRetPHI->addIncoming(Inst, Inst->getParent());
514 CallRetPHI->addIncoming(CallResult, RetValBB);
515}
516
517// This function does the actual indirect-call promotion transformation:
518// For an indirect-call like:
519// Ret = (*Foo)(Args);
520// It transforms to:
521// if (Foo == DirectCallee)
522// Ret1 = DirectCallee(Args);
523// else
524// Ret2 = (*Foo)(Args);
525// Ret = phi(Ret1, Ret2);
526// It adds type casts for the args do not match the parameters and the return
527// value. Branch weights metadata also updated.
528void ICallPromotionFunc::promote(Instruction *Inst, Function *DirectCallee,
529 uint64_t Count, uint64_t TotalCount) {
530 assert(DirectCallee != nullptr);
531 BasicBlock *BB = Inst->getParent();
532 // Just to suppress the non-debug build warning.
533 (void)BB;
534 DEBUG(dbgs() << "\n\n== Basic Block Before ==\n");
535 DEBUG(dbgs() << *BB << "\n");
536
537 BasicBlock *DirectCallBB, *IndirectCallBB, *MergeBB;
538 createIfThenElse(Inst, DirectCallee, Count, TotalCount, &DirectCallBB,
539 &IndirectCallBB, &MergeBB);
540
541 Instruction *NewInst =
542 createDirectCallInst(Inst, DirectCallee, DirectCallBB, MergeBB);
543
544 // Move Inst from MergeBB to IndirectCallBB.
545 Inst->removeFromParent();
546 IndirectCallBB->getInstList().insert(IndirectCallBB->getFirstInsertionPt(),
547 Inst);
548
549 if (InvokeInst *II = dyn_cast<InvokeInst>(Inst)) {
550 // At this point, the original indirect invoke instruction has the original
551 // UnwindDest and NormalDest. For the direct invoke instruction, the
552 // NormalDest points to MergeBB, and MergeBB jumps to the original
553 // NormalDest. MergeBB might have a new bitcast instruction for the return
554 // value. The PHIs are with the original NormalDest. Since we now have two
555 // incoming edges to NormalDest and UnwindDest, we have to do some fixups.
556 //
557 // UnwindDest will not use the return value. So pass nullptr here.
558 fixupPHINodeForUnwind(Inst, II->getUnwindDest(), MergeBB, IndirectCallBB,
559 DirectCallBB);
560 // We don't need to update the operand from NormalDest for DirectCallBB.
561 // Pass nullptr here.
562 fixupPHINodeForNormalDest(Inst, II->getNormalDest(), MergeBB,
563 IndirectCallBB, NewInst);
564 }
565
566 insertCallRetPHI(Inst, NewInst, DirectCallee);
567
568 DEBUG(dbgs() << "\n== Basic Blocks After ==\n");
569 DEBUG(dbgs() << *BB << *DirectCallBB << *IndirectCallBB << *MergeBB << "\n");
570
Rong Xu62d5e472016-04-28 17:49:56 +0000571 emitOptimizationRemark(
Xinliang David Li0b293302016-06-02 01:52:05 +0000572 F.getContext(), "pgo-icall-prom", F, Inst->getDebugLoc(),
Rong Xu62d5e472016-04-28 17:49:56 +0000573 Twine("Promote indirect call to ") + DirectCallee->getName() +
574 " with count " + Twine(Count) + " out of " + Twine(TotalCount));
Rong Xu6e34c492016-04-27 23:20:27 +0000575}
576
577// Promote indirect-call to conditional direct-call for one callsite.
578uint32_t ICallPromotionFunc::tryToPromote(
579 Instruction *Inst, const std::vector<PromotionCandidate> &Candidates,
580 uint64_t &TotalCount) {
581 uint32_t NumPromoted = 0;
582
583 for (auto &C : Candidates) {
584 uint64_t Count = C.Count;
585 promote(Inst, C.TargetFunction, Count, TotalCount);
586 assert(TotalCount >= Count);
587 TotalCount -= Count;
588 NumOfPGOICallPromotion++;
589 NumPromoted++;
590 }
591 return NumPromoted;
592}
593
594// Traverse all the indirect-call callsite and get the value profile
595// annotation to perform indirect-call promotion.
596bool ICallPromotionFunc::processFunction() {
597 bool Changed = false;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000598 ICallPromotionAnalysis ICallAnalysis;
Rong Xu6e34c492016-04-27 23:20:27 +0000599 for (auto &I : findIndirectCallSites(F)) {
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000600 uint32_t NumVals, NumCandidates;
Rong Xu6e34c492016-04-27 23:20:27 +0000601 uint64_t TotalCount;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000602 auto ICallProfDataRef = ICallAnalysis.getPromotionCandidatesForInstruction(
603 I, NumVals, TotalCount, NumCandidates);
604 if (!NumCandidates)
Rong Xu6e34c492016-04-27 23:20:27 +0000605 continue;
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000606 auto PromotionCandidates = getPromotionCandidatesForCallSite(
607 I, ICallProfDataRef, TotalCount, NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000608 uint32_t NumPromoted = tryToPromote(I, PromotionCandidates, TotalCount);
609 if (NumPromoted == 0)
610 continue;
611
612 Changed = true;
613 // Adjust the MD.prof metadata. First delete the old one.
614 I->setMetadata(LLVMContext::MD_prof, 0);
615 // If all promoted, we don't need the MD.prof metadata.
616 if (TotalCount == 0 || NumPromoted == NumVals)
617 continue;
618 // Otherwise we need update with the un-promoted records back.
Teresa Johnson1e44b5d2016-07-12 21:13:44 +0000619 annotateValueSite(*M, *I, ICallProfDataRef.slice(NumPromoted), TotalCount,
620 IPVK_IndirectCallTarget, NumCandidates);
Rong Xu6e34c492016-04-27 23:20:27 +0000621 }
622 return Changed;
623}
624
625// A wrapper function that does the actual work.
626static bool promoteIndirectCalls(Module &M, bool InLTO) {
627 if (DisableICP)
628 return false;
629 InstrProfSymtab Symtab;
630 Symtab.create(M, InLTO);
631 bool Changed = false;
632 for (auto &F : M) {
633 if (F.isDeclaration())
634 continue;
635 if (F.hasFnAttribute(Attribute::OptimizeNone))
636 continue;
637 ICallPromotionFunc ICallPromotion(F, &M, &Symtab);
638 bool FuncChanged = ICallPromotion.processFunction();
639 if (ICPDUMPAFTER && FuncChanged) {
640 DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs()));
641 DEBUG(dbgs() << "\n");
642 }
643 Changed |= FuncChanged;
644 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {
645 DEBUG(dbgs() << " Stop: Cutoff reached.\n");
646 break;
647 }
648 }
649 return Changed;
650}
651
Xinliang David Li72616182016-05-15 01:04:24 +0000652bool PGOIndirectCallPromotionLegacyPass::runOnModule(Module &M) {
Rong Xu6e34c492016-04-27 23:20:27 +0000653 // Command-line option has the priority for InLTO.
Xinliang David Li7d0fed72016-05-17 21:06:16 +0000654 return promoteIndirectCalls(M, InLTO | ICPLTOMode);
Rong Xu6e34c492016-04-27 23:20:27 +0000655}
Xinliang David Lif3c7a352016-05-16 16:31:07 +0000656
657PreservedAnalyses PGOIndirectCallPromotion::run(Module &M, AnalysisManager<Module> &AM) {
Xinliang David Li7d0fed72016-05-17 21:06:16 +0000658 if (!promoteIndirectCalls(M, InLTO | ICPLTOMode))
Xinliang David Lif3c7a352016-05-16 16:31:07 +0000659 return PreservedAnalyses::all();
660
661 return PreservedAnalyses::none();
662}