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