blob: 23947137c67e17e5400602808dee13c96e38dbd9 [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) {
336 Instruction *I = CS.getInstruction();
337 CallInst *CI = dyn_cast<CallInst>(I);
338 if (CS.getCalledFunction() || !CS.getCalledValue() ||
339 (CI && CI->isInlineAsm()))
Rong Xued9fec72016-01-21 18:11:44 +0000340 return;
Xinliang David Lia55fd1a2016-03-30 02:16:07 +0000341 IndirectCallInsts.push_back(I);
Rong Xued9fec72016-01-21 18:11:44 +0000342 }
343};
344
345// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000346// Critical edges will be split.
347static void instrumentOneFunc(Function &F, Module *M,
348 BranchProbabilityInfo *BPI,
349 BlockFrequencyInfo *BFI) {
350 unsigned NumCounters = 0;
351 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);
352 for (auto &E : FuncInfo.MST.AllEdges) {
353 if (!E->InMST && !E->Removed)
354 NumCounters++;
355 }
356
357 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000358 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000359 for (auto &E : FuncInfo.MST.AllEdges) {
360 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
361 if (!InstrBB)
362 continue;
363
364 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
365 assert(Builder.GetInsertPoint() != InstrBB->end() &&
366 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000367 Builder.CreateCall(
368 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
369 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
370 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
371 Builder.getInt32(I++)});
372 }
Rong Xued9fec72016-01-21 18:11:44 +0000373
374 if (DisableValueProfiling)
375 return;
376
377 unsigned NumIndirectCallSites = 0;
378 PGOIndirectCallSiteVisitor ICV;
379 ICV.visit(F);
380 for (auto &I : ICV.IndirectCallInsts) {
381 CallSite CS(I);
382 Value *Callee = CS.getCalledValue();
383 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
384 << NumIndirectCallSites << "\n");
385 IRBuilder<> Builder(I);
386 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
387 "Cannot get the Instrumentation point");
388 Builder.CreateCall(
389 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
390 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
391 Builder.getInt64(FuncInfo.FunctionHash),
392 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
393 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
394 Builder.getInt32(NumIndirectCallSites++)});
395 }
396 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000397}
398
399// This class represents a CFG edge in profile use compilation.
400struct PGOUseEdge : public PGOEdge {
401 bool CountValid;
402 uint64_t CountValue;
403 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
404 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
405
406 // Set edge count value
407 void setEdgeCount(uint64_t Value) {
408 CountValue = Value;
409 CountValid = true;
410 }
411
412 // Return the information string for this object.
413 const std::string infoString() const {
414 if (!CountValid)
415 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000416 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
417 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000418 }
419};
420
421typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
422
423// This class stores the auxiliary information for each BB.
424struct UseBBInfo : public BBInfo {
425 uint64_t CountValue;
426 bool CountValid;
427 int32_t UnknownCountInEdge;
428 int32_t UnknownCountOutEdge;
429 DirectEdges InEdges;
430 DirectEdges OutEdges;
431 UseBBInfo(unsigned IX)
432 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
433 UnknownCountOutEdge(0) {}
434 UseBBInfo(unsigned IX, uint64_t C)
435 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
436 UnknownCountOutEdge(0) {}
437
438 // Set the profile count value for this BB.
439 void setBBInfoCount(uint64_t Value) {
440 CountValue = Value;
441 CountValid = true;
442 }
443
444 // Return the information string of this object.
445 const std::string infoString() const {
446 if (!CountValid)
447 return BBInfo::infoString();
448 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
449 }
450};
451
452// Sum up the count values for all the edges.
453static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
454 uint64_t Total = 0;
455 for (auto &E : Edges) {
456 if (E->Removed)
457 continue;
458 Total += E->CountValue;
459 }
460 return Total;
461}
462
463class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000464public:
465 PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr,
466 BlockFrequencyInfo *BFI = nullptr)
467 : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI),
468 FreqAttr(FFA_Normal) {}
469
470 // Read counts for the instrumented BB from profile.
471 bool readCounters(IndexedInstrProfReader *PGOReader);
472
473 // Populate the counts for all BBs.
474 void populateCounters();
475
476 // Set the branch weights based on the count values.
477 void setBranchWeights();
478
479 // Annotate the indirect call sites.
480 void annotateIndirectCallSites();
481
482 // The hotness of the function from the profile count.
483 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
484
485 // Return the funtion hotness from the profile.
486 FuncFreqAttr getFuncFreqAttr() const {
487 return FreqAttr;
488 }
489
Rong Xuf430ae42015-12-09 18:08:16 +0000490private:
491 Function &F;
492 Module *M;
493 // This member stores the shared information with class PGOGenFunc.
494 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
495
496 // Return the auxiliary BB information.
497 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
498 return FuncInfo.getBBInfo(BB);
499 }
500
501 // The maximum count value in the profile. This is only used in PGO use
502 // compilation.
503 uint64_t ProgramMaxCount;
504
Rong Xu13b01dc2016-02-10 18:24:45 +0000505 // ProfileRecord for this function.
506 InstrProfRecord ProfileRecord;
507
Rong Xu6090afd2016-03-28 17:08:56 +0000508 // Function hotness info derived from profile.
509 FuncFreqAttr FreqAttr;
510
Rong Xuf430ae42015-12-09 18:08:16 +0000511 // Find the Instrumented BB and set the value.
512 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
513
514 // Set the edge counter value for the unknown edge -- there should be only
515 // one unknown edge.
516 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
517
518 // Return FuncName string;
519 const std::string getFuncName() const { return FuncInfo.FuncName; }
520
521 // Set the hot/cold inline hints based on the count values.
522 // FIXME: This function should be removed once the functionality in
523 // the inliner is implemented.
Rong Xu6090afd2016-03-28 17:08:56 +0000524 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
Rong Xuf430ae42015-12-09 18:08:16 +0000525 if (ProgramMaxCount == 0)
526 return;
527 // Threshold of the hot functions.
528 const BranchProbability HotFunctionThreshold(1, 100);
529 // Threshold of the cold functions.
530 const BranchProbability ColdFunctionThreshold(2, 10000);
531 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000532 FreqAttr = FFA_Hot;
Rong Xuf430ae42015-12-09 18:08:16 +0000533 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
Rong Xu6090afd2016-03-28 17:08:56 +0000534 FreqAttr = FFA_Cold;
Rong Xuf430ae42015-12-09 18:08:16 +0000535 }
Rong Xuf430ae42015-12-09 18:08:16 +0000536};
537
538// Visit all the edges and assign the count value for the instrumented
539// edges and the BB.
540void PGOUseFunc::setInstrumentedCounts(
541 const std::vector<uint64_t> &CountFromProfile) {
542
543 // Use a worklist as we will update the vector during the iteration.
544 std::vector<PGOUseEdge *> WorkList;
545 for (auto &E : FuncInfo.MST.AllEdges)
546 WorkList.push_back(E.get());
547
548 uint32_t I = 0;
549 for (auto &E : WorkList) {
550 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
551 if (!InstrBB)
552 continue;
553 uint64_t CountValue = CountFromProfile[I++];
554 if (!E->Removed) {
555 getBBInfo(InstrBB).setBBInfoCount(CountValue);
556 E->setEdgeCount(CountValue);
557 continue;
558 }
559
560 // Need to add two new edges.
561 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
562 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
563 // Add new edge of SrcBB->InstrBB.
564 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
565 NewEdge.setEdgeCount(CountValue);
566 // Add new edge of InstrBB->DestBB.
567 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
568 NewEdge1.setEdgeCount(CountValue);
569 NewEdge1.InMST = true;
570 getBBInfo(InstrBB).setBBInfoCount(CountValue);
571 }
572}
573
574// Set the count value for the unknown edge. There should be one and only one
575// unknown edge in Edges vector.
576void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
577 for (auto &E : Edges) {
578 if (E->CountValid)
579 continue;
580 E->setEdgeCount(Value);
581
582 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
583 getBBInfo(E->DestBB).UnknownCountInEdge--;
584 return;
585 }
586 llvm_unreachable("Cannot find the unknown count edge");
587}
588
589// Read the profile from ProfileFileName and assign the value to the
590// instrumented BB and the edges. This function also updates ProgramMaxCount.
591// Return true if the profile are successfully read, and false on errors.
592bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
593 auto &Ctx = M->getContext();
594 ErrorOr<InstrProfRecord> Result =
595 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
596 if (std::error_code EC = Result.getError()) {
597 if (EC == instrprof_error::unknown_function)
598 NumOfPGOMissing++;
599 else if (EC == instrprof_error::hash_mismatch ||
600 EC == llvm::instrprof_error::malformed)
601 NumOfPGOMismatch++;
602
603 std::string Msg = EC.message() + std::string(" ") + F.getName().str();
604 Ctx.diagnose(
605 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
606 return false;
607 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000608 ProfileRecord = std::move(Result.get());
609 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000610
611 NumOfPGOFunc++;
612 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
613 uint64_t ValueSum = 0;
614 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
615 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
616 ValueSum += CountFromProfile[I];
617 }
618
619 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
620
621 getBBInfo(nullptr).UnknownCountOutEdge = 2;
622 getBBInfo(nullptr).UnknownCountInEdge = 2;
623
624 setInstrumentedCounts(CountFromProfile);
625 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
626 return true;
627}
628
629// Populate the counters from instrumented BBs to all BBs.
630// In the end of this operation, all BBs should have a valid count value.
631void PGOUseFunc::populateCounters() {
632 // First set up Count variable for all BBs.
633 for (auto &E : FuncInfo.MST.AllEdges) {
634 if (E->Removed)
635 continue;
636
637 const BasicBlock *SrcBB = E->SrcBB;
638 const BasicBlock *DestBB = E->DestBB;
639 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
640 UseBBInfo &DestInfo = getBBInfo(DestBB);
641 SrcInfo.OutEdges.push_back(E.get());
642 DestInfo.InEdges.push_back(E.get());
643 SrcInfo.UnknownCountOutEdge++;
644 DestInfo.UnknownCountInEdge++;
645
646 if (!E->CountValid)
647 continue;
648 DestInfo.UnknownCountInEdge--;
649 SrcInfo.UnknownCountOutEdge--;
650 }
651
652 bool Changes = true;
653 unsigned NumPasses = 0;
654 while (Changes) {
655 NumPasses++;
656 Changes = false;
657
658 // For efficient traversal, it's better to start from the end as most
659 // of the instrumented edges are at the end.
660 for (auto &BB : reverse(F)) {
661 UseBBInfo &Count = getBBInfo(&BB);
662 if (!Count.CountValid) {
663 if (Count.UnknownCountOutEdge == 0) {
664 Count.CountValue = sumEdgeCount(Count.OutEdges);
665 Count.CountValid = true;
666 Changes = true;
667 } else if (Count.UnknownCountInEdge == 0) {
668 Count.CountValue = sumEdgeCount(Count.InEdges);
669 Count.CountValid = true;
670 Changes = true;
671 }
672 }
673 if (Count.CountValid) {
674 if (Count.UnknownCountOutEdge == 1) {
675 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
676 setEdgeCount(Count.OutEdges, Total);
677 Changes = true;
678 }
679 if (Count.UnknownCountInEdge == 1) {
680 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
681 setEdgeCount(Count.InEdges, Total);
682 Changes = true;
683 }
684 }
685 }
686 }
687
688 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
689 // Assert every BB has a valid counter.
690 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
691 uint64_t FuncMaxCount = FuncEntryCount;
692 for (auto &BB : F) {
693 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
694 uint64_t Count = getBBInfo(&BB).CountValue;
695 if (Count > FuncMaxCount)
696 FuncMaxCount = Count;
697 }
Rong Xu6090afd2016-03-28 17:08:56 +0000698 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000699
700 DEBUG(FuncInfo.dumpInfo("after reading profile."));
701}
702
703// Assign the scaled count values to the BB with multiple out edges.
704void PGOUseFunc::setBranchWeights() {
705 // Generate MD_prof metadata for every branch instruction.
706 DEBUG(dbgs() << "\nSetting branch weights.\n");
707 MDBuilder MDB(M->getContext());
708 for (auto &BB : F) {
709 TerminatorInst *TI = BB.getTerminator();
710 if (TI->getNumSuccessors() < 2)
711 continue;
712 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
713 continue;
714 if (getBBInfo(&BB).CountValue == 0)
715 continue;
716
717 // We have a non-zero Branch BB.
718 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
719 unsigned Size = BBCountInfo.OutEdges.size();
720 SmallVector<unsigned, 2> EdgeCounts(Size, 0);
721 uint64_t MaxCount = 0;
722 for (unsigned s = 0; s < Size; s++) {
723 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
724 const BasicBlock *SrcBB = E->SrcBB;
725 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000726 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000727 continue;
728 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
729 uint64_t EdgeCount = E->CountValue;
730 if (EdgeCount > MaxCount)
731 MaxCount = EdgeCount;
732 EdgeCounts[SuccNum] = EdgeCount;
733 }
734 assert(MaxCount > 0 && "Bad max count");
735 uint64_t Scale = calculateCountScale(MaxCount);
736 SmallVector<unsigned, 4> Weights;
737 for (const auto &ECI : EdgeCounts)
738 Weights.push_back(scaleBranchCount(ECI, Scale));
739
740 TI->setMetadata(llvm::LLVMContext::MD_prof,
741 MDB.createBranchWeights(Weights));
742 DEBUG(dbgs() << "Weight is: ";
743 for (const auto &W : Weights) { dbgs() << W << " "; }
744 dbgs() << "\n";);
745 }
746}
Rong Xu13b01dc2016-02-10 18:24:45 +0000747
748// Traverse all the indirect callsites and annotate the instructions.
749void PGOUseFunc::annotateIndirectCallSites() {
750 if (DisableValueProfiling)
751 return;
752
753 unsigned IndirectCallSiteIndex = 0;
754 PGOIndirectCallSiteVisitor ICV;
755 ICV.visit(F);
Rong Xu9e926e82016-02-29 19:16:04 +0000756 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +0000757 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
758 if (NumValueSites != ICV.IndirectCallInsts.size()) {
759 std::string Msg =
760 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +0000761 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +0000762 auto &Ctx = M->getContext();
763 Ctx.diagnose(
764 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
765 return;
766 }
767
768 for (auto &I : ICV.IndirectCallInsts) {
769 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +0000770 << IndirectCallSiteIndex << " out of " << NumValueSites
771 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +0000772 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +0000773 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +0000774 IndirectCallSiteIndex++;
775 }
776}
Rong Xuf430ae42015-12-09 18:08:16 +0000777} // end anonymous namespace
778
Rong Xu33c76c02016-02-10 17:18:30 +0000779// Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime
780// aware this is an ir_level profile so it can set the version flag.
781static void createIRLevelProfileFlagVariable(Module &M) {
782 Type *IntTy64 = Type::getInt64Ty(M.getContext());
783 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +0000784 auto IRLevelVersionVariable = new GlobalVariable(
785 M, IntTy64, true, GlobalVariable::ExternalLinkage,
786 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
787 INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +0000788 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
789 Triple TT(M.getTargetTriple());
790 if (TT.isOSBinFormatMachO())
791 IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceODRLinkage);
792 else
Rong Xu9e926e82016-02-29 19:16:04 +0000793 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
794 StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +0000795}
796
Rong Xuf430ae42015-12-09 18:08:16 +0000797bool PGOInstrumentationGen::runOnModule(Module &M) {
Rong Xu33c76c02016-02-10 17:18:30 +0000798 createIRLevelProfileFlagVariable(M);
Rong Xuf430ae42015-12-09 18:08:16 +0000799 for (auto &F : M) {
800 if (F.isDeclaration())
801 continue;
802 BranchProbabilityInfo *BPI =
803 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
804 BlockFrequencyInfo *BFI =
805 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
806 instrumentOneFunc(F, &M, BPI, BFI);
807 }
808 return true;
809}
810
811static void setPGOCountOnFunc(PGOUseFunc &Func,
812 IndexedInstrProfReader *PGOReader) {
813 if (Func.readCounters(PGOReader)) {
814 Func.populateCounters();
815 Func.setBranchWeights();
Rong Xu13b01dc2016-02-10 18:24:45 +0000816 Func.annotateIndirectCallSites();
Rong Xuf430ae42015-12-09 18:08:16 +0000817 }
818}
819
820bool PGOInstrumentationUse::runOnModule(Module &M) {
821 DEBUG(dbgs() << "Read in profile counters: ");
822 auto &Ctx = M.getContext();
823 // Read the counter array from file.
824 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
825 if (std::error_code EC = ReaderOrErr.getError()) {
826 Ctx.diagnose(
827 DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));
828 return false;
829 }
830
831 PGOReader = std::move(ReaderOrErr.get());
832 if (!PGOReader) {
833 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
834 "Cannot get PGOReader"));
835 return false;
836 }
Rong Xu33c76c02016-02-10 17:18:30 +0000837 // TODO: might need to change the warning once the clang option is finalized.
838 if (!PGOReader->isIRLevelProfile()) {
839 Ctx.diagnose(DiagnosticInfoPGOProfile(
840 ProfileFileName.data(), "Not an IR level instrumentation profile"));
841 return false;
842 }
843
Rong Xu6090afd2016-03-28 17:08:56 +0000844 std::vector<Function *> HotFunctions;
845 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +0000846 for (auto &F : M) {
847 if (F.isDeclaration())
848 continue;
849 BranchProbabilityInfo *BPI =
850 &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
851 BlockFrequencyInfo *BFI =
852 &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
853 PGOUseFunc Func(F, &M, BPI, BFI);
854 setPGOCountOnFunc(Func, PGOReader.get());
Rong Xu6090afd2016-03-28 17:08:56 +0000855 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
856 if (FreqAttr == PGOUseFunc::FFA_Cold)
857 ColdFunctions.push_back(&F);
858 else if (FreqAttr == PGOUseFunc::FFA_Hot)
859 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +0000860 }
Rong Xu6090afd2016-03-28 17:08:56 +0000861
862 // Set function hotness attribute from the profile.
863 for (auto &F : HotFunctions) {
864 F->addFnAttr(llvm::Attribute::InlineHint);
865 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
866 << "\n");
867 }
868 for (auto &F : ColdFunctions) {
869 F->addFnAttr(llvm::Attribute::Cold);
870 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
871 }
872
Rong Xuf430ae42015-12-09 18:08:16 +0000873 return true;
874}