blob: 5feeccb6293e3695253226c799fbe61b6dc26c65 [file] [log] [blame]
Rong Xuf430ae42015-12-09 18:08:16 +00001//===-- PGOInstrumentation.cpp - MST-based PGO Instrumentation ------------===//
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 PGO instrumentation using a minimum spanning tree based
11// on the following paper:
12// [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
13// for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
14// Issue 3, pp 313-322
15// The idea of the algorithm based on the fact that for each node (except for
16// the entry and exit), the sum of incoming edge counts equals the sum of
17// outgoing edge counts. The count of edge on spanning tree can be derived from
18// those edges not on the spanning tree. Knuth proves this method instruments
19// the minimum number of edges.
20//
21// The minimal spanning tree here is actually a maximum weight tree -- on-tree
22// edges have higher frequencies (more likely to execute). The idea is to
23// instrument those less frequently executed edges to reduce the runtime
24// overhead of instrumented binaries.
25//
26// This file contains two passes:
27// (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
Rong Xu13b01dc2016-02-10 18:24:45 +000028// count profile, and generates the instrumentation for indirect call
29// profiling.
Rong Xuf430ae42015-12-09 18:08:16 +000030// (2) Pass PGOInstrumentationUse which reads the edge count profile and
Rong Xu13b01dc2016-02-10 18:24:45 +000031// annotates the branch weights. It also reads the indirect call value
32// profiling records and annotate the indirect call instructions.
33//
Rong Xuf430ae42015-12-09 18:08:16 +000034// To get the precise counter information, These two passes need to invoke at
35// the same compilation point (so they see the same IR). For pass
36// PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
37// pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
38// the profile is opened in module level and passed to each PGOUseFunc instance.
39// The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
40// in class FuncPGOInstrumentation.
41//
42// Class PGOEdge represents a CFG edge and some auxiliary information. Class
43// BBInfo contains auxiliary information for each BB. These two classes are used
44// in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
45// class of PGOEdge and BBInfo, respectively. They contains extra data structure
46// used in populating profile counters.
47// The MST implementation is in Class CFGMST (CFGMST.h).
48//
49//===----------------------------------------------------------------------===//
50
Rong Xuf430ae42015-12-09 18:08:16 +000051#include "CFGMST.h"
52#include "llvm/ADT/DenseMap.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/Statistic.h"
Rong Xu33c76c02016-02-10 17:18:30 +000055#include "llvm/ADT/Triple.h"
Rong Xuf430ae42015-12-09 18:08:16 +000056#include "llvm/Analysis/BlockFrequencyInfo.h"
57#include "llvm/Analysis/BranchProbabilityInfo.h"
58#include "llvm/Analysis/CFG.h"
Rong Xued9fec72016-01-21 18:11:44 +000059#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000060#include "llvm/IR/DiagnosticInfo.h"
61#include "llvm/IR/IRBuilder.h"
62#include "llvm/IR/InstIterator.h"
Rong Xued9fec72016-01-21 18:11:44 +000063#include "llvm/IR/InstVisitor.h"
Rong Xuf430ae42015-12-09 18:08:16 +000064#include "llvm/IR/Instructions.h"
65#include "llvm/IR/IntrinsicInst.h"
66#include "llvm/IR/MDBuilder.h"
67#include "llvm/IR/Module.h"
68#include "llvm/Pass.h"
69#include "llvm/ProfileData/InstrProfReader.h"
70#include "llvm/Support/BranchProbability.h"
71#include "llvm/Support/Debug.h"
72#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000073#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000074#include "llvm/Transforms/Utils/BasicBlockUtils.h"
75#include <string>
76#include <utility>
77#include <vector>
78
79using namespace llvm;
80
81#define DEBUG_TYPE "pgo-instrumentation"
82
83STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
84STATISTIC(NumOfPGOEdge, "Number of edges.");
85STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
86STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
87STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
88STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
89STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000090STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000091
92// Command line option to specify the file to read profile from. This is
93// mainly used for testing.
94static cl::opt<std::string>
95 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
96 cl::value_desc("filename"),
97 cl::desc("Specify the path of profile data file. This is"
98 "mainly for test purpose."));
99
Rong Xuecdc98f2016-03-04 22:08:44 +0000100// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000101// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000102static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
103 cl::Hidden,
104 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000105
Rong Xuecdc98f2016-03-04 22:08:44 +0000106// Command line option to set the maximum number of VP annotations to write to
107// the metada for a single indirect call callsite.
108static cl::opt<unsigned>
109 MaxNumAnnotations("icp-max-annotations", cl::init(3), cl::Hidden,
110 cl::ZeroOrMore,
111 cl::desc("Max number of annotations for a single indirect "
112 "call callsite"));
113
Rong Xuf430ae42015-12-09 18:08:16 +0000114namespace {
115class PGOInstrumentationGen : public ModulePass {
116public:
117 static char ID;
118
119 PGOInstrumentationGen() : ModulePass(ID) {
120 initializePGOInstrumentationGenPass(*PassRegistry::getPassRegistry());
121 }
122
123 const char *getPassName() const override {
124 return "PGOInstrumentationGenPass";
125 }
126
127private:
128 bool runOnModule(Module &M) override;
129
130 void getAnalysisUsage(AnalysisUsage &AU) const override {
131 AU.addRequired<BlockFrequencyInfoWrapperPass>();
132 }
133};
134
135class PGOInstrumentationUse : public ModulePass {
136public:
137 static char ID;
138
139 // Provide the profile filename as the parameter.
140 PGOInstrumentationUse(std::string Filename = "")
141 : ModulePass(ID), ProfileFileName(Filename) {
142 if (!PGOTestProfileFile.empty())
143 ProfileFileName = PGOTestProfileFile;
144 initializePGOInstrumentationUsePass(*PassRegistry::getPassRegistry());
145 }
146
147 const char *getPassName() const override {
148 return "PGOInstrumentationUsePass";
149 }
150
151private:
152 std::string ProfileFileName;
153 std::unique_ptr<IndexedInstrProfReader> PGOReader;
154 bool runOnModule(Module &M) override;
155
156 void getAnalysisUsage(AnalysisUsage &AU) const override {
157 AU.addRequired<BlockFrequencyInfoWrapperPass>();
158 }
159};
160} // end anonymous namespace
161
162char PGOInstrumentationGen::ID = 0;
163INITIALIZE_PASS_BEGIN(PGOInstrumentationGen, "pgo-instr-gen",
164 "PGO instrumentation.", false, false)
165INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
166INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
167INITIALIZE_PASS_END(PGOInstrumentationGen, "pgo-instr-gen",
168 "PGO instrumentation.", false, false)
169
170ModulePass *llvm::createPGOInstrumentationGenPass() {
171 return new PGOInstrumentationGen();
172}
173
174char PGOInstrumentationUse::ID = 0;
175INITIALIZE_PASS_BEGIN(PGOInstrumentationUse, "pgo-instr-use",
176 "Read PGO instrumentation profile.", false, false)
177INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
178INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
179INITIALIZE_PASS_END(PGOInstrumentationUse, "pgo-instr-use",
180 "Read PGO instrumentation profile.", false, false)
181
182ModulePass *llvm::createPGOInstrumentationUsePass(StringRef Filename) {
183 return new PGOInstrumentationUse(Filename.str());
184}
185
186namespace {
187/// \brief An MST based instrumentation for PGO
188///
189/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
190/// in the function level.
191struct PGOEdge {
192 // This class implements the CFG edges. Note the CFG can be a multi-graph.
193 // So there might be multiple edges with same SrcBB and DestBB.
194 const BasicBlock *SrcBB;
195 const BasicBlock *DestBB;
196 uint64_t Weight;
197 bool InMST;
198 bool Removed;
199 bool IsCritical;
200 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
201 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
202 IsCritical(false) {}
203 // Return the information string of an edge.
204 const std::string infoString() const {
205 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
206 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
207 }
208};
209
210// This class stores the auxiliary information for each BB.
211struct BBInfo {
212 BBInfo *Group;
213 uint32_t Index;
214 uint32_t Rank;
215
216 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
217
218 // Return the information string of this object.
219 const std::string infoString() const {
220 return (Twine("Index=") + Twine(Index)).str();
221 }
222};
223
224// This class implements the CFG edges. Note the CFG can be a multi-graph.
225template <class Edge, class BBInfo> class FuncPGOInstrumentation {
226private:
227 Function &F;
228 void computeCFGHash();
229
230public:
231 std::string FuncName;
232 GlobalVariable *FuncNameVar;
233 // CFG hash value for this function.
234 uint64_t FunctionHash;
235
236 // The Minimum Spanning Tree of function CFG.
237 CFGMST<Edge, BBInfo> MST;
238
239 // Give an edge, find the BB that will be instrumented.
240 // Return nullptr if there is no BB to be instrumented.
241 BasicBlock *getInstrBB(Edge *E);
242
243 // Return the auxiliary BB information.
244 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
245
246 // Dump edges and BB information.
247 void dumpInfo(std::string Str = "") const {
248 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000249 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000250 }
251
252 FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false,
253 BranchProbabilityInfo *BPI = nullptr,
254 BlockFrequencyInfo *BFI = nullptr)
255 : F(Func), FunctionHash(0), MST(F, BPI, BFI) {
256 FuncName = getPGOFuncName(F);
257 computeCFGHash();
258 DEBUG(dumpInfo("after CFGMST"));
259
260 NumOfPGOBB += MST.BBInfos.size();
261 for (auto &E : MST.AllEdges) {
262 if (E->Removed)
263 continue;
264 NumOfPGOEdge++;
265 if (!E->InMST)
266 NumOfPGOInstrument++;
267 }
268
269 if (CreateGlobalVar)
270 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000271 }
Rong Xuf430ae42015-12-09 18:08:16 +0000272};
273
274// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
275// value of each BB in the CFG. The higher 32 bits record the number of edges.
276template <class Edge, class BBInfo>
277void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
278 std::vector<char> Indexes;
279 JamCRC JC;
280 for (auto &BB : F) {
281 const TerminatorInst *TI = BB.getTerminator();
282 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
283 BasicBlock *Succ = TI->getSuccessor(I);
284 uint32_t Index = getBBInfo(Succ).Index;
285 for (int J = 0; J < 4; J++)
286 Indexes.push_back((char)(Index >> (J * 8)));
287 }
288 }
289 JC.update(Indexes);
290 FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
291}
292
293// Given a CFG E to be instrumented, find which BB to place the instrumented
294// code. The function will split the critical edge if necessary.
295template <class Edge, class BBInfo>
296BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
297 if (E->InMST || E->Removed)
298 return nullptr;
299
300 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
301 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
302 // For a fake edge, instrument the real BB.
303 if (SrcBB == nullptr)
304 return DestBB;
305 if (DestBB == nullptr)
306 return SrcBB;
307
308 // Instrument the SrcBB if it has a single successor,
309 // otherwise, the DestBB if this is not a critical edge.
310 TerminatorInst *TI = SrcBB->getTerminator();
311 if (TI->getNumSuccessors() <= 1)
312 return SrcBB;
313 if (!E->IsCritical)
314 return DestBB;
315
316 // For a critical edge, we have to split. Instrument the newly
317 // created BB.
318 NumOfPGOSplit++;
319 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
320 << getBBInfo(DestBB).Index << "\n");
321 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
322 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
323 assert(InstrBB && "Critical edge is not split");
324
325 E->Removed = true;
326 return InstrBB;
327}
328
Rong Xued9fec72016-01-21 18:11:44 +0000329// Visitor class that finds all indirect call sites.
330struct PGOIndirectCallSiteVisitor
331 : public InstVisitor<PGOIndirectCallSiteVisitor> {
Xinliang David Lia55fd1a2016-03-30 02:16:07 +0000332 std::vector<Instruction *> IndirectCallInsts;
Rong Xued9fec72016-01-21 18:11:44 +0000333 PGOIndirectCallSiteVisitor() {}
334
Xinliang David Lia55fd1a2016-03-30 02:16:07 +0000335 void visitCallSite(CallSite CS) {
Xinliang David Lid0b4cbb2016-03-31 16:22:17 +0000336 if (CS.getCalledFunction() || !CS.getCalledValue())
Rong Xued9fec72016-01-21 18:11:44 +0000337 return;
Xinliang David Lid0b4cbb2016-03-31 16:22:17 +0000338 Instruction *I = CS.getInstruction();
339 if (CallInst *CI = dyn_cast<CallInst>(I)) {
340 if (CI->isInlineAsm())
341 return;
342 }
Xinliang David Lia55fd1a2016-03-30 02:16:07 +0000343 IndirectCallInsts.push_back(I);
Rong Xued9fec72016-01-21 18:11:44 +0000344 }
345};
346
347// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000348// Critical edges will be split.
349static void instrumentOneFunc(Function &F, Module *M,
350 BranchProbabilityInfo *BPI,
351 BlockFrequencyInfo *BFI) {
352 unsigned NumCounters = 0;
353 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);
354 for (auto &E : FuncInfo.MST.AllEdges) {
355 if (!E->InMST && !E->Removed)
356 NumCounters++;
357 }
358
359 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000360 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000361 for (auto &E : FuncInfo.MST.AllEdges) {
362 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
363 if (!InstrBB)
364 continue;
365
366 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
367 assert(Builder.GetInsertPoint() != InstrBB->end() &&
368 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000369 Builder.CreateCall(
370 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
371 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
372 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
373 Builder.getInt32(I++)});
374 }
Rong Xued9fec72016-01-21 18:11:44 +0000375
376 if (DisableValueProfiling)
377 return;
378
379 unsigned NumIndirectCallSites = 0;
380 PGOIndirectCallSiteVisitor ICV;
381 ICV.visit(F);
382 for (auto &I : ICV.IndirectCallInsts) {
383 CallSite CS(I);
384 Value *Callee = CS.getCalledValue();
385 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
386 << NumIndirectCallSites << "\n");
387 IRBuilder<> Builder(I);
388 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
389 "Cannot get the Instrumentation point");
390 Builder.CreateCall(
391 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
392 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
393 Builder.getInt64(FuncInfo.FunctionHash),
394 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
395 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
396 Builder.getInt32(NumIndirectCallSites++)});
397 }
398 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000399}
400
401// This class represents a CFG edge in profile use compilation.
402struct PGOUseEdge : public PGOEdge {
403 bool CountValid;
404 uint64_t CountValue;
405 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
406 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
407
408 // Set edge count value
409 void setEdgeCount(uint64_t Value) {
410 CountValue = Value;
411 CountValid = true;
412 }
413
414 // Return the information string for this object.
415 const std::string infoString() const {
416 if (!CountValid)
417 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000418 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
419 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000420 }
421};
422
423typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
424
425// This class stores the auxiliary information for each BB.
426struct UseBBInfo : public BBInfo {
427 uint64_t CountValue;
428 bool CountValid;
429 int32_t UnknownCountInEdge;
430 int32_t UnknownCountOutEdge;
431 DirectEdges InEdges;
432 DirectEdges OutEdges;
433 UseBBInfo(unsigned IX)
434 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
435 UnknownCountOutEdge(0) {}
436 UseBBInfo(unsigned IX, uint64_t C)
437 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
438 UnknownCountOutEdge(0) {}
439
440 // Set the profile count value for this BB.
441 void setBBInfoCount(uint64_t Value) {
442 CountValue = Value;
443 CountValid = true;
444 }
445
446 // Return the information string of this object.
447 const std::string infoString() const {
448 if (!CountValid)
449 return BBInfo::infoString();
450 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
451 }
452};
453
454// Sum up the count values for all the edges.
455static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
456 uint64_t Total = 0;
457 for (auto &E : Edges) {
458 if (E->Removed)
459 continue;
460 Total += E->CountValue;
461 }
462 return Total;
463}
464
465class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000466public:
467 PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr,
468 BlockFrequencyInfo *BFI = nullptr)
469 : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI),
470 FreqAttr(FFA_Normal) {}
471
472 // Read counts for the instrumented BB from profile.
473 bool readCounters(IndexedInstrProfReader *PGOReader);
474
475 // Populate the counts for all BBs.
476 void populateCounters();
477
478 // Set the branch weights based on the count values.
479 void setBranchWeights();
480
481 // Annotate the indirect call sites.
482 void annotateIndirectCallSites();
483
484 // The hotness of the function from the profile count.
485 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
486
487 // Return the funtion hotness from the profile.
488 FuncFreqAttr getFuncFreqAttr() const {
489 return FreqAttr;
490 }
491
Rong Xuf430ae42015-12-09 18:08:16 +0000492private:
493 Function &F;
494 Module *M;
495 // This member stores the shared information with class PGOGenFunc.
496 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
497
498 // Return the auxiliary BB information.
499 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
500 return FuncInfo.getBBInfo(BB);
501 }
502
503 // The maximum count value in the profile. This is only used in PGO use
504 // compilation.
505 uint64_t ProgramMaxCount;
506
Rong Xu13b01dc2016-02-10 18:24:45 +0000507 // ProfileRecord for this function.
508 InstrProfRecord ProfileRecord;
509
Rong Xu6090afd2016-03-28 17:08:56 +0000510 // Function hotness info derived from profile.
511 FuncFreqAttr FreqAttr;
512
Rong Xuf430ae42015-12-09 18:08:16 +0000513 // Find the Instrumented BB and set the value.
514 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
515
516 // Set the edge counter value for the unknown edge -- there should be only
517 // one unknown edge.
518 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
519
520 // Return FuncName string;
521 const std::string getFuncName() const { return FuncInfo.FuncName; }
522
523 // Set the hot/cold inline hints based on the count values.
524 // FIXME: This function should be removed once the functionality in
525 // the inliner is implemented.
Rong Xu6090afd2016-03-28 17:08:56 +0000526 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
Rong Xuf430ae42015-12-09 18:08:16 +0000527 if (ProgramMaxCount == 0)
528 return;
529 // Threshold of the hot functions.
530 const BranchProbability HotFunctionThreshold(1, 100);
531 // Threshold of the cold functions.
532 const BranchProbability ColdFunctionThreshold(2, 10000);
533 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000534 FreqAttr = FFA_Hot;
Rong Xuf430ae42015-12-09 18:08:16 +0000535 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000536 FreqAttr = FFA_Cold;
Rong Xuf430ae42015-12-09 18:08:16 +0000537 }
Rong Xuf430ae42015-12-09 18:08:16 +0000538};
539
540// Visit all the edges and assign the count value for the instrumented
541// edges and the BB.
542void PGOUseFunc::setInstrumentedCounts(
543 const std::vector<uint64_t> &CountFromProfile) {
544
545 // Use a worklist as we will update the vector during the iteration.
546 std::vector<PGOUseEdge *> WorkList;
547 for (auto &E : FuncInfo.MST.AllEdges)
548 WorkList.push_back(E.get());
549
550 uint32_t I = 0;
551 for (auto &E : WorkList) {
552 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
553 if (!InstrBB)
554 continue;
555 uint64_t CountValue = CountFromProfile[I++];
556 if (!E->Removed) {
557 getBBInfo(InstrBB).setBBInfoCount(CountValue);
558 E->setEdgeCount(CountValue);
559 continue;
560 }
561
562 // Need to add two new edges.
563 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
564 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
565 // Add new edge of SrcBB->InstrBB.
566 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
567 NewEdge.setEdgeCount(CountValue);
568 // Add new edge of InstrBB->DestBB.
569 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
570 NewEdge1.setEdgeCount(CountValue);
571 NewEdge1.InMST = true;
572 getBBInfo(InstrBB).setBBInfoCount(CountValue);
573 }
574}
575
576// Set the count value for the unknown edge. There should be one and only one
577// unknown edge in Edges vector.
578void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
579 for (auto &E : Edges) {
580 if (E->CountValid)
581 continue;
582 E->setEdgeCount(Value);
583
584 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
585 getBBInfo(E->DestBB).UnknownCountInEdge--;
586 return;
587 }
588 llvm_unreachable("Cannot find the unknown count edge");
589}
590
591// Read the profile from ProfileFileName and assign the value to the
592// instrumented BB and the edges. This function also updates ProgramMaxCount.
593// Return true if the profile are successfully read, and false on errors.
594bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
595 auto &Ctx = M->getContext();
596 ErrorOr<InstrProfRecord> Result =
597 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
598 if (std::error_code EC = Result.getError()) {
599 if (EC == instrprof_error::unknown_function)
600 NumOfPGOMissing++;
601 else if (EC == instrprof_error::hash_mismatch ||
602 EC == llvm::instrprof_error::malformed)
603 NumOfPGOMismatch++;
604
605 std::string Msg = EC.message() + std::string(" ") + F.getName().str();
606 Ctx.diagnose(
607 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
608 return false;
609 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000610 ProfileRecord = std::move(Result.get());
611 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000612
613 NumOfPGOFunc++;
614 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
615 uint64_t ValueSum = 0;
616 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
617 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
618 ValueSum += CountFromProfile[I];
619 }
620
621 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
622
623 getBBInfo(nullptr).UnknownCountOutEdge = 2;
624 getBBInfo(nullptr).UnknownCountInEdge = 2;
625
626 setInstrumentedCounts(CountFromProfile);
627 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
628 return true;
629}
630
631// Populate the counters from instrumented BBs to all BBs.
632// In the end of this operation, all BBs should have a valid count value.
633void PGOUseFunc::populateCounters() {
634 // First set up Count variable for all BBs.
635 for (auto &E : FuncInfo.MST.AllEdges) {
636 if (E->Removed)
637 continue;
638
639 const BasicBlock *SrcBB = E->SrcBB;
640 const BasicBlock *DestBB = E->DestBB;
641 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
642 UseBBInfo &DestInfo = getBBInfo(DestBB);
643 SrcInfo.OutEdges.push_back(E.get());
644 DestInfo.InEdges.push_back(E.get());
645 SrcInfo.UnknownCountOutEdge++;
646 DestInfo.UnknownCountInEdge++;
647
648 if (!E->CountValid)
649 continue;
650 DestInfo.UnknownCountInEdge--;
651 SrcInfo.UnknownCountOutEdge--;
652 }
653
654 bool Changes = true;
655 unsigned NumPasses = 0;
656 while (Changes) {
657 NumPasses++;
658 Changes = false;
659
660 // For efficient traversal, it's better to start from the end as most
661 // of the instrumented edges are at the end.
662 for (auto &BB : reverse(F)) {
663 UseBBInfo &Count = getBBInfo(&BB);
664 if (!Count.CountValid) {
665 if (Count.UnknownCountOutEdge == 0) {
666 Count.CountValue = sumEdgeCount(Count.OutEdges);
667 Count.CountValid = true;
668 Changes = true;
669 } else if (Count.UnknownCountInEdge == 0) {
670 Count.CountValue = sumEdgeCount(Count.InEdges);
671 Count.CountValid = true;
672 Changes = true;
673 }
674 }
675 if (Count.CountValid) {
676 if (Count.UnknownCountOutEdge == 1) {
677 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
678 setEdgeCount(Count.OutEdges, Total);
679 Changes = true;
680 }
681 if (Count.UnknownCountInEdge == 1) {
682 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
683 setEdgeCount(Count.InEdges, Total);
684 Changes = true;
685 }
686 }
687 }
688 }
689
690 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
691 // Assert every BB has a valid counter.
692 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
693 uint64_t FuncMaxCount = FuncEntryCount;
694 for (auto &BB : F) {
695 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
696 uint64_t Count = getBBInfo(&BB).CountValue;
697 if (Count > FuncMaxCount)
698 FuncMaxCount = Count;
699 }
Rong Xu6090afd2016-03-28 17:08:56 +0000700 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000701
702 DEBUG(FuncInfo.dumpInfo("after reading profile."));
703}
704
705// Assign the scaled count values to the BB with multiple out edges.
706void PGOUseFunc::setBranchWeights() {
707 // Generate MD_prof metadata for every branch instruction.
708 DEBUG(dbgs() << "\nSetting branch weights.\n");
709 MDBuilder MDB(M->getContext());
710 for (auto &BB : F) {
711 TerminatorInst *TI = BB.getTerminator();
712 if (TI->getNumSuccessors() < 2)
713 continue;
714 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
715 continue;
716 if (getBBInfo(&BB).CountValue == 0)
717 continue;
718
719 // We have a non-zero Branch BB.
720 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
721 unsigned Size = BBCountInfo.OutEdges.size();
722 SmallVector<unsigned, 2> EdgeCounts(Size, 0);
723 uint64_t MaxCount = 0;
724 for (unsigned s = 0; s < Size; s++) {
725 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
726 const BasicBlock *SrcBB = E->SrcBB;
727 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000728 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000729 continue;
730 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
731 uint64_t EdgeCount = E->CountValue;
732 if (EdgeCount > MaxCount)
733 MaxCount = EdgeCount;
734 EdgeCounts[SuccNum] = EdgeCount;
735 }
736 assert(MaxCount > 0 && "Bad max count");
737 uint64_t Scale = calculateCountScale(MaxCount);
738 SmallVector<unsigned, 4> Weights;
739 for (const auto &ECI : EdgeCounts)
740 Weights.push_back(scaleBranchCount(ECI, Scale));
741
742 TI->setMetadata(llvm::LLVMContext::MD_prof,
743 MDB.createBranchWeights(Weights));
744 DEBUG(dbgs() << "Weight is: ";
745 for (const auto &W : Weights) { dbgs() << W << " "; }
746 dbgs() << "\n";);
747 }
748}
Rong Xu13b01dc2016-02-10 18:24:45 +0000749
750// Traverse all the indirect callsites and annotate the instructions.
751void PGOUseFunc::annotateIndirectCallSites() {
752 if (DisableValueProfiling)
753 return;
754
Rong Xu8e8fe852016-04-01 16:43:30 +0000755 // Create the PGOFuncName meta data.
756 createPGOFuncNameMetadata(F);
Rong Xub5341662016-03-30 18:37:52 +0000757
Rong Xu13b01dc2016-02-10 18:24:45 +0000758 unsigned IndirectCallSiteIndex = 0;
759 PGOIndirectCallSiteVisitor ICV;
760 ICV.visit(F);
Rong Xu9e926e82016-02-29 19:16:04 +0000761 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +0000762 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
763 if (NumValueSites != ICV.IndirectCallInsts.size()) {
764 std::string Msg =
765 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +0000766 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +0000767 auto &Ctx = M->getContext();
768 Ctx.diagnose(
769 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
770 return;
771 }
772
773 for (auto &I : ICV.IndirectCallInsts) {
774 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +0000775 << IndirectCallSiteIndex << " out of " << NumValueSites
776 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +0000777 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +0000778 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +0000779 IndirectCallSiteIndex++;
780 }
781}
Rong Xuf430ae42015-12-09 18:08:16 +0000782} // end anonymous namespace
783
Rong Xu33c76c02016-02-10 17:18:30 +0000784// Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime
785// aware this is an ir_level profile so it can set the version flag.
786static void createIRLevelProfileFlagVariable(Module &M) {
787 Type *IntTy64 = Type::getInt64Ty(M.getContext());
788 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +0000789 auto IRLevelVersionVariable = new GlobalVariable(
790 M, IntTy64, true, GlobalVariable::ExternalLinkage,
791 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
792 INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +0000793 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
794 Triple TT(M.getTargetTriple());
795 if (TT.isOSBinFormatMachO())
796 IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceODRLinkage);
797 else
Rong Xu9e926e82016-02-29 19:16:04 +0000798 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
799 StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +0000800}
801
Rong Xuf430ae42015-12-09 18:08:16 +0000802bool PGOInstrumentationGen::runOnModule(Module &M) {
Rong Xu33c76c02016-02-10 17:18:30 +0000803 createIRLevelProfileFlagVariable(M);
Rong Xuf430ae42015-12-09 18:08:16 +0000804 for (auto &F : M) {
805 if (F.isDeclaration())
806 continue;
807 BranchProbabilityInfo *BPI =
808 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
809 BlockFrequencyInfo *BFI =
810 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
811 instrumentOneFunc(F, &M, BPI, BFI);
812 }
813 return true;
814}
815
816static void setPGOCountOnFunc(PGOUseFunc &Func,
817 IndexedInstrProfReader *PGOReader) {
818 if (Func.readCounters(PGOReader)) {
819 Func.populateCounters();
820 Func.setBranchWeights();
Rong Xu13b01dc2016-02-10 18:24:45 +0000821 Func.annotateIndirectCallSites();
Rong Xuf430ae42015-12-09 18:08:16 +0000822 }
823}
824
825bool PGOInstrumentationUse::runOnModule(Module &M) {
826 DEBUG(dbgs() << "Read in profile counters: ");
827 auto &Ctx = M.getContext();
828 // Read the counter array from file.
829 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
830 if (std::error_code EC = ReaderOrErr.getError()) {
831 Ctx.diagnose(
832 DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));
833 return false;
834 }
835
836 PGOReader = std::move(ReaderOrErr.get());
837 if (!PGOReader) {
838 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
839 "Cannot get PGOReader"));
840 return false;
841 }
Rong Xu33c76c02016-02-10 17:18:30 +0000842 // TODO: might need to change the warning once the clang option is finalized.
843 if (!PGOReader->isIRLevelProfile()) {
844 Ctx.diagnose(DiagnosticInfoPGOProfile(
845 ProfileFileName.data(), "Not an IR level instrumentation profile"));
846 return false;
847 }
848
Rong Xu6090afd2016-03-28 17:08:56 +0000849 std::vector<Function *> HotFunctions;
850 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +0000851 for (auto &F : M) {
852 if (F.isDeclaration())
853 continue;
854 BranchProbabilityInfo *BPI =
855 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
856 BlockFrequencyInfo *BFI =
857 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
858 PGOUseFunc Func(F, &M, BPI, BFI);
859 setPGOCountOnFunc(Func, PGOReader.get());
Rong Xu6090afd2016-03-28 17:08:56 +0000860 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
861 if (FreqAttr == PGOUseFunc::FFA_Cold)
862 ColdFunctions.push_back(&F);
863 else if (FreqAttr == PGOUseFunc::FFA_Hot)
864 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +0000865 }
Rong Xu6090afd2016-03-28 17:08:56 +0000866
867 // Set function hotness attribute from the profile.
868 for (auto &F : HotFunctions) {
869 F->addFnAttr(llvm::Attribute::InlineHint);
870 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
871 << "\n");
872 }
873 for (auto &F : ColdFunctions) {
874 F->addFnAttr(llvm::Attribute::Cold);
875 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
876 }
877
Rong Xuf430ae42015-12-09 18:08:16 +0000878 return true;
879}