1 //===-- 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
28 // count profile, and generates the instrumentation for indirect call
29 // profiling.
30 // (2) Pass PGOInstrumentationUse which reads the edge count profile and
31 // annotates the branch weights. It also reads the indirect call value
32 // profiling records and annotate the indirect call instructions.
33 //
34 // 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 
51 #include "CFGMST.h"
52 #include "llvm/ADT/DenseMap.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/Triple.h"
56 #include "llvm/Analysis/BlockFrequencyInfo.h"
57 #include "llvm/Analysis/BranchProbabilityInfo.h"
58 #include "llvm/Analysis/CFG.h"
59 #include "llvm/IR/CallSite.h"
60 #include "llvm/IR/DiagnosticInfo.h"
61 #include "llvm/IR/IRBuilder.h"
62 #include "llvm/IR/InstIterator.h"
63 #include "llvm/IR/InstVisitor.h"
64 #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"
73 #include "llvm/Transforms/Instrumentation.h"
74 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
75 #include <string>
76 #include <utility>
77 #include <vector>
78 
79 using namespace llvm;
80 
81 #define DEBUG_TYPE "pgo-instrumentation"
82 
83 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
84 STATISTIC(NumOfPGOEdge, "Number of edges.");
85 STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
86 STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
87 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
88 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
89 STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
90 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
91 
92 // Command line option to specify the file to read profile from. This is
93 // mainly used for testing.
94 static 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 
100 // Command line option to disable value profiling. The default is false:
101 // i.e. value profiling is enabled by default. This is for debug purpose.
102 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
103                                            cl::Hidden,
104                                            cl::desc("Disable Value Profiling"));
105 
106 // Command line option to set the maximum number of VP annotations to write to
107 // the metada for a single indirect call callsite.
108 static 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 
114 namespace {
115 class PGOInstrumentationGen : public ModulePass {
116 public:
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 
127 private:
128   bool runOnModule(Module &M) override;
129 
130   void getAnalysisUsage(AnalysisUsage &AU) const override {
131     AU.addRequired<BlockFrequencyInfoWrapperPass>();
132   }
133 };
134 
135 class PGOInstrumentationUse : public ModulePass {
136 public:
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 
151 private:
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 
162 char PGOInstrumentationGen::ID = 0;
163 INITIALIZE_PASS_BEGIN(PGOInstrumentationGen, "pgo-instr-gen",
164                       "PGO instrumentation.", false, false)
165 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
166 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
167 INITIALIZE_PASS_END(PGOInstrumentationGen, "pgo-instr-gen",
168                     "PGO instrumentation.", false, false)
169 
170 ModulePass *llvm::createPGOInstrumentationGenPass() {
171   return new PGOInstrumentationGen();
172 }
173 
174 char PGOInstrumentationUse::ID = 0;
175 INITIALIZE_PASS_BEGIN(PGOInstrumentationUse, "pgo-instr-use",
176                       "Read PGO instrumentation profile.", false, false)
177 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
178 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
179 INITIALIZE_PASS_END(PGOInstrumentationUse, "pgo-instr-use",
180                     "Read PGO instrumentation profile.", false, false)
181 
182 ModulePass *llvm::createPGOInstrumentationUsePass(StringRef Filename) {
183   return new PGOInstrumentationUse(Filename.str());
184 }
185 
186 namespace {
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.
191 struct 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.
211 struct 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.
225 template <class Edge, class BBInfo> class FuncPGOInstrumentation {
226 private:
227   Function &F;
228   void computeCFGHash();
229 
230 public:
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: " +
249                               Twine(FunctionHash) + "\t" + Str);
250   }
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);
271   }
272 };
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.
276 template <class Edge, class BBInfo>
277 void 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.
295 template <class Edge, class BBInfo>
296 BasicBlock *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 
329 // Visitor class that finds all indirect call sites.
330 struct PGOIndirectCallSiteVisitor
331     : public InstVisitor<PGOIndirectCallSiteVisitor> {
332   std::vector<CallInst *> IndirectCallInsts;
333   PGOIndirectCallSiteVisitor() {}
334 
335   void visitCallInst(CallInst &I) {
336     CallSite CS(&I);
337     if (CS.getCalledFunction() || !CS.getCalledValue() || I.isInlineAsm())
338       return;
339     IndirectCallInsts.push_back(&I);
340   }
341 };
342 
343 // Visit all edge and instrument the edges not in MST, and do value profiling.
344 // Critical edges will be split.
345 static void instrumentOneFunc(Function &F, Module *M,
346                               BranchProbabilityInfo *BPI,
347                               BlockFrequencyInfo *BFI) {
348   unsigned NumCounters = 0;
349   FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);
350   for (auto &E : FuncInfo.MST.AllEdges) {
351     if (!E->InMST && !E->Removed)
352       NumCounters++;
353   }
354 
355   uint32_t I = 0;
356   Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
357   for (auto &E : FuncInfo.MST.AllEdges) {
358     BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
359     if (!InstrBB)
360       continue;
361 
362     IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
363     assert(Builder.GetInsertPoint() != InstrBB->end() &&
364            "Cannot get the Instrumentation point");
365     Builder.CreateCall(
366         Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
367         {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
368          Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
369          Builder.getInt32(I++)});
370   }
371 
372   if (DisableValueProfiling)
373     return;
374 
375   unsigned NumIndirectCallSites = 0;
376   PGOIndirectCallSiteVisitor ICV;
377   ICV.visit(F);
378   for (auto &I : ICV.IndirectCallInsts) {
379     CallSite CS(I);
380     Value *Callee = CS.getCalledValue();
381     DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
382                  << NumIndirectCallSites << "\n");
383     IRBuilder<> Builder(I);
384     assert(Builder.GetInsertPoint() != I->getParent()->end() &&
385            "Cannot get the Instrumentation point");
386     Builder.CreateCall(
387         Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
388         {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
389          Builder.getInt64(FuncInfo.FunctionHash),
390          Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
391          Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
392          Builder.getInt32(NumIndirectCallSites++)});
393   }
394   NumOfPGOICall += NumIndirectCallSites;
395 }
396 
397 // This class represents a CFG edge in profile use compilation.
398 struct PGOUseEdge : public PGOEdge {
399   bool CountValid;
400   uint64_t CountValue;
401   PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
402       : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
403 
404   // Set edge count value
405   void setEdgeCount(uint64_t Value) {
406     CountValue = Value;
407     CountValid = true;
408   }
409 
410   // Return the information string for this object.
411   const std::string infoString() const {
412     if (!CountValid)
413       return PGOEdge::infoString();
414     return (Twine(PGOEdge::infoString()) + "  Count=" + Twine(CountValue))
415         .str();
416   }
417 };
418 
419 typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
420 
421 // This class stores the auxiliary information for each BB.
422 struct UseBBInfo : public BBInfo {
423   uint64_t CountValue;
424   bool CountValid;
425   int32_t UnknownCountInEdge;
426   int32_t UnknownCountOutEdge;
427   DirectEdges InEdges;
428   DirectEdges OutEdges;
429   UseBBInfo(unsigned IX)
430       : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
431         UnknownCountOutEdge(0) {}
432   UseBBInfo(unsigned IX, uint64_t C)
433       : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
434         UnknownCountOutEdge(0) {}
435 
436   // Set the profile count value for this BB.
437   void setBBInfoCount(uint64_t Value) {
438     CountValue = Value;
439     CountValid = true;
440   }
441 
442   // Return the information string of this object.
443   const std::string infoString() const {
444     if (!CountValid)
445       return BBInfo::infoString();
446     return (Twine(BBInfo::infoString()) + "  Count=" + Twine(CountValue)).str();
447   }
448 };
449 
450 // Sum up the count values for all the edges.
451 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
452   uint64_t Total = 0;
453   for (auto &E : Edges) {
454     if (E->Removed)
455       continue;
456     Total += E->CountValue;
457   }
458   return Total;
459 }
460 
461 class PGOUseFunc {
462 private:
463   Function &F;
464   Module *M;
465   // This member stores the shared information with class PGOGenFunc.
466   FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
467 
468   // Return the auxiliary BB information.
469   UseBBInfo &getBBInfo(const BasicBlock *BB) const {
470     return FuncInfo.getBBInfo(BB);
471   }
472 
473   // The maximum count value in the profile. This is only used in PGO use
474   // compilation.
475   uint64_t ProgramMaxCount;
476 
477   // ProfileRecord for this function.
478   InstrProfRecord ProfileRecord;
479 
480   // Find the Instrumented BB and set the value.
481   void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
482 
483   // Set the edge counter value for the unknown edge -- there should be only
484   // one unknown edge.
485   void setEdgeCount(DirectEdges &Edges, uint64_t Value);
486 
487   // Return FuncName string;
488   const std::string getFuncName() const { return FuncInfo.FuncName; }
489 
490   // Set the hot/cold inline hints based on the count values.
491   // FIXME: This function should be removed once the functionality in
492   // the inliner is implemented.
493   void applyFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
494     if (ProgramMaxCount == 0)
495       return;
496     // Threshold of the hot functions.
497     const BranchProbability HotFunctionThreshold(1, 100);
498     // Threshold of the cold functions.
499     const BranchProbability ColdFunctionThreshold(2, 10000);
500     if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
501       F.addFnAttr(llvm::Attribute::InlineHint);
502     else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
503       F.addFnAttr(llvm::Attribute::Cold);
504   }
505 
506 public:
507   PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr,
508              BlockFrequencyInfo *BFI = nullptr)
509       : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI) {}
510 
511   // Read counts for the instrumented BB from profile.
512   bool readCounters(IndexedInstrProfReader *PGOReader);
513 
514   // Populate the counts for all BBs.
515   void populateCounters();
516 
517   // Set the branch weights based on the count values.
518   void setBranchWeights();
519 
520   // Annotate the indirect call sites.
521   void annotateIndirectCallSites();
522 };
523 
524 // Visit all the edges and assign the count value for the instrumented
525 // edges and the BB.
526 void PGOUseFunc::setInstrumentedCounts(
527     const std::vector<uint64_t> &CountFromProfile) {
528 
529   // Use a worklist as we will update the vector during the iteration.
530   std::vector<PGOUseEdge *> WorkList;
531   for (auto &E : FuncInfo.MST.AllEdges)
532     WorkList.push_back(E.get());
533 
534   uint32_t I = 0;
535   for (auto &E : WorkList) {
536     BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
537     if (!InstrBB)
538       continue;
539     uint64_t CountValue = CountFromProfile[I++];
540     if (!E->Removed) {
541       getBBInfo(InstrBB).setBBInfoCount(CountValue);
542       E->setEdgeCount(CountValue);
543       continue;
544     }
545 
546     // Need to add two new edges.
547     BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
548     BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
549     // Add new edge of SrcBB->InstrBB.
550     PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
551     NewEdge.setEdgeCount(CountValue);
552     // Add new edge of InstrBB->DestBB.
553     PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
554     NewEdge1.setEdgeCount(CountValue);
555     NewEdge1.InMST = true;
556     getBBInfo(InstrBB).setBBInfoCount(CountValue);
557   }
558 }
559 
560 // Set the count value for the unknown edge. There should be one and only one
561 // unknown edge in Edges vector.
562 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
563   for (auto &E : Edges) {
564     if (E->CountValid)
565       continue;
566     E->setEdgeCount(Value);
567 
568     getBBInfo(E->SrcBB).UnknownCountOutEdge--;
569     getBBInfo(E->DestBB).UnknownCountInEdge--;
570     return;
571   }
572   llvm_unreachable("Cannot find the unknown count edge");
573 }
574 
575 // Read the profile from ProfileFileName and assign the value to the
576 // instrumented BB and the edges. This function also updates ProgramMaxCount.
577 // Return true if the profile are successfully read, and false on errors.
578 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
579   auto &Ctx = M->getContext();
580   ErrorOr<InstrProfRecord> Result =
581       PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
582   if (std::error_code EC = Result.getError()) {
583     if (EC == instrprof_error::unknown_function)
584       NumOfPGOMissing++;
585     else if (EC == instrprof_error::hash_mismatch ||
586              EC == llvm::instrprof_error::malformed)
587       NumOfPGOMismatch++;
588 
589     std::string Msg = EC.message() + std::string(" ") + F.getName().str();
590     Ctx.diagnose(
591         DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
592     return false;
593   }
594   ProfileRecord = std::move(Result.get());
595   std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
596 
597   NumOfPGOFunc++;
598   DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
599   uint64_t ValueSum = 0;
600   for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
601     DEBUG(dbgs() << "  " << I << ": " << CountFromProfile[I] << "\n");
602     ValueSum += CountFromProfile[I];
603   }
604 
605   DEBUG(dbgs() << "SUM =  " << ValueSum << "\n");
606 
607   getBBInfo(nullptr).UnknownCountOutEdge = 2;
608   getBBInfo(nullptr).UnknownCountInEdge = 2;
609 
610   setInstrumentedCounts(CountFromProfile);
611   ProgramMaxCount = PGOReader->getMaximumFunctionCount();
612   return true;
613 }
614 
615 // Populate the counters from instrumented BBs to all BBs.
616 // In the end of this operation, all BBs should have a valid count value.
617 void PGOUseFunc::populateCounters() {
618   // First set up Count variable for all BBs.
619   for (auto &E : FuncInfo.MST.AllEdges) {
620     if (E->Removed)
621       continue;
622 
623     const BasicBlock *SrcBB = E->SrcBB;
624     const BasicBlock *DestBB = E->DestBB;
625     UseBBInfo &SrcInfo = getBBInfo(SrcBB);
626     UseBBInfo &DestInfo = getBBInfo(DestBB);
627     SrcInfo.OutEdges.push_back(E.get());
628     DestInfo.InEdges.push_back(E.get());
629     SrcInfo.UnknownCountOutEdge++;
630     DestInfo.UnknownCountInEdge++;
631 
632     if (!E->CountValid)
633       continue;
634     DestInfo.UnknownCountInEdge--;
635     SrcInfo.UnknownCountOutEdge--;
636   }
637 
638   bool Changes = true;
639   unsigned NumPasses = 0;
640   while (Changes) {
641     NumPasses++;
642     Changes = false;
643 
644     // For efficient traversal, it's better to start from the end as most
645     // of the instrumented edges are at the end.
646     for (auto &BB : reverse(F)) {
647       UseBBInfo &Count = getBBInfo(&BB);
648       if (!Count.CountValid) {
649         if (Count.UnknownCountOutEdge == 0) {
650           Count.CountValue = sumEdgeCount(Count.OutEdges);
651           Count.CountValid = true;
652           Changes = true;
653         } else if (Count.UnknownCountInEdge == 0) {
654           Count.CountValue = sumEdgeCount(Count.InEdges);
655           Count.CountValid = true;
656           Changes = true;
657         }
658       }
659       if (Count.CountValid) {
660         if (Count.UnknownCountOutEdge == 1) {
661           uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
662           setEdgeCount(Count.OutEdges, Total);
663           Changes = true;
664         }
665         if (Count.UnknownCountInEdge == 1) {
666           uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
667           setEdgeCount(Count.InEdges, Total);
668           Changes = true;
669         }
670       }
671     }
672   }
673 
674   DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
675   // Assert every BB has a valid counter.
676   uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
677   uint64_t FuncMaxCount = FuncEntryCount;
678   for (auto &BB : F) {
679     assert(getBBInfo(&BB).CountValid && "BB count is not valid");
680     uint64_t Count = getBBInfo(&BB).CountValue;
681     if (Count > FuncMaxCount)
682       FuncMaxCount = Count;
683   }
684   applyFunctionAttributes(FuncEntryCount, FuncMaxCount);
685 
686   DEBUG(FuncInfo.dumpInfo("after reading profile."));
687 }
688 
689 // Assign the scaled count values to the BB with multiple out edges.
690 void PGOUseFunc::setBranchWeights() {
691   // Generate MD_prof metadata for every branch instruction.
692   DEBUG(dbgs() << "\nSetting branch weights.\n");
693   MDBuilder MDB(M->getContext());
694   for (auto &BB : F) {
695     TerminatorInst *TI = BB.getTerminator();
696     if (TI->getNumSuccessors() < 2)
697       continue;
698     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
699       continue;
700     if (getBBInfo(&BB).CountValue == 0)
701       continue;
702 
703     // We have a non-zero Branch BB.
704     const UseBBInfo &BBCountInfo = getBBInfo(&BB);
705     unsigned Size = BBCountInfo.OutEdges.size();
706     SmallVector<unsigned, 2> EdgeCounts(Size, 0);
707     uint64_t MaxCount = 0;
708     for (unsigned s = 0; s < Size; s++) {
709       const PGOUseEdge *E = BBCountInfo.OutEdges[s];
710       const BasicBlock *SrcBB = E->SrcBB;
711       const BasicBlock *DestBB = E->DestBB;
712       if (DestBB == nullptr)
713         continue;
714       unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
715       uint64_t EdgeCount = E->CountValue;
716       if (EdgeCount > MaxCount)
717         MaxCount = EdgeCount;
718       EdgeCounts[SuccNum] = EdgeCount;
719     }
720     assert(MaxCount > 0 && "Bad max count");
721     uint64_t Scale = calculateCountScale(MaxCount);
722     SmallVector<unsigned, 4> Weights;
723     for (const auto &ECI : EdgeCounts)
724       Weights.push_back(scaleBranchCount(ECI, Scale));
725 
726     TI->setMetadata(llvm::LLVMContext::MD_prof,
727                     MDB.createBranchWeights(Weights));
728     DEBUG(dbgs() << "Weight is: ";
729           for (const auto &W : Weights) { dbgs() << W << " "; }
730           dbgs() << "\n";);
731   }
732 }
733 
734 // Traverse all the indirect callsites and annotate the instructions.
735 void PGOUseFunc::annotateIndirectCallSites() {
736   if (DisableValueProfiling)
737     return;
738 
739   unsigned IndirectCallSiteIndex = 0;
740   PGOIndirectCallSiteVisitor ICV;
741   ICV.visit(F);
742   unsigned NumValueSites =
743       ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
744   if (NumValueSites != ICV.IndirectCallInsts.size()) {
745     std::string Msg =
746         std::string("Inconsistent number of indirect call sites: ") +
747         F.getName().str();
748     auto &Ctx = M->getContext();
749     Ctx.diagnose(
750         DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
751     return;
752   }
753 
754   for (auto &I : ICV.IndirectCallInsts) {
755     DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
756                  << IndirectCallSiteIndex << " out of " << NumValueSites
757                  << "\n");
758     annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
759                       IndirectCallSiteIndex, MaxNumAnnotations);
760     IndirectCallSiteIndex++;
761   }
762 }
763 } // end anonymous namespace
764 
765 // Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime
766 // aware this is an ir_level profile so it can set the version flag.
767 static void createIRLevelProfileFlagVariable(Module &M) {
768   Type *IntTy64 = Type::getInt64Ty(M.getContext());
769   uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
770   auto IRLevelVersionVariable = new GlobalVariable(
771       M, IntTy64, true, GlobalVariable::ExternalLinkage,
772       Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
773       INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR));
774   IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
775   Triple TT(M.getTargetTriple());
776   if (TT.isOSBinFormatMachO())
777     IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceODRLinkage);
778   else
779     IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
780         StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR))));
781 }
782 
783 bool PGOInstrumentationGen::runOnModule(Module &M) {
784   createIRLevelProfileFlagVariable(M);
785   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 
797 static void setPGOCountOnFunc(PGOUseFunc &Func,
798                               IndexedInstrProfReader *PGOReader) {
799   if (Func.readCounters(PGOReader)) {
800     Func.populateCounters();
801     Func.setBranchWeights();
802     Func.annotateIndirectCallSites();
803   }
804 }
805 
806 bool PGOInstrumentationUse::runOnModule(Module &M) {
807   DEBUG(dbgs() << "Read in profile counters: ");
808   auto &Ctx = M.getContext();
809   // Read the counter array from file.
810   auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
811   if (std::error_code EC = ReaderOrErr.getError()) {
812     Ctx.diagnose(
813         DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));
814     return false;
815   }
816 
817   PGOReader = std::move(ReaderOrErr.get());
818   if (!PGOReader) {
819     Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
820                                           "Cannot get PGOReader"));
821     return false;
822   }
823   // TODO: might need to change the warning once the clang option is finalized.
824   if (!PGOReader->isIRLevelProfile()) {
825     Ctx.diagnose(DiagnosticInfoPGOProfile(
826         ProfileFileName.data(), "Not an IR level instrumentation profile"));
827     return false;
828   }
829 
830   for (auto &F : M) {
831     if (F.isDeclaration())
832       continue;
833     BranchProbabilityInfo *BPI =
834         &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());
835     BlockFrequencyInfo *BFI =
836         &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());
837     PGOUseFunc Func(F, &M, BPI, BFI);
838     setPGOCountOnFunc(Func, PGOReader.get());
839   }
840   return true;
841 }
842