blob: c9e315bc3723f70ac067d349ce65e0e4c6a7c344 [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"
Rong Xu0eb36032016-04-01 23:16:44 +000052#include "IndirectCallSiteVisitor.h"
Rong Xuf430ae42015-12-09 18:08:16 +000053#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"
63#include "llvm/IR/Instructions.h"
64#include "llvm/IR/IntrinsicInst.h"
65#include "llvm/IR/MDBuilder.h"
66#include "llvm/IR/Module.h"
67#include "llvm/Pass.h"
68#include "llvm/ProfileData/InstrProfReader.h"
69#include "llvm/Support/BranchProbability.h"
70#include "llvm/Support/Debug.h"
71#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000072#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000073#include "llvm/Transforms/Utils/BasicBlockUtils.h"
74#include <string>
75#include <utility>
76#include <vector>
77
78using namespace llvm;
79
80#define DEBUG_TYPE "pgo-instrumentation"
81
82STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
83STATISTIC(NumOfPGOEdge, "Number of edges.");
84STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
85STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
86STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
87STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
88STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000089STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000090
91// Command line option to specify the file to read profile from. This is
92// mainly used for testing.
93static cl::opt<std::string>
94 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
95 cl::value_desc("filename"),
96 cl::desc("Specify the path of profile data file. This is"
97 "mainly for test purpose."));
98
Rong Xuecdc98f2016-03-04 22:08:44 +000099// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000100// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000101static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
102 cl::Hidden,
103 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000104
Rong Xuecdc98f2016-03-04 22:08:44 +0000105// Command line option to set the maximum number of VP annotations to write to
106// the metada for a single indirect call callsite.
107static cl::opt<unsigned>
108 MaxNumAnnotations("icp-max-annotations", cl::init(3), cl::Hidden,
109 cl::ZeroOrMore,
110 cl::desc("Max number of annotations for a single indirect "
111 "call callsite"));
112
Rong Xuf430ae42015-12-09 18:08:16 +0000113namespace {
114class PGOInstrumentationGen : public ModulePass {
115public:
116 static char ID;
117
118 PGOInstrumentationGen() : ModulePass(ID) {
119 initializePGOInstrumentationGenPass(*PassRegistry::getPassRegistry());
120 }
121
122 const char *getPassName() const override {
123 return "PGOInstrumentationGenPass";
124 }
125
126private:
127 bool runOnModule(Module &M) override;
128
129 void getAnalysisUsage(AnalysisUsage &AU) const override {
130 AU.addRequired<BlockFrequencyInfoWrapperPass>();
131 }
132};
133
134class PGOInstrumentationUse : public ModulePass {
135public:
136 static char ID;
137
138 // Provide the profile filename as the parameter.
139 PGOInstrumentationUse(std::string Filename = "")
140 : ModulePass(ID), ProfileFileName(Filename) {
141 if (!PGOTestProfileFile.empty())
142 ProfileFileName = PGOTestProfileFile;
143 initializePGOInstrumentationUsePass(*PassRegistry::getPassRegistry());
144 }
145
146 const char *getPassName() const override {
147 return "PGOInstrumentationUsePass";
148 }
149
150private:
151 std::string ProfileFileName;
152 std::unique_ptr<IndexedInstrProfReader> PGOReader;
153 bool runOnModule(Module &M) override;
154
155 void getAnalysisUsage(AnalysisUsage &AU) const override {
156 AU.addRequired<BlockFrequencyInfoWrapperPass>();
157 }
158};
159} // end anonymous namespace
160
161char PGOInstrumentationGen::ID = 0;
162INITIALIZE_PASS_BEGIN(PGOInstrumentationGen, "pgo-instr-gen",
163 "PGO instrumentation.", false, false)
164INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
165INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
166INITIALIZE_PASS_END(PGOInstrumentationGen, "pgo-instr-gen",
167 "PGO instrumentation.", false, false)
168
169ModulePass *llvm::createPGOInstrumentationGenPass() {
170 return new PGOInstrumentationGen();
171}
172
173char PGOInstrumentationUse::ID = 0;
174INITIALIZE_PASS_BEGIN(PGOInstrumentationUse, "pgo-instr-use",
175 "Read PGO instrumentation profile.", false, false)
176INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
177INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
178INITIALIZE_PASS_END(PGOInstrumentationUse, "pgo-instr-use",
179 "Read PGO instrumentation profile.", false, false)
180
181ModulePass *llvm::createPGOInstrumentationUsePass(StringRef Filename) {
182 return new PGOInstrumentationUse(Filename.str());
183}
184
185namespace {
186/// \brief An MST based instrumentation for PGO
187///
188/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
189/// in the function level.
190struct PGOEdge {
191 // This class implements the CFG edges. Note the CFG can be a multi-graph.
192 // So there might be multiple edges with same SrcBB and DestBB.
193 const BasicBlock *SrcBB;
194 const BasicBlock *DestBB;
195 uint64_t Weight;
196 bool InMST;
197 bool Removed;
198 bool IsCritical;
199 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
200 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
201 IsCritical(false) {}
202 // Return the information string of an edge.
203 const std::string infoString() const {
204 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
205 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
206 }
207};
208
209// This class stores the auxiliary information for each BB.
210struct BBInfo {
211 BBInfo *Group;
212 uint32_t Index;
213 uint32_t Rank;
214
215 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
216
217 // Return the information string of this object.
218 const std::string infoString() const {
219 return (Twine("Index=") + Twine(Index)).str();
220 }
221};
222
223// This class implements the CFG edges. Note the CFG can be a multi-graph.
224template <class Edge, class BBInfo> class FuncPGOInstrumentation {
225private:
226 Function &F;
227 void computeCFGHash();
228
229public:
230 std::string FuncName;
231 GlobalVariable *FuncNameVar;
232 // CFG hash value for this function.
233 uint64_t FunctionHash;
234
235 // The Minimum Spanning Tree of function CFG.
236 CFGMST<Edge, BBInfo> MST;
237
238 // Give an edge, find the BB that will be instrumented.
239 // Return nullptr if there is no BB to be instrumented.
240 BasicBlock *getInstrBB(Edge *E);
241
242 // Return the auxiliary BB information.
243 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
244
245 // Dump edges and BB information.
246 void dumpInfo(std::string Str = "") const {
247 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000248 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000249 }
250
251 FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false,
252 BranchProbabilityInfo *BPI = nullptr,
253 BlockFrequencyInfo *BFI = nullptr)
254 : F(Func), FunctionHash(0), MST(F, BPI, BFI) {
255 FuncName = getPGOFuncName(F);
256 computeCFGHash();
257 DEBUG(dumpInfo("after CFGMST"));
258
259 NumOfPGOBB += MST.BBInfos.size();
260 for (auto &E : MST.AllEdges) {
261 if (E->Removed)
262 continue;
263 NumOfPGOEdge++;
264 if (!E->InMST)
265 NumOfPGOInstrument++;
266 }
267
268 if (CreateGlobalVar)
269 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000270 }
Rong Xuf430ae42015-12-09 18:08:16 +0000271};
272
273// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
274// value of each BB in the CFG. The higher 32 bits record the number of edges.
275template <class Edge, class BBInfo>
276void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
277 std::vector<char> Indexes;
278 JamCRC JC;
279 for (auto &BB : F) {
280 const TerminatorInst *TI = BB.getTerminator();
281 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
282 BasicBlock *Succ = TI->getSuccessor(I);
283 uint32_t Index = getBBInfo(Succ).Index;
284 for (int J = 0; J < 4; J++)
285 Indexes.push_back((char)(Index >> (J * 8)));
286 }
287 }
288 JC.update(Indexes);
289 FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
290}
291
292// Given a CFG E to be instrumented, find which BB to place the instrumented
293// code. The function will split the critical edge if necessary.
294template <class Edge, class BBInfo>
295BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
296 if (E->InMST || E->Removed)
297 return nullptr;
298
299 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
300 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
301 // For a fake edge, instrument the real BB.
302 if (SrcBB == nullptr)
303 return DestBB;
304 if (DestBB == nullptr)
305 return SrcBB;
306
307 // Instrument the SrcBB if it has a single successor,
308 // otherwise, the DestBB if this is not a critical edge.
309 TerminatorInst *TI = SrcBB->getTerminator();
310 if (TI->getNumSuccessors() <= 1)
311 return SrcBB;
312 if (!E->IsCritical)
313 return DestBB;
314
315 // For a critical edge, we have to split. Instrument the newly
316 // created BB.
317 NumOfPGOSplit++;
318 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
319 << getBBInfo(DestBB).Index << "\n");
320 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
321 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
322 assert(InstrBB && "Critical edge is not split");
323
324 E->Removed = true;
325 return InstrBB;
326}
327
Rong Xued9fec72016-01-21 18:11:44 +0000328// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000329// Critical edges will be split.
330static void instrumentOneFunc(Function &F, Module *M,
331 BranchProbabilityInfo *BPI,
332 BlockFrequencyInfo *BFI) {
333 unsigned NumCounters = 0;
334 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);
335 for (auto &E : FuncInfo.MST.AllEdges) {
336 if (!E->InMST && !E->Removed)
337 NumCounters++;
338 }
339
340 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000341 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000342 for (auto &E : FuncInfo.MST.AllEdges) {
343 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
344 if (!InstrBB)
345 continue;
346
347 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
348 assert(Builder.GetInsertPoint() != InstrBB->end() &&
349 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000350 Builder.CreateCall(
351 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
352 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
353 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
354 Builder.getInt32(I++)});
355 }
Rong Xued9fec72016-01-21 18:11:44 +0000356
357 if (DisableValueProfiling)
358 return;
359
360 unsigned NumIndirectCallSites = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000361 for (auto &I : findIndirectCallSites(F)) {
Rong Xued9fec72016-01-21 18:11:44 +0000362 CallSite CS(I);
363 Value *Callee = CS.getCalledValue();
364 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
365 << NumIndirectCallSites << "\n");
366 IRBuilder<> Builder(I);
367 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
368 "Cannot get the Instrumentation point");
369 Builder.CreateCall(
370 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
371 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
372 Builder.getInt64(FuncInfo.FunctionHash),
373 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
374 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
375 Builder.getInt32(NumIndirectCallSites++)});
376 }
377 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000378}
379
380// This class represents a CFG edge in profile use compilation.
381struct PGOUseEdge : public PGOEdge {
382 bool CountValid;
383 uint64_t CountValue;
384 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
385 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
386
387 // Set edge count value
388 void setEdgeCount(uint64_t Value) {
389 CountValue = Value;
390 CountValid = true;
391 }
392
393 // Return the information string for this object.
394 const std::string infoString() const {
395 if (!CountValid)
396 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000397 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
398 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000399 }
400};
401
402typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
403
404// This class stores the auxiliary information for each BB.
405struct UseBBInfo : public BBInfo {
406 uint64_t CountValue;
407 bool CountValid;
408 int32_t UnknownCountInEdge;
409 int32_t UnknownCountOutEdge;
410 DirectEdges InEdges;
411 DirectEdges OutEdges;
412 UseBBInfo(unsigned IX)
413 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
414 UnknownCountOutEdge(0) {}
415 UseBBInfo(unsigned IX, uint64_t C)
416 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
417 UnknownCountOutEdge(0) {}
418
419 // Set the profile count value for this BB.
420 void setBBInfoCount(uint64_t Value) {
421 CountValue = Value;
422 CountValid = true;
423 }
424
425 // Return the information string of this object.
426 const std::string infoString() const {
427 if (!CountValid)
428 return BBInfo::infoString();
429 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
430 }
431};
432
433// Sum up the count values for all the edges.
434static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
435 uint64_t Total = 0;
436 for (auto &E : Edges) {
437 if (E->Removed)
438 continue;
439 Total += E->CountValue;
440 }
441 return Total;
442}
443
444class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000445public:
446 PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr,
447 BlockFrequencyInfo *BFI = nullptr)
448 : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI),
449 FreqAttr(FFA_Normal) {}
450
451 // Read counts for the instrumented BB from profile.
452 bool readCounters(IndexedInstrProfReader *PGOReader);
453
454 // Populate the counts for all BBs.
455 void populateCounters();
456
457 // Set the branch weights based on the count values.
458 void setBranchWeights();
459
460 // Annotate the indirect call sites.
461 void annotateIndirectCallSites();
462
463 // The hotness of the function from the profile count.
464 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
465
466 // Return the funtion hotness from the profile.
467 FuncFreqAttr getFuncFreqAttr() const {
468 return FreqAttr;
469 }
470
Rong Xuf430ae42015-12-09 18:08:16 +0000471private:
472 Function &F;
473 Module *M;
474 // This member stores the shared information with class PGOGenFunc.
475 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
476
477 // Return the auxiliary BB information.
478 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
479 return FuncInfo.getBBInfo(BB);
480 }
481
482 // The maximum count value in the profile. This is only used in PGO use
483 // compilation.
484 uint64_t ProgramMaxCount;
485
Rong Xu13b01dc2016-02-10 18:24:45 +0000486 // ProfileRecord for this function.
487 InstrProfRecord ProfileRecord;
488
Rong Xu6090afd2016-03-28 17:08:56 +0000489 // Function hotness info derived from profile.
490 FuncFreqAttr FreqAttr;
491
Rong Xuf430ae42015-12-09 18:08:16 +0000492 // Find the Instrumented BB and set the value.
493 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
494
495 // Set the edge counter value for the unknown edge -- there should be only
496 // one unknown edge.
497 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
498
499 // Return FuncName string;
500 const std::string getFuncName() const { return FuncInfo.FuncName; }
501
502 // Set the hot/cold inline hints based on the count values.
503 // FIXME: This function should be removed once the functionality in
504 // the inliner is implemented.
Rong Xu6090afd2016-03-28 17:08:56 +0000505 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
Rong Xuf430ae42015-12-09 18:08:16 +0000506 if (ProgramMaxCount == 0)
507 return;
508 // Threshold of the hot functions.
509 const BranchProbability HotFunctionThreshold(1, 100);
510 // Threshold of the cold functions.
511 const BranchProbability ColdFunctionThreshold(2, 10000);
512 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000513 FreqAttr = FFA_Hot;
Rong Xuf430ae42015-12-09 18:08:16 +0000514 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000515 FreqAttr = FFA_Cold;
Rong Xuf430ae42015-12-09 18:08:16 +0000516 }
Rong Xuf430ae42015-12-09 18:08:16 +0000517};
518
519// Visit all the edges and assign the count value for the instrumented
520// edges and the BB.
521void PGOUseFunc::setInstrumentedCounts(
522 const std::vector<uint64_t> &CountFromProfile) {
523
524 // Use a worklist as we will update the vector during the iteration.
525 std::vector<PGOUseEdge *> WorkList;
526 for (auto &E : FuncInfo.MST.AllEdges)
527 WorkList.push_back(E.get());
528
529 uint32_t I = 0;
530 for (auto &E : WorkList) {
531 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
532 if (!InstrBB)
533 continue;
534 uint64_t CountValue = CountFromProfile[I++];
535 if (!E->Removed) {
536 getBBInfo(InstrBB).setBBInfoCount(CountValue);
537 E->setEdgeCount(CountValue);
538 continue;
539 }
540
541 // Need to add two new edges.
542 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
543 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
544 // Add new edge of SrcBB->InstrBB.
545 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
546 NewEdge.setEdgeCount(CountValue);
547 // Add new edge of InstrBB->DestBB.
548 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
549 NewEdge1.setEdgeCount(CountValue);
550 NewEdge1.InMST = true;
551 getBBInfo(InstrBB).setBBInfoCount(CountValue);
552 }
553}
554
555// Set the count value for the unknown edge. There should be one and only one
556// unknown edge in Edges vector.
557void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
558 for (auto &E : Edges) {
559 if (E->CountValid)
560 continue;
561 E->setEdgeCount(Value);
562
563 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
564 getBBInfo(E->DestBB).UnknownCountInEdge--;
565 return;
566 }
567 llvm_unreachable("Cannot find the unknown count edge");
568}
569
570// Read the profile from ProfileFileName and assign the value to the
571// instrumented BB and the edges. This function also updates ProgramMaxCount.
572// Return true if the profile are successfully read, and false on errors.
573bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
574 auto &Ctx = M->getContext();
575 ErrorOr<InstrProfRecord> Result =
576 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
577 if (std::error_code EC = Result.getError()) {
578 if (EC == instrprof_error::unknown_function)
579 NumOfPGOMissing++;
580 else if (EC == instrprof_error::hash_mismatch ||
581 EC == llvm::instrprof_error::malformed)
582 NumOfPGOMismatch++;
583
584 std::string Msg = EC.message() + std::string(" ") + F.getName().str();
585 Ctx.diagnose(
586 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
587 return false;
588 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000589 ProfileRecord = std::move(Result.get());
590 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000591
592 NumOfPGOFunc++;
593 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
594 uint64_t ValueSum = 0;
595 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
596 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
597 ValueSum += CountFromProfile[I];
598 }
599
600 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
601
602 getBBInfo(nullptr).UnknownCountOutEdge = 2;
603 getBBInfo(nullptr).UnknownCountInEdge = 2;
604
605 setInstrumentedCounts(CountFromProfile);
606 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
607 return true;
608}
609
610// Populate the counters from instrumented BBs to all BBs.
611// In the end of this operation, all BBs should have a valid count value.
612void PGOUseFunc::populateCounters() {
613 // First set up Count variable for all BBs.
614 for (auto &E : FuncInfo.MST.AllEdges) {
615 if (E->Removed)
616 continue;
617
618 const BasicBlock *SrcBB = E->SrcBB;
619 const BasicBlock *DestBB = E->DestBB;
620 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
621 UseBBInfo &DestInfo = getBBInfo(DestBB);
622 SrcInfo.OutEdges.push_back(E.get());
623 DestInfo.InEdges.push_back(E.get());
624 SrcInfo.UnknownCountOutEdge++;
625 DestInfo.UnknownCountInEdge++;
626
627 if (!E->CountValid)
628 continue;
629 DestInfo.UnknownCountInEdge--;
630 SrcInfo.UnknownCountOutEdge--;
631 }
632
633 bool Changes = true;
634 unsigned NumPasses = 0;
635 while (Changes) {
636 NumPasses++;
637 Changes = false;
638
639 // For efficient traversal, it's better to start from the end as most
640 // of the instrumented edges are at the end.
641 for (auto &BB : reverse(F)) {
642 UseBBInfo &Count = getBBInfo(&BB);
643 if (!Count.CountValid) {
644 if (Count.UnknownCountOutEdge == 0) {
645 Count.CountValue = sumEdgeCount(Count.OutEdges);
646 Count.CountValid = true;
647 Changes = true;
648 } else if (Count.UnknownCountInEdge == 0) {
649 Count.CountValue = sumEdgeCount(Count.InEdges);
650 Count.CountValid = true;
651 Changes = true;
652 }
653 }
654 if (Count.CountValid) {
655 if (Count.UnknownCountOutEdge == 1) {
656 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
657 setEdgeCount(Count.OutEdges, Total);
658 Changes = true;
659 }
660 if (Count.UnknownCountInEdge == 1) {
661 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
662 setEdgeCount(Count.InEdges, Total);
663 Changes = true;
664 }
665 }
666 }
667 }
668
669 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
670 // Assert every BB has a valid counter.
671 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
672 uint64_t FuncMaxCount = FuncEntryCount;
673 for (auto &BB : F) {
674 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
675 uint64_t Count = getBBInfo(&BB).CountValue;
676 if (Count > FuncMaxCount)
677 FuncMaxCount = Count;
678 }
Rong Xu6090afd2016-03-28 17:08:56 +0000679 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000680
681 DEBUG(FuncInfo.dumpInfo("after reading profile."));
682}
683
684// Assign the scaled count values to the BB with multiple out edges.
685void PGOUseFunc::setBranchWeights() {
686 // Generate MD_prof metadata for every branch instruction.
687 DEBUG(dbgs() << "\nSetting branch weights.\n");
688 MDBuilder MDB(M->getContext());
689 for (auto &BB : F) {
690 TerminatorInst *TI = BB.getTerminator();
691 if (TI->getNumSuccessors() < 2)
692 continue;
693 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
694 continue;
695 if (getBBInfo(&BB).CountValue == 0)
696 continue;
697
698 // We have a non-zero Branch BB.
699 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
700 unsigned Size = BBCountInfo.OutEdges.size();
701 SmallVector<unsigned, 2> EdgeCounts(Size, 0);
702 uint64_t MaxCount = 0;
703 for (unsigned s = 0; s < Size; s++) {
704 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
705 const BasicBlock *SrcBB = E->SrcBB;
706 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000707 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000708 continue;
709 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
710 uint64_t EdgeCount = E->CountValue;
711 if (EdgeCount > MaxCount)
712 MaxCount = EdgeCount;
713 EdgeCounts[SuccNum] = EdgeCount;
714 }
715 assert(MaxCount > 0 && "Bad max count");
716 uint64_t Scale = calculateCountScale(MaxCount);
717 SmallVector<unsigned, 4> Weights;
718 for (const auto &ECI : EdgeCounts)
719 Weights.push_back(scaleBranchCount(ECI, Scale));
720
721 TI->setMetadata(llvm::LLVMContext::MD_prof,
722 MDB.createBranchWeights(Weights));
723 DEBUG(dbgs() << "Weight is: ";
724 for (const auto &W : Weights) { dbgs() << W << " "; }
725 dbgs() << "\n";);
726 }
727}
Rong Xu13b01dc2016-02-10 18:24:45 +0000728
729// Traverse all the indirect callsites and annotate the instructions.
730void PGOUseFunc::annotateIndirectCallSites() {
731 if (DisableValueProfiling)
732 return;
733
Rong Xu8e8fe852016-04-01 16:43:30 +0000734 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +0000735 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +0000736
Rong Xu13b01dc2016-02-10 18:24:45 +0000737 unsigned IndirectCallSiteIndex = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000738 auto IndirectCallSites = findIndirectCallSites(F);
Rong Xu9e926e82016-02-29 19:16:04 +0000739 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +0000740 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +0000741 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000742 std::string Msg =
743 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +0000744 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +0000745 auto &Ctx = M->getContext();
746 Ctx.diagnose(
747 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
748 return;
749 }
750
Rong Xu0eb36032016-04-01 23:16:44 +0000751 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000752 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +0000753 << IndirectCallSiteIndex << " out of " << NumValueSites
754 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +0000755 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +0000756 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +0000757 IndirectCallSiteIndex++;
758 }
759}
Rong Xuf430ae42015-12-09 18:08:16 +0000760} // end anonymous namespace
761
Rong Xu33c76c02016-02-10 17:18:30 +0000762// Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime
763// aware this is an ir_level profile so it can set the version flag.
764static void createIRLevelProfileFlagVariable(Module &M) {
765 Type *IntTy64 = Type::getInt64Ty(M.getContext());
766 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +0000767 auto IRLevelVersionVariable = new GlobalVariable(
768 M, IntTy64, true, GlobalVariable::ExternalLinkage,
769 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
770 INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +0000771 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
772 Triple TT(M.getTargetTriple());
773 if (TT.isOSBinFormatMachO())
774 IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceODRLinkage);
775 else
Rong Xu9e926e82016-02-29 19:16:04 +0000776 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
777 StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +0000778}
779
Rong Xuf430ae42015-12-09 18:08:16 +0000780bool PGOInstrumentationGen::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000781 if (skipModule(M))
782 return false;
783
Rong Xu33c76c02016-02-10 17:18:30 +0000784 createIRLevelProfileFlagVariable(M);
Rong Xuf430ae42015-12-09 18:08:16 +0000785 for (auto &F : M) {
786 if (F.isDeclaration())
787 continue;
788 BranchProbabilityInfo *BPI =
789 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
790 BlockFrequencyInfo *BFI =
791 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
792 instrumentOneFunc(F, &M, BPI, BFI);
793 }
794 return true;
795}
796
797static void setPGOCountOnFunc(PGOUseFunc &Func,
798 IndexedInstrProfReader *PGOReader) {
799 if (Func.readCounters(PGOReader)) {
800 Func.populateCounters();
801 Func.setBranchWeights();
Rong Xu13b01dc2016-02-10 18:24:45 +0000802 Func.annotateIndirectCallSites();
Rong Xuf430ae42015-12-09 18:08:16 +0000803 }
804}
805
806bool PGOInstrumentationUse::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000807 if (skipModule(M))
808 return false;
809
Rong Xuf430ae42015-12-09 18:08:16 +0000810 DEBUG(dbgs() << "Read in profile counters: ");
811 auto &Ctx = M.getContext();
812 // Read the counter array from file.
813 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
814 if (std::error_code EC = ReaderOrErr.getError()) {
815 Ctx.diagnose(
816 DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));
817 return false;
818 }
819
820 PGOReader = std::move(ReaderOrErr.get());
821 if (!PGOReader) {
822 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
823 "Cannot get PGOReader"));
824 return false;
825 }
Rong Xu33c76c02016-02-10 17:18:30 +0000826 // TODO: might need to change the warning once the clang option is finalized.
827 if (!PGOReader->isIRLevelProfile()) {
828 Ctx.diagnose(DiagnosticInfoPGOProfile(
829 ProfileFileName.data(), "Not an IR level instrumentation profile"));
830 return false;
831 }
832
Rong Xu6090afd2016-03-28 17:08:56 +0000833 std::vector<Function *> HotFunctions;
834 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +0000835 for (auto &F : M) {
836 if (F.isDeclaration())
837 continue;
838 BranchProbabilityInfo *BPI =
839 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
840 BlockFrequencyInfo *BFI =
841 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
842 PGOUseFunc Func(F, &M, BPI, BFI);
843 setPGOCountOnFunc(Func, PGOReader.get());
Rong Xu6090afd2016-03-28 17:08:56 +0000844 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
845 if (FreqAttr == PGOUseFunc::FFA_Cold)
846 ColdFunctions.push_back(&F);
847 else if (FreqAttr == PGOUseFunc::FFA_Hot)
848 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +0000849 }
Rong Xu6090afd2016-03-28 17:08:56 +0000850
851 // Set function hotness attribute from the profile.
852 for (auto &F : HotFunctions) {
853 F->addFnAttr(llvm::Attribute::InlineHint);
854 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
855 << "\n");
856 }
857 for (auto &F : ColdFunctions) {
858 F->addFnAttr(llvm::Attribute::Cold);
859 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
860 }
861
Rong Xuf430ae42015-12-09 18:08:16 +0000862 return true;
863}