55 #define DEBUG_TYPE "pgo-icall-prom"
57 STATISTIC(NumOfPGOICallPromotion,
"Number of indirect call promotions.");
58 STATISTIC(NumOfPGOICallsites,
"Number of indirect call candidate sites.");
63 cl::desc(
"Disable indirect call promotion"));
71 cl::desc(
"Max number of promotions for this compilation"));
77 cl::desc(
"Skip Callsite up to this number for this compilation"));
83 cl::desc(
"Run indirect-call promotion in LTO "
90 cl::desc(
"Run indirect-call promotion in SamplePGO mode"));
96 cl::desc(
"Run indirect-call promotion for call instructions "
103 cl::desc(
"Run indirect-call promotion for "
104 "invoke instruction only"));
110 cl::desc(
"Dump IR after transformation happens"));
113 class PGOIndirectCallPromotionLegacyPass :
public ModulePass {
117 PGOIndirectCallPromotionLegacyPass(
bool InLTO =
false,
bool SamplePGO =
false)
123 StringRef getPassName()
const override {
return "PGOIndirectCallPromotion"; }
126 bool runOnModule(
Module &M)
override;
140 "Use PGO instrumentation profile to promote indirect calls to "
146 return new PGOIndirectCallPromotionLegacyPass(InLTO, SamplePGO);
152 class ICallPromotionFunc {
165 const char **Reason =
nullptr);
168 struct PromotionCandidate {
171 PromotionCandidate(
Function *
F, uint64_t
C) : TargetFunction(F), Count(C) {}
179 std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(
181 uint64_t TotalCount,
uint32_t NumCandidates);
186 const std::vector<PromotionCandidate> &Candidates,
187 uint64_t &TotalCount);
190 ICallPromotionFunc(
const ICallPromotionFunc &other) =
delete;
191 ICallPromotionFunc &operator=(
const ICallPromotionFunc &other) =
delete;
196 :
F(Func), M(Modu), Symtab(Symtab), SamplePGO(SamplePGO) {}
198 bool processFunction();
203 const char **Reason) {
208 if (FuncRetType != CallRetType &&
211 *Reason =
"Return type mismatch";
222 if (ParamNum != ArgNum && !DirectCalleeType->
isVarArg()) {
224 *Reason =
"The number of arguments mismatch";
228 for (
unsigned I = 0;
I < ParamNum; ++
I) {
235 *Reason =
"Argument type mismatch";
240 DEBUG(
dbgs() <<
" #" << NumOfPGOICallPromotion <<
" Promote the icall to "
247 const char **Reason) {
248 TargetFunction = Symtab->getFunction(Target);
249 if (TargetFunction ==
nullptr) {
250 *Reason =
"Cannot find the target";
258 std::vector<ICallPromotionFunc::PromotionCandidate>
259 ICallPromotionFunc::getPromotionCandidatesForCallSite(
261 uint64_t TotalCount,
uint32_t NumCandidates) {
262 std::vector<PromotionCandidate>
Ret;
264 DEBUG(
dbgs() <<
" \nWork on callsite #" << NumOfPGOICallsites << *Inst
265 <<
" Num_targets: " << ValueDataRef.
size()
266 <<
" Num_candidates: " << NumCandidates <<
"\n");
267 NumOfPGOICallsites++;
269 DEBUG(
dbgs() <<
" Skip: User options.\n");
274 uint64_t Count = ValueDataRef[
I].Count;
275 assert(Count <= TotalCount);
276 uint64_t Target = ValueDataRef[
I].Value;
277 DEBUG(
dbgs() <<
" Candidate " <<
I <<
" Count=" << Count
278 <<
" Target_func: " << Target <<
"\n");
281 DEBUG(
dbgs() <<
" Not promote: User options.\n");
285 DEBUG(
dbgs() <<
" Not promote: User option.\n");
289 DEBUG(
dbgs() <<
" Not promote: Cutoff reached.\n");
293 const char *Reason =
nullptr;
294 if (!isPromotionLegal(Inst, Target, TargetFunction, &Reason)) {
295 StringRef TargetFuncName = Symtab->getFuncName(Target);
296 DEBUG(
dbgs() <<
" Not promote: " << Reason <<
"\n");
299 Twine(
"Cannot promote indirect call to ") +
301 Twine(
" with count of ") +
Twine(Count) +
": " + Reason);
304 Ret.push_back(PromotionCandidate(TargetFunction, Count));
313 uint64_t Count, uint64_t TotalCount,
328 uint64_t ElseCount = TotalCount - Count;
329 uint64_t MaxCount = (Count >= ElseCount ? Count : ElseCount);
332 MDNode *BranchWeights = MDB.createBranchWeights(
338 (*DirectCallBB)->
setName(
"if.true.direct_targ");
340 (*IndirectCallBB)->
setName(
"if.false.orig_indirect");
342 (*MergeBB)->
setName(
"if.end.icp");
361 for (
auto &
I : *BB) {
369 if (dyn_cast<Instruction>(V) == Inst)
385 for (
auto &
I : *BB) {
407 for (
auto &
I : *BB) {
415 if (dyn_cast<Instruction>(V) == Inst) {
429 return DirectCallInst;
433 if (FuncRetType == CallRetType)
434 return DirectCallInst;
437 if (
CallInst *CI = dyn_cast<CallInst>(DirectCallInst))
442 return (
new BitCastInst(DirectCallInst, CallRetType,
"",
459 if (
CallInst *CI = dyn_cast<CallInst>(NewInst)) {
460 CI->setCalledFunction(DirectCallee);
482 for (
unsigned I = 0;
I < ParamNum; ++
I) {
503 if (
InvokeInst *II = dyn_cast<InvokeInst>(CallResult))
504 RetValBB = II->getNormalDest();
533 Function *DirectCallee, uint64_t Count,
535 bool AttachProfToDirectCall) {
536 assert(DirectCallee !=
nullptr);
540 DEBUG(
dbgs() <<
"\n\n== Basic Block Before ==\n");
543 BasicBlock *DirectCallBB, *IndirectCallBB, *MergeBB;
545 &IndirectCallBB, &MergeBB);
550 if (AttachProfToDirectCall) {
563 if (
InvokeInst *II = dyn_cast<InvokeInst>(Inst)) {
577 IndirectCallBB, NewInst);
582 DEBUG(
dbgs() <<
"\n== Basic Blocks After ==\n");
583 DEBUG(
dbgs() << *BB << *DirectCallBB << *IndirectCallBB << *MergeBB <<
"\n");
587 Twine(
"Promote indirect call to ") + DirectCallee->
getName() +
588 " with count " +
Twine(Count) +
" out of " +
Twine(TotalCount));
593 uint32_t ICallPromotionFunc::tryToPromote(
594 Instruction *Inst,
const std::vector<PromotionCandidate> &Candidates,
595 uint64_t &TotalCount) {
598 for (
auto &
C : Candidates) {
599 uint64_t Count =
C.Count;
601 assert(TotalCount >= Count);
603 NumOfPGOICallPromotion++;
611 bool ICallPromotionFunc::processFunction() {
612 bool Changed =
false;
618 I, NumVals, TotalCount, NumCandidates);
621 auto PromotionCandidates = getPromotionCandidatesForCallSite(
622 I, ICallProfDataRef, TotalCount, NumCandidates);
623 uint32_t NumPromoted = tryToPromote(
I, PromotionCandidates, TotalCount);
624 if (NumPromoted == 0)
631 if (TotalCount == 0 || NumPromoted == NumVals)
635 IPVK_IndirectCallTarget, NumCandidates);
646 std::string SymtabFailure =
toString(std::move(
E));
647 DEBUG(
dbgs() <<
"Failed to create symtab: " << SymtabFailure <<
"\n");
651 bool Changed =
false;
653 if (
F.isDeclaration())
655 if (
F.hasFnAttribute(Attribute::OptimizeNone))
657 ICallPromotionFunc ICallPromotion(
F, &M, &Symtab, SamplePGO);
658 bool FuncChanged = ICallPromotion.processFunction();
663 Changed |= FuncChanged;
665 DEBUG(
dbgs() <<
" Stop: Cutoff reached.\n");
672 bool PGOIndirectCallPromotionLegacyPass::runOnModule(
Module &M) {
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, TerminatorInst **ThenTerm, TerminatorInst **ElseTerm, MDNode *BranchWeights=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
STATISTIC(NumFunctions,"Total number of functions")
void setCalledFunction(Value *Fn)
Set the function called.
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
This class represents a function call, abstracting a target machine's calling convention.
const Function * getParent() const
Return the enclosing method, or null if none.
Type * getFunctionParamType(unsigned i) const
unsigned arg_size() const
StringRef getName() const
Return a constant reference to the value's name.
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
ValTy * getCalledValue() const
Return the pointer to function that is being called.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void setName(const Twine &Name)
Change the name of the value.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
void setArgument(unsigned ArgNo, Value *newVal)
Class to represent function types.
This file provides the interface for IR based instrumentation passes ( (profile-gen, and profile-use).
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
void setNormalDest(BasicBlock *B)
This class represents a no-op cast from one type to another.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
size_t size() const
size - Get the array size.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
BasicBlock * getNormalDest() const
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
void emitOptimizationRemark(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization-applied message.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
Returns the type of the ret val.
initializer< Ty > init(const Ty &Val)
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
void push_front(pointer val)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
static bool isBitCastable(Type *SrcTy, Type *DestTy)
Check whether a bitcast between these types is valid.
bool isLegalToPromote(Instruction *Inst, Function *F, const char **Reason)
const InstListType & getInstList() const
Return the underlying instruction list container.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
static uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
Instruction * promoteIndirectCall(Instruction *Inst, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall)
static uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVMContext & getContext() const
All values hold a context through their type.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
void emitOptimizationRemarkMissed(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization-missed message.
C setMetadata(LLVMContext::MD_range, MDNode::get(Context, LowAndHigh))
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
ValTy * getArgument(unsigned ArgNo) const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
void mutateFunctionType(FunctionType *FTy)
void initializePGOIndirectCallPromotionLegacyPassPass(PassRegistry &)
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Target - Wrapper for Target specific information.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
unsigned getFunctionNumParams() const
iterator insert(iterator where, pointer New)
static std::vector< Instruction * > findIndirectCallSites(Function &F)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVMContext & getContext() const
Get the context in which this basic block lives.
LLVM Value Representation.
Lightweight error class with error context and mandatory checking.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This header defines various interfaces for pass management in LLVM.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
const BasicBlock * getParent() const
bool isVoidTy() const
Return true if this is 'void'.
ModulePass * createPGOIndirectCallPromotionLegacyPass(bool InLTO=false, bool SamplePGO=false)