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 "llvm/Transforms/PGOInstrumentation.h"
52 #include "CFGMST.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/Triple.h"
57 #include "llvm/Analysis/BlockFrequencyInfo.h"
58 #include "llvm/Analysis/BranchProbabilityInfo.h"
59 #include "llvm/Analysis/CFG.h"
60 #include "llvm/Analysis/IndirectCallSiteVisitor.h"
61 #include "llvm/Analysis/LoopInfo.h"
62 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
63 #include "llvm/IR/CallSite.h"
64 #include "llvm/IR/DiagnosticInfo.h"
65 #include "llvm/IR/Dominators.h"
66 #include "llvm/IR/GlobalValue.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/InstIterator.h"
69 #include "llvm/IR/Instructions.h"
70 #include "llvm/IR/IntrinsicInst.h"
71 #include "llvm/IR/MDBuilder.h"
72 #include "llvm/IR/Module.h"
73 #include "llvm/Pass.h"
74 #include "llvm/ProfileData/InstrProfReader.h"
75 #include "llvm/ProfileData/ProfileCommon.h"
76 #include "llvm/Support/BranchProbability.h"
77 #include "llvm/Support/DOTGraphTraits.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Support/GraphWriter.h"
80 #include "llvm/Support/JamCRC.h"
81 #include "llvm/Transforms/Instrumentation.h"
82 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
83 #include <algorithm>
84 #include <string>
85 #include <unordered_map>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "pgo-instrumentation"
92 
93 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
94 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
95 STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
96 STATISTIC(NumOfPGOEdge, "Number of edges.");
97 STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
98 STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
99 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
100 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
101 STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
102 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
103 
104 // Command line option to specify the file to read profile from. This is
105 // mainly used for testing.
106 static cl::opt<std::string>
107     PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
108                        cl::value_desc("filename"),
109                        cl::desc("Specify the path of profile data file. This is"
110                                 "mainly for test purpose."));
111 
112 // Command line option to disable value profiling. The default is false:
113 // i.e. value profiling is enabled by default. This is for debug purpose.
114 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
115                                            cl::Hidden,
116                                            cl::desc("Disable Value Profiling"));
117 
118 // Command line option to set the maximum number of VP annotations to write to
119 // the metadata for a single indirect call callsite.
120 static cl::opt<unsigned> MaxNumAnnotations(
121     "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
122     cl::desc("Max number of annotations for a single indirect "
123              "call callsite"));
124 
125 // Command line option to set the maximum number of value annotations
126 // to write to the metadata for a single memop intrinsic.
127 static cl::opt<unsigned> MaxNumMemOPAnnotations(
128     "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
129     cl::desc("Max number of preicise value annotations for a single memop"
130              "intrinsic"));
131 
132 // Command line option to control appending FunctionHash to the name of a COMDAT
133 // function. This is to avoid the hash mismatch caused by the preinliner.
134 static cl::opt<bool> DoComdatRenaming(
135     "do-comdat-renaming", cl::init(false), cl::Hidden,
136     cl::desc("Append function hash to the name of COMDAT function to avoid "
137              "function hash mismatch due to the preinliner"));
138 
139 // Command line option to enable/disable the warning about missing profile
140 // information.
141 static cl::opt<bool>
142     PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
143                    cl::desc("Use this option to turn on/off "
144                             "warnings about missing profile data for "
145                             "functions."));
146 
147 // Command line option to enable/disable the warning about a hash mismatch in
148 // the profile data.
149 static cl::opt<bool>
150     NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
151                       cl::desc("Use this option to turn off/on "
152                                "warnings about profile cfg mismatch."));
153 
154 // Command line option to enable/disable the warning about a hash mismatch in
155 // the profile data for Comdat functions, which often turns out to be false
156 // positive due to the pre-instrumentation inline.
157 static cl::opt<bool>
158     NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
159                             cl::Hidden,
160                             cl::desc("The option is used to turn on/off "
161                                      "warnings about hash mismatch for comdat "
162                                      "functions."));
163 
164 // Command line option to enable/disable select instruction instrumentation.
165 static cl::opt<bool>
166     PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
167                    cl::desc("Use this option to turn on/off SELECT "
168                             "instruction instrumentation. "));
169 
170 // Command line option to turn on CFG dot dump of raw profile counts
171 static cl::opt<bool>
172     PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden,
173                      cl::desc("A boolean option to show CFG dag "
174                               "with raw profile counts from "
175                               "profile data. See also option "
176                               "-pgo-view-counts. To limit graph "
177                               "display to only one function, use "
178                               "filtering option -view-bfi-func-name."));
179 
180 // Command line option to enable/disable memop intrinsic call.size profiling.
181 static cl::opt<bool>
182     PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
183                   cl::desc("Use this option to turn on/off "
184                            "memory intrinsic size profiling."));
185 
186 // Emit branch probability as optimization remarks.
187 static cl::opt<bool>
188     EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
189                           cl::desc("When this option is on, the annotated "
190                                    "branch probability will be emitted as "
191                                    " optimization remarks: -Rpass-analysis="
192                                    "pgo-instr-use"));
193 
194 // Command line option to turn on CFG dot dump after profile annotation.
195 // Defined in Analysis/BlockFrequencyInfo.cpp:  -pgo-view-counts
196 extern cl::opt<bool> PGOViewCounts;
197 
198 // Command line option to specify the name of the function for CFG dump
199 // Defined in Analysis/BlockFrequencyInfo.cpp:  -view-bfi-func-name=
200 extern cl::opt<std::string> ViewBlockFreqFuncName;
201 
202 namespace {
203 
204 // Return a string describing the branch condition that can be
205 // used in static branch probability heuristics:
206 std::string getBranchCondString(Instruction *TI) {
207   BranchInst *BI = dyn_cast<BranchInst>(TI);
208   if (!BI || !BI->isConditional())
209     return std::string();
210 
211   Value *Cond = BI->getCondition();
212   ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
213   if (!CI)
214     return std::string();
215 
216   std::string result;
217   raw_string_ostream OS(result);
218   OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
219   CI->getOperand(0)->getType()->print(OS, true);
220 
221   Value *RHS = CI->getOperand(1);
222   ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
223   if (CV) {
224     if (CV->isZero())
225       OS << "_Zero";
226     else if (CV->isOne())
227       OS << "_One";
228     else if (CV->isMinusOne())
229       OS << "_MinusOne";
230     else
231       OS << "_Const";
232   }
233   OS.flush();
234   return result;
235 }
236 
237 /// The select instruction visitor plays three roles specified
238 /// by the mode. In \c VM_counting mode, it simply counts the number of
239 /// select instructions. In \c VM_instrument mode, it inserts code to count
240 /// the number times TrueValue of select is taken. In \c VM_annotate mode,
241 /// it reads the profile data and annotate the select instruction with metadata.
242 enum VisitMode { VM_counting, VM_instrument, VM_annotate };
243 class PGOUseFunc;
244 
245 /// Instruction Visitor class to visit select instructions.
246 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
247   Function &F;
248   unsigned NSIs = 0;             // Number of select instructions instrumented.
249   VisitMode Mode = VM_counting;  // Visiting mode.
250   unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
251   unsigned TotalNumCtrs = 0;     // Total number of counters
252   GlobalVariable *FuncNameVar = nullptr;
253   uint64_t FuncHash = 0;
254   PGOUseFunc *UseFunc = nullptr;
255 
256   SelectInstVisitor(Function &Func) : F(Func) {}
257 
258   void countSelects(Function &Func) {
259     NSIs = 0;
260     Mode = VM_counting;
261     visit(Func);
262   }
263   // Visit the IR stream and instrument all select instructions. \p
264   // Ind is a pointer to the counter index variable; \p TotalNC
265   // is the total number of counters; \p FNV is the pointer to the
266   // PGO function name var; \p FHash is the function hash.
267   void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
268                          GlobalVariable *FNV, uint64_t FHash) {
269     Mode = VM_instrument;
270     CurCtrIdx = Ind;
271     TotalNumCtrs = TotalNC;
272     FuncHash = FHash;
273     FuncNameVar = FNV;
274     visit(Func);
275   }
276 
277   // Visit the IR stream and annotate all select instructions.
278   void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
279     Mode = VM_annotate;
280     UseFunc = UF;
281     CurCtrIdx = Ind;
282     visit(Func);
283   }
284 
285   void instrumentOneSelectInst(SelectInst &SI);
286   void annotateOneSelectInst(SelectInst &SI);
287   // Visit \p SI instruction and perform tasks according to visit mode.
288   void visitSelectInst(SelectInst &SI);
289   // Return the number of select instructions. This needs be called after
290   // countSelects().
291   unsigned getNumOfSelectInsts() const { return NSIs; }
292 };
293 
294 /// Instruction Visitor class to visit memory intrinsic calls.
295 struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
296   Function &F;
297   unsigned NMemIs = 0;          // Number of memIntrinsics instrumented.
298   VisitMode Mode = VM_counting; // Visiting mode.
299   unsigned CurCtrId = 0;        // Current counter index.
300   unsigned TotalNumCtrs = 0;    // Total number of counters
301   GlobalVariable *FuncNameVar = nullptr;
302   uint64_t FuncHash = 0;
303   PGOUseFunc *UseFunc = nullptr;
304   std::vector<Instruction *> Candidates;
305 
306   MemIntrinsicVisitor(Function &Func) : F(Func) {}
307 
308   void countMemIntrinsics(Function &Func) {
309     NMemIs = 0;
310     Mode = VM_counting;
311     visit(Func);
312   }
313 
314   void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
315                                GlobalVariable *FNV, uint64_t FHash) {
316     Mode = VM_instrument;
317     TotalNumCtrs = TotalNC;
318     FuncHash = FHash;
319     FuncNameVar = FNV;
320     visit(Func);
321   }
322 
323   std::vector<Instruction *> findMemIntrinsics(Function &Func) {
324     Candidates.clear();
325     Mode = VM_annotate;
326     visit(Func);
327     return Candidates;
328   }
329 
330   // Visit the IR stream and annotate all mem intrinsic call instructions.
331   void instrumentOneMemIntrinsic(MemIntrinsic &MI);
332   // Visit \p MI instruction and perform tasks according to visit mode.
333   void visitMemIntrinsic(MemIntrinsic &SI);
334   unsigned getNumOfMemIntrinsics() const { return NMemIs; }
335 };
336 
337 class PGOInstrumentationGenLegacyPass : public ModulePass {
338 public:
339   static char ID;
340 
341   PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
342     initializePGOInstrumentationGenLegacyPassPass(
343         *PassRegistry::getPassRegistry());
344   }
345 
346   StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
347 
348 private:
349   bool runOnModule(Module &M) override;
350 
351   void getAnalysisUsage(AnalysisUsage &AU) const override {
352     AU.addRequired<BlockFrequencyInfoWrapperPass>();
353   }
354 };
355 
356 class PGOInstrumentationUseLegacyPass : public ModulePass {
357 public:
358   static char ID;
359 
360   // Provide the profile filename as the parameter.
361   PGOInstrumentationUseLegacyPass(std::string Filename = "")
362       : ModulePass(ID), ProfileFileName(std::move(Filename)) {
363     if (!PGOTestProfileFile.empty())
364       ProfileFileName = PGOTestProfileFile;
365     initializePGOInstrumentationUseLegacyPassPass(
366         *PassRegistry::getPassRegistry());
367   }
368 
369   StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
370 
371 private:
372   std::string ProfileFileName;
373 
374   bool runOnModule(Module &M) override;
375   void getAnalysisUsage(AnalysisUsage &AU) const override {
376     AU.addRequired<BlockFrequencyInfoWrapperPass>();
377   }
378 };
379 
380 } // end anonymous namespace
381 
382 char PGOInstrumentationGenLegacyPass::ID = 0;
383 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
384                       "PGO instrumentation.", false, false)
385 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
386 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
387 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
388                     "PGO instrumentation.", false, false)
389 
390 ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
391   return new PGOInstrumentationGenLegacyPass();
392 }
393 
394 char PGOInstrumentationUseLegacyPass::ID = 0;
395 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
396                       "Read PGO instrumentation profile.", false, false)
397 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
398 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
399 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
400                     "Read PGO instrumentation profile.", false, false)
401 
402 ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
403   return new PGOInstrumentationUseLegacyPass(Filename.str());
404 }
405 
406 namespace {
407 /// \brief An MST based instrumentation for PGO
408 ///
409 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
410 /// in the function level.
411 struct PGOEdge {
412   // This class implements the CFG edges. Note the CFG can be a multi-graph.
413   // So there might be multiple edges with same SrcBB and DestBB.
414   const BasicBlock *SrcBB;
415   const BasicBlock *DestBB;
416   uint64_t Weight;
417   bool InMST;
418   bool Removed;
419   bool IsCritical;
420   PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
421       : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
422         IsCritical(false) {}
423   // Return the information string of an edge.
424   const std::string infoString() const {
425     return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
426             (IsCritical ? "c" : " ") + "  W=" + Twine(Weight)).str();
427   }
428 };
429 
430 // This class stores the auxiliary information for each BB.
431 struct BBInfo {
432   BBInfo *Group;
433   uint32_t Index;
434   uint32_t Rank;
435 
436   BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
437 
438   // Return the information string of this object.
439   const std::string infoString() const {
440     return (Twine("Index=") + Twine(Index)).str();
441   }
442 };
443 
444 // This class implements the CFG edges. Note the CFG can be a multi-graph.
445 template <class Edge, class BBInfo> class FuncPGOInstrumentation {
446 private:
447   Function &F;
448   void computeCFGHash();
449   void renameComdatFunction();
450   // A map that stores the Comdat group in function F.
451   std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
452 
453 public:
454   std::vector<std::vector<Instruction *>> ValueSites;
455   SelectInstVisitor SIVisitor;
456   MemIntrinsicVisitor MIVisitor;
457   std::string FuncName;
458   GlobalVariable *FuncNameVar;
459   // CFG hash value for this function.
460   uint64_t FunctionHash;
461 
462   // The Minimum Spanning Tree of function CFG.
463   CFGMST<Edge, BBInfo> MST;
464 
465   // Give an edge, find the BB that will be instrumented.
466   // Return nullptr if there is no BB to be instrumented.
467   BasicBlock *getInstrBB(Edge *E);
468 
469   // Return the auxiliary BB information.
470   BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
471 
472   // Return the auxiliary BB information if available.
473   BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
474 
475   // Dump edges and BB information.
476   void dumpInfo(std::string Str = "") const {
477     MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
478                               Twine(FunctionHash) + "\t" + Str);
479   }
480 
481   FuncPGOInstrumentation(
482       Function &Func,
483       std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
484       bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
485       BlockFrequencyInfo *BFI = nullptr)
486       : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
487         SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) {
488 
489     // This should be done before CFG hash computation.
490     SIVisitor.countSelects(Func);
491     MIVisitor.countMemIntrinsics(Func);
492     NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
493     NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
494     ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
495     ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
496 
497     FuncName = getPGOFuncName(F);
498     computeCFGHash();
499     if (ComdatMembers.size())
500       renameComdatFunction();
501     DEBUG(dumpInfo("after CFGMST"));
502 
503     NumOfPGOBB += MST.BBInfos.size();
504     for (auto &E : MST.AllEdges) {
505       if (E->Removed)
506         continue;
507       NumOfPGOEdge++;
508       if (!E->InMST)
509         NumOfPGOInstrument++;
510     }
511 
512     if (CreateGlobalVar)
513       FuncNameVar = createPGOFuncNameVar(F, FuncName);
514   }
515 
516   // Return the number of profile counters needed for the function.
517   unsigned getNumCounters() {
518     unsigned NumCounters = 0;
519     for (auto &E : this->MST.AllEdges) {
520       if (!E->InMST && !E->Removed)
521         NumCounters++;
522     }
523     return NumCounters + SIVisitor.getNumOfSelectInsts();
524   }
525 };
526 
527 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
528 // value of each BB in the CFG. The higher 32 bits record the number of edges.
529 template <class Edge, class BBInfo>
530 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
531   std::vector<char> Indexes;
532   JamCRC JC;
533   for (auto &BB : F) {
534     const TerminatorInst *TI = BB.getTerminator();
535     for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
536       BasicBlock *Succ = TI->getSuccessor(I);
537       auto BI = findBBInfo(Succ);
538       if (BI == nullptr)
539         continue;
540       uint32_t Index = BI->Index;
541       for (int J = 0; J < 4; J++)
542         Indexes.push_back((char)(Index >> (J * 8)));
543     }
544   }
545   JC.update(Indexes);
546   FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
547                  (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
548                  (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
549   DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
550                << " CRC = " << JC.getCRC()
551                << ", Selects = " << SIVisitor.getNumOfSelectInsts()
552                << ", Edges = " << MST.AllEdges.size()
553                << ", ICSites = " << ValueSites[IPVK_IndirectCallTarget].size()
554                << ", Hash = " << FunctionHash << "\n";);
555 }
556 
557 // Check if we can safely rename this Comdat function.
558 static bool canRenameComdat(
559     Function &F,
560     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
561   if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
562     return false;
563 
564   // FIXME: Current only handle those Comdat groups that only containing one
565   // function and function aliases.
566   // (1) For a Comdat group containing multiple functions, we need to have a
567   // unique postfix based on the hashes for each function. There is a
568   // non-trivial code refactoring to do this efficiently.
569   // (2) Variables can not be renamed, so we can not rename Comdat function in a
570   // group including global vars.
571   Comdat *C = F.getComdat();
572   for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
573     if (dyn_cast<GlobalAlias>(CM.second))
574       continue;
575     Function *FM = dyn_cast<Function>(CM.second);
576     if (FM != &F)
577       return false;
578   }
579   return true;
580 }
581 
582 // Append the CFGHash to the Comdat function name.
583 template <class Edge, class BBInfo>
584 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
585   if (!canRenameComdat(F, ComdatMembers))
586     return;
587   std::string OrigName = F.getName().str();
588   std::string NewFuncName =
589       Twine(F.getName() + "." + Twine(FunctionHash)).str();
590   F.setName(Twine(NewFuncName));
591   GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
592   FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
593   Comdat *NewComdat;
594   Module *M = F.getParent();
595   // For AvailableExternallyLinkage functions, change the linkage to
596   // LinkOnceODR and put them into comdat. This is because after renaming, there
597   // is no backup external copy available for the function.
598   if (!F.hasComdat()) {
599     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
600     NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
601     F.setLinkage(GlobalValue::LinkOnceODRLinkage);
602     F.setComdat(NewComdat);
603     return;
604   }
605 
606   // This function belongs to a single function Comdat group.
607   Comdat *OrigComdat = F.getComdat();
608   std::string NewComdatName =
609       Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
610   NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
611   NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
612 
613   for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
614     if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
615       // For aliases, change the name directly.
616       assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
617       std::string OrigGAName = GA->getName().str();
618       GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
619       GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
620       continue;
621     }
622     // Must be a function.
623     Function *CF = dyn_cast<Function>(CM.second);
624     assert(CF);
625     CF->setComdat(NewComdat);
626   }
627 }
628 
629 // Given a CFG E to be instrumented, find which BB to place the instrumented
630 // code. The function will split the critical edge if necessary.
631 template <class Edge, class BBInfo>
632 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
633   if (E->InMST || E->Removed)
634     return nullptr;
635 
636   BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
637   BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
638   // For a fake edge, instrument the real BB.
639   if (SrcBB == nullptr)
640     return DestBB;
641   if (DestBB == nullptr)
642     return SrcBB;
643 
644   // Instrument the SrcBB if it has a single successor,
645   // otherwise, the DestBB if this is not a critical edge.
646   TerminatorInst *TI = SrcBB->getTerminator();
647   if (TI->getNumSuccessors() <= 1)
648     return SrcBB;
649   if (!E->IsCritical)
650     return DestBB;
651 
652   // For a critical edge, we have to split. Instrument the newly
653   // created BB.
654   NumOfPGOSplit++;
655   DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
656                << getBBInfo(DestBB).Index << "\n");
657   unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
658   BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
659   assert(InstrBB && "Critical edge is not split");
660 
661   E->Removed = true;
662   return InstrBB;
663 }
664 
665 // Visit all edge and instrument the edges not in MST, and do value profiling.
666 // Critical edges will be split.
667 static void instrumentOneFunc(
668     Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
669     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
670   FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
671                                                    BFI);
672   unsigned NumCounters = FuncInfo.getNumCounters();
673 
674   uint32_t I = 0;
675   Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
676   for (auto &E : FuncInfo.MST.AllEdges) {
677     BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
678     if (!InstrBB)
679       continue;
680 
681     IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
682     assert(Builder.GetInsertPoint() != InstrBB->end() &&
683            "Cannot get the Instrumentation point");
684     Builder.CreateCall(
685         Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
686         {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
687          Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
688          Builder.getInt32(I++)});
689   }
690 
691   // Now instrument select instructions:
692   FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
693                                        FuncInfo.FunctionHash);
694   assert(I == NumCounters);
695 
696   if (DisableValueProfiling)
697     return;
698 
699   unsigned NumIndirectCallSites = 0;
700   for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
701     CallSite CS(I);
702     Value *Callee = CS.getCalledValue();
703     DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
704                  << NumIndirectCallSites << "\n");
705     IRBuilder<> Builder(I);
706     assert(Builder.GetInsertPoint() != I->getParent()->end() &&
707            "Cannot get the Instrumentation point");
708     Builder.CreateCall(
709         Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
710         {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
711          Builder.getInt64(FuncInfo.FunctionHash),
712          Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
713          Builder.getInt32(IPVK_IndirectCallTarget),
714          Builder.getInt32(NumIndirectCallSites++)});
715   }
716   NumOfPGOICall += NumIndirectCallSites;
717 
718   // Now instrument memop intrinsic calls.
719   FuncInfo.MIVisitor.instrumentMemIntrinsics(
720       F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
721 }
722 
723 // This class represents a CFG edge in profile use compilation.
724 struct PGOUseEdge : public PGOEdge {
725   bool CountValid;
726   uint64_t CountValue;
727   PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
728       : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
729 
730   // Set edge count value
731   void setEdgeCount(uint64_t Value) {
732     CountValue = Value;
733     CountValid = true;
734   }
735 
736   // Return the information string for this object.
737   const std::string infoString() const {
738     if (!CountValid)
739       return PGOEdge::infoString();
740     return (Twine(PGOEdge::infoString()) + "  Count=" + Twine(CountValue))
741         .str();
742   }
743 };
744 
745 typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
746 
747 // This class stores the auxiliary information for each BB.
748 struct UseBBInfo : public BBInfo {
749   uint64_t CountValue;
750   bool CountValid;
751   int32_t UnknownCountInEdge;
752   int32_t UnknownCountOutEdge;
753   DirectEdges InEdges;
754   DirectEdges OutEdges;
755   UseBBInfo(unsigned IX)
756       : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
757         UnknownCountOutEdge(0) {}
758   UseBBInfo(unsigned IX, uint64_t C)
759       : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
760         UnknownCountOutEdge(0) {}
761 
762   // Set the profile count value for this BB.
763   void setBBInfoCount(uint64_t Value) {
764     CountValue = Value;
765     CountValid = true;
766   }
767 
768   // Return the information string of this object.
769   const std::string infoString() const {
770     if (!CountValid)
771       return BBInfo::infoString();
772     return (Twine(BBInfo::infoString()) + "  Count=" + Twine(CountValue)).str();
773   }
774 };
775 
776 // Sum up the count values for all the edges.
777 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
778   uint64_t Total = 0;
779   for (auto &E : Edges) {
780     if (E->Removed)
781       continue;
782     Total += E->CountValue;
783   }
784   return Total;
785 }
786 
787 class PGOUseFunc {
788 public:
789   PGOUseFunc(Function &Func, Module *Modu,
790              std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
791              BranchProbabilityInfo *BPI = nullptr,
792              BlockFrequencyInfo *BFI = nullptr)
793       : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
794         CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
795 
796   // Read counts for the instrumented BB from profile.
797   bool readCounters(IndexedInstrProfReader *PGOReader);
798 
799   // Populate the counts for all BBs.
800   void populateCounters();
801 
802   // Set the branch weights based on the count values.
803   void setBranchWeights();
804 
805   // Annotate the value profile call sites all all value kind.
806   void annotateValueSites();
807 
808   // Annotate the value profile call sites for one value kind.
809   void annotateValueSites(uint32_t Kind);
810 
811   // The hotness of the function from the profile count.
812   enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
813 
814   // Return the function hotness from the profile.
815   FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
816 
817   // Return the function hash.
818   uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
819   // Return the profile record for this function;
820   InstrProfRecord &getProfileRecord() { return ProfileRecord; }
821 
822   // Return the auxiliary BB information.
823   UseBBInfo &getBBInfo(const BasicBlock *BB) const {
824     return FuncInfo.getBBInfo(BB);
825   }
826 
827   // Return the auxiliary BB information if available.
828   UseBBInfo *findBBInfo(const BasicBlock *BB) const {
829     return FuncInfo.findBBInfo(BB);
830   }
831 
832   Function &getFunc() const { return F; }
833 
834 private:
835   Function &F;
836   Module *M;
837   // This member stores the shared information with class PGOGenFunc.
838   FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
839 
840   // The maximum count value in the profile. This is only used in PGO use
841   // compilation.
842   uint64_t ProgramMaxCount;
843 
844   // Position of counter that remains to be read.
845   uint32_t CountPosition;
846 
847   // Total size of the profile count for this function.
848   uint32_t ProfileCountSize;
849 
850   // ProfileRecord for this function.
851   InstrProfRecord ProfileRecord;
852 
853   // Function hotness info derived from profile.
854   FuncFreqAttr FreqAttr;
855 
856   // Find the Instrumented BB and set the value.
857   void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
858 
859   // Set the edge counter value for the unknown edge -- there should be only
860   // one unknown edge.
861   void setEdgeCount(DirectEdges &Edges, uint64_t Value);
862 
863   // Return FuncName string;
864   const std::string getFuncName() const { return FuncInfo.FuncName; }
865 
866   // Set the hot/cold inline hints based on the count values.
867   // FIXME: This function should be removed once the functionality in
868   // the inliner is implemented.
869   void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
870     if (ProgramMaxCount == 0)
871       return;
872     // Threshold of the hot functions.
873     const BranchProbability HotFunctionThreshold(1, 100);
874     // Threshold of the cold functions.
875     const BranchProbability ColdFunctionThreshold(2, 10000);
876     if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
877       FreqAttr = FFA_Hot;
878     else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
879       FreqAttr = FFA_Cold;
880   }
881 };
882 
883 // Visit all the edges and assign the count value for the instrumented
884 // edges and the BB.
885 void PGOUseFunc::setInstrumentedCounts(
886     const std::vector<uint64_t> &CountFromProfile) {
887 
888   assert(FuncInfo.getNumCounters() == CountFromProfile.size());
889   // Use a worklist as we will update the vector during the iteration.
890   std::vector<PGOUseEdge *> WorkList;
891   for (auto &E : FuncInfo.MST.AllEdges)
892     WorkList.push_back(E.get());
893 
894   uint32_t I = 0;
895   for (auto &E : WorkList) {
896     BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
897     if (!InstrBB)
898       continue;
899     uint64_t CountValue = CountFromProfile[I++];
900     if (!E->Removed) {
901       getBBInfo(InstrBB).setBBInfoCount(CountValue);
902       E->setEdgeCount(CountValue);
903       continue;
904     }
905 
906     // Need to add two new edges.
907     BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
908     BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
909     // Add new edge of SrcBB->InstrBB.
910     PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
911     NewEdge.setEdgeCount(CountValue);
912     // Add new edge of InstrBB->DestBB.
913     PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
914     NewEdge1.setEdgeCount(CountValue);
915     NewEdge1.InMST = true;
916     getBBInfo(InstrBB).setBBInfoCount(CountValue);
917   }
918   ProfileCountSize = CountFromProfile.size();
919   CountPosition = I;
920 }
921 
922 // Set the count value for the unknown edge. There should be one and only one
923 // unknown edge in Edges vector.
924 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
925   for (auto &E : Edges) {
926     if (E->CountValid)
927       continue;
928     E->setEdgeCount(Value);
929 
930     getBBInfo(E->SrcBB).UnknownCountOutEdge--;
931     getBBInfo(E->DestBB).UnknownCountInEdge--;
932     return;
933   }
934   llvm_unreachable("Cannot find the unknown count edge");
935 }
936 
937 // Read the profile from ProfileFileName and assign the value to the
938 // instrumented BB and the edges. This function also updates ProgramMaxCount.
939 // Return true if the profile are successfully read, and false on errors.
940 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
941   auto &Ctx = M->getContext();
942   Expected<InstrProfRecord> Result =
943       PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
944   if (Error E = Result.takeError()) {
945     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
946       auto Err = IPE.get();
947       bool SkipWarning = false;
948       if (Err == instrprof_error::unknown_function) {
949         NumOfPGOMissing++;
950         SkipWarning = !PGOWarnMissing;
951       } else if (Err == instrprof_error::hash_mismatch ||
952                  Err == instrprof_error::malformed) {
953         NumOfPGOMismatch++;
954         SkipWarning =
955             NoPGOWarnMismatch ||
956             (NoPGOWarnMismatchComdat &&
957              (F.hasComdat() ||
958               F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
959       }
960 
961       if (SkipWarning)
962         return;
963 
964       std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
965       Ctx.diagnose(
966           DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
967     });
968     return false;
969   }
970   ProfileRecord = std::move(Result.get());
971   std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
972 
973   NumOfPGOFunc++;
974   DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
975   uint64_t ValueSum = 0;
976   for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
977     DEBUG(dbgs() << "  " << I << ": " << CountFromProfile[I] << "\n");
978     ValueSum += CountFromProfile[I];
979   }
980 
981   DEBUG(dbgs() << "SUM =  " << ValueSum << "\n");
982 
983   getBBInfo(nullptr).UnknownCountOutEdge = 2;
984   getBBInfo(nullptr).UnknownCountInEdge = 2;
985 
986   setInstrumentedCounts(CountFromProfile);
987   ProgramMaxCount = PGOReader->getMaximumFunctionCount();
988   return true;
989 }
990 
991 // Populate the counters from instrumented BBs to all BBs.
992 // In the end of this operation, all BBs should have a valid count value.
993 void PGOUseFunc::populateCounters() {
994   // First set up Count variable for all BBs.
995   for (auto &E : FuncInfo.MST.AllEdges) {
996     if (E->Removed)
997       continue;
998 
999     const BasicBlock *SrcBB = E->SrcBB;
1000     const BasicBlock *DestBB = E->DestBB;
1001     UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1002     UseBBInfo &DestInfo = getBBInfo(DestBB);
1003     SrcInfo.OutEdges.push_back(E.get());
1004     DestInfo.InEdges.push_back(E.get());
1005     SrcInfo.UnknownCountOutEdge++;
1006     DestInfo.UnknownCountInEdge++;
1007 
1008     if (!E->CountValid)
1009       continue;
1010     DestInfo.UnknownCountInEdge--;
1011     SrcInfo.UnknownCountOutEdge--;
1012   }
1013 
1014   bool Changes = true;
1015   unsigned NumPasses = 0;
1016   while (Changes) {
1017     NumPasses++;
1018     Changes = false;
1019 
1020     // For efficient traversal, it's better to start from the end as most
1021     // of the instrumented edges are at the end.
1022     for (auto &BB : reverse(F)) {
1023       UseBBInfo *Count = findBBInfo(&BB);
1024       if (Count == nullptr)
1025         continue;
1026       if (!Count->CountValid) {
1027         if (Count->UnknownCountOutEdge == 0) {
1028           Count->CountValue = sumEdgeCount(Count->OutEdges);
1029           Count->CountValid = true;
1030           Changes = true;
1031         } else if (Count->UnknownCountInEdge == 0) {
1032           Count->CountValue = sumEdgeCount(Count->InEdges);
1033           Count->CountValid = true;
1034           Changes = true;
1035         }
1036       }
1037       if (Count->CountValid) {
1038         if (Count->UnknownCountOutEdge == 1) {
1039           uint64_t Total = 0;
1040           uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1041           // If the one of the successor block can early terminate (no-return),
1042           // we can end up with situation where out edge sum count is larger as
1043           // the source BB's count is collected by a post-dominated block.
1044           if (Count->CountValue > OutSum)
1045             Total = Count->CountValue - OutSum;
1046           setEdgeCount(Count->OutEdges, Total);
1047           Changes = true;
1048         }
1049         if (Count->UnknownCountInEdge == 1) {
1050           uint64_t Total = 0;
1051           uint64_t InSum = sumEdgeCount(Count->InEdges);
1052           if (Count->CountValue > InSum)
1053             Total = Count->CountValue - InSum;
1054           setEdgeCount(Count->InEdges, Total);
1055           Changes = true;
1056         }
1057       }
1058     }
1059   }
1060 
1061   DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
1062 #ifndef NDEBUG
1063   // Assert every BB has a valid counter.
1064   for (auto &BB : F) {
1065     auto BI = findBBInfo(&BB);
1066     if (BI == nullptr)
1067       continue;
1068     assert(BI->CountValid && "BB count is not valid");
1069   }
1070 #endif
1071   uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
1072   F.setEntryCount(FuncEntryCount);
1073   uint64_t FuncMaxCount = FuncEntryCount;
1074   for (auto &BB : F) {
1075     auto BI = findBBInfo(&BB);
1076     if (BI == nullptr)
1077       continue;
1078     FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1079   }
1080   markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1081 
1082   // Now annotate select instructions
1083   FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1084   assert(CountPosition == ProfileCountSize);
1085 
1086   DEBUG(FuncInfo.dumpInfo("after reading profile."));
1087 }
1088 
1089 // Assign the scaled count values to the BB with multiple out edges.
1090 void PGOUseFunc::setBranchWeights() {
1091   // Generate MD_prof metadata for every branch instruction.
1092   DEBUG(dbgs() << "\nSetting branch weights.\n");
1093   for (auto &BB : F) {
1094     TerminatorInst *TI = BB.getTerminator();
1095     if (TI->getNumSuccessors() < 2)
1096       continue;
1097     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1098       continue;
1099     if (getBBInfo(&BB).CountValue == 0)
1100       continue;
1101 
1102     // We have a non-zero Branch BB.
1103     const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1104     unsigned Size = BBCountInfo.OutEdges.size();
1105     SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
1106     uint64_t MaxCount = 0;
1107     for (unsigned s = 0; s < Size; s++) {
1108       const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1109       const BasicBlock *SrcBB = E->SrcBB;
1110       const BasicBlock *DestBB = E->DestBB;
1111       if (DestBB == nullptr)
1112         continue;
1113       unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1114       uint64_t EdgeCount = E->CountValue;
1115       if (EdgeCount > MaxCount)
1116         MaxCount = EdgeCount;
1117       EdgeCounts[SuccNum] = EdgeCount;
1118     }
1119     setProfMetadata(M, TI, EdgeCounts, MaxCount);
1120   }
1121 }
1122 
1123 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1124   Module *M = F.getParent();
1125   IRBuilder<> Builder(&SI);
1126   Type *Int64Ty = Builder.getInt64Ty();
1127   Type *I8PtrTy = Builder.getInt8PtrTy();
1128   auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1129   Builder.CreateCall(
1130       Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1131       {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1132        Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1133        Builder.getInt32(*CurCtrIdx), Step});
1134   ++(*CurCtrIdx);
1135 }
1136 
1137 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1138   std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1139   assert(*CurCtrIdx < CountFromProfile.size() &&
1140          "Out of bound access of counters");
1141   uint64_t SCounts[2];
1142   SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1143   ++(*CurCtrIdx);
1144   uint64_t TotalCount = 0;
1145   auto BI = UseFunc->findBBInfo(SI.getParent());
1146   if (BI != nullptr)
1147     TotalCount = BI->CountValue;
1148   // False Count
1149   SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1150   uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1151   if (MaxCount)
1152     setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
1153 }
1154 
1155 void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1156   if (!PGOInstrSelect)
1157     return;
1158   // FIXME: do not handle this yet.
1159   if (SI.getCondition()->getType()->isVectorTy())
1160     return;
1161 
1162   switch (Mode) {
1163   case VM_counting:
1164     NSIs++;
1165     return;
1166   case VM_instrument:
1167     instrumentOneSelectInst(SI);
1168     return;
1169   case VM_annotate:
1170     annotateOneSelectInst(SI);
1171     return;
1172   }
1173 
1174   llvm_unreachable("Unknown visiting mode");
1175 }
1176 
1177 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1178   Module *M = F.getParent();
1179   IRBuilder<> Builder(&MI);
1180   Type *Int64Ty = Builder.getInt64Ty();
1181   Type *I8PtrTy = Builder.getInt8PtrTy();
1182   Value *Length = MI.getLength();
1183   assert(!dyn_cast<ConstantInt>(Length));
1184   Builder.CreateCall(
1185       Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
1186       {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1187        Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
1188        Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1189   ++CurCtrId;
1190 }
1191 
1192 void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1193   if (!PGOInstrMemOP)
1194     return;
1195   Value *Length = MI.getLength();
1196   // Not instrument constant length calls.
1197   if (dyn_cast<ConstantInt>(Length))
1198     return;
1199 
1200   switch (Mode) {
1201   case VM_counting:
1202     NMemIs++;
1203     return;
1204   case VM_instrument:
1205     instrumentOneMemIntrinsic(MI);
1206     return;
1207   case VM_annotate:
1208     Candidates.push_back(&MI);
1209     return;
1210   }
1211   llvm_unreachable("Unknown visiting mode");
1212 }
1213 
1214 // Traverse all valuesites and annotate the instructions for all value kind.
1215 void PGOUseFunc::annotateValueSites() {
1216   if (DisableValueProfiling)
1217     return;
1218 
1219   // Create the PGOFuncName meta data.
1220   createPGOFuncNameMetadata(F, FuncInfo.FuncName);
1221 
1222   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1223     annotateValueSites(Kind);
1224 }
1225 
1226 // Annotate the instructions for a specific value kind.
1227 void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1228   unsigned ValueSiteIndex = 0;
1229   auto &ValueSites = FuncInfo.ValueSites[Kind];
1230   unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1231   if (NumValueSites != ValueSites.size()) {
1232     auto &Ctx = M->getContext();
1233     Ctx.diagnose(DiagnosticInfoPGOProfile(
1234         M->getName().data(),
1235         Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1236             " in " + F.getName().str(),
1237         DS_Warning));
1238     return;
1239   }
1240 
1241   for (auto &I : ValueSites) {
1242     DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1243                  << "): Index = " << ValueSiteIndex << " out of "
1244                  << NumValueSites << "\n");
1245     annotateValueSite(*M, *I, ProfileRecord,
1246                       static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1247                       Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1248                                              : MaxNumAnnotations);
1249     ValueSiteIndex++;
1250   }
1251 }
1252 } // end anonymous namespace
1253 
1254 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
1255 // aware this is an ir_level profile so it can set the version flag.
1256 static void createIRLevelProfileFlagVariable(Module &M) {
1257   Type *IntTy64 = Type::getInt64Ty(M.getContext());
1258   uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
1259   auto IRLevelVersionVariable = new GlobalVariable(
1260       M, IntTy64, true, GlobalVariable::ExternalLinkage,
1261       Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
1262       INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1263   IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1264   Triple TT(M.getTargetTriple());
1265   if (!TT.supportsCOMDAT())
1266     IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
1267   else
1268     IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
1269         StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
1270 }
1271 
1272 // Collect the set of members for each Comdat in module M and store
1273 // in ComdatMembers.
1274 static void collectComdatMembers(
1275     Module &M,
1276     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1277   if (!DoComdatRenaming)
1278     return;
1279   for (Function &F : M)
1280     if (Comdat *C = F.getComdat())
1281       ComdatMembers.insert(std::make_pair(C, &F));
1282   for (GlobalVariable &GV : M.globals())
1283     if (Comdat *C = GV.getComdat())
1284       ComdatMembers.insert(std::make_pair(C, &GV));
1285   for (GlobalAlias &GA : M.aliases())
1286     if (Comdat *C = GA.getComdat())
1287       ComdatMembers.insert(std::make_pair(C, &GA));
1288 }
1289 
1290 static bool InstrumentAllFunctions(
1291     Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1292     function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
1293   createIRLevelProfileFlagVariable(M);
1294   std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1295   collectComdatMembers(M, ComdatMembers);
1296 
1297   for (auto &F : M) {
1298     if (F.isDeclaration())
1299       continue;
1300     auto *BPI = LookupBPI(F);
1301     auto *BFI = LookupBFI(F);
1302     instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
1303   }
1304   return true;
1305 }
1306 
1307 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
1308   if (skipModule(M))
1309     return false;
1310 
1311   auto LookupBPI = [this](Function &F) {
1312     return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1313   };
1314   auto LookupBFI = [this](Function &F) {
1315     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1316   };
1317   return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1318 }
1319 
1320 PreservedAnalyses PGOInstrumentationGen::run(Module &M,
1321                                              ModuleAnalysisManager &AM) {
1322 
1323   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1324   auto LookupBPI = [&FAM](Function &F) {
1325     return &FAM.getResult<BranchProbabilityAnalysis>(F);
1326   };
1327 
1328   auto LookupBFI = [&FAM](Function &F) {
1329     return &FAM.getResult<BlockFrequencyAnalysis>(F);
1330   };
1331 
1332   if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1333     return PreservedAnalyses::all();
1334 
1335   return PreservedAnalyses::none();
1336 }
1337 
1338 static bool annotateAllFunctions(
1339     Module &M, StringRef ProfileFileName,
1340     function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1341     function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
1342   DEBUG(dbgs() << "Read in profile counters: ");
1343   auto &Ctx = M.getContext();
1344   // Read the counter array from file.
1345   auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
1346   if (Error E = ReaderOrErr.takeError()) {
1347     handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1348       Ctx.diagnose(
1349           DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1350     });
1351     return false;
1352   }
1353 
1354   std::unique_ptr<IndexedInstrProfReader> PGOReader =
1355       std::move(ReaderOrErr.get());
1356   if (!PGOReader) {
1357     Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
1358                                           StringRef("Cannot get PGOReader")));
1359     return false;
1360   }
1361   // TODO: might need to change the warning once the clang option is finalized.
1362   if (!PGOReader->isIRLevelProfile()) {
1363     Ctx.diagnose(DiagnosticInfoPGOProfile(
1364         ProfileFileName.data(), "Not an IR level instrumentation profile"));
1365     return false;
1366   }
1367 
1368   std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1369   collectComdatMembers(M, ComdatMembers);
1370   std::vector<Function *> HotFunctions;
1371   std::vector<Function *> ColdFunctions;
1372   for (auto &F : M) {
1373     if (F.isDeclaration())
1374       continue;
1375     auto *BPI = LookupBPI(F);
1376     auto *BFI = LookupBFI(F);
1377     PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
1378     if (!Func.readCounters(PGOReader.get()))
1379       continue;
1380     Func.populateCounters();
1381     Func.setBranchWeights();
1382     Func.annotateValueSites();
1383     PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1384     if (FreqAttr == PGOUseFunc::FFA_Cold)
1385       ColdFunctions.push_back(&F);
1386     else if (FreqAttr == PGOUseFunc::FFA_Hot)
1387       HotFunctions.push_back(&F);
1388     if (PGOViewCounts && (ViewBlockFreqFuncName.empty() ||
1389                           F.getName().equals(ViewBlockFreqFuncName))) {
1390       LoopInfo LI{DominatorTree(F)};
1391       std::unique_ptr<BranchProbabilityInfo> NewBPI =
1392           llvm::make_unique<BranchProbabilityInfo>(F, LI);
1393       std::unique_ptr<BlockFrequencyInfo> NewBFI =
1394           llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1395 
1396       NewBFI->view();
1397     }
1398     if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() ||
1399                              F.getName().equals(ViewBlockFreqFuncName))) {
1400       if (ViewBlockFreqFuncName.empty())
1401         WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1402       else
1403         ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1404     }
1405   }
1406   M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
1407   // Set function hotness attribute from the profile.
1408   // We have to apply these attributes at the end because their presence
1409   // can affect the BranchProbabilityInfo of any callers, resulting in an
1410   // inconsistent MST between prof-gen and prof-use.
1411   for (auto &F : HotFunctions) {
1412     F->addFnAttr(llvm::Attribute::InlineHint);
1413     DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1414                  << "\n");
1415   }
1416   for (auto &F : ColdFunctions) {
1417     F->addFnAttr(llvm::Attribute::Cold);
1418     DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1419   }
1420   return true;
1421 }
1422 
1423 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
1424     : ProfileFileName(std::move(Filename)) {
1425   if (!PGOTestProfileFile.empty())
1426     ProfileFileName = PGOTestProfileFile;
1427 }
1428 
1429 PreservedAnalyses PGOInstrumentationUse::run(Module &M,
1430                                              ModuleAnalysisManager &AM) {
1431 
1432   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1433   auto LookupBPI = [&FAM](Function &F) {
1434     return &FAM.getResult<BranchProbabilityAnalysis>(F);
1435   };
1436 
1437   auto LookupBFI = [&FAM](Function &F) {
1438     return &FAM.getResult<BlockFrequencyAnalysis>(F);
1439   };
1440 
1441   if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1442     return PreservedAnalyses::all();
1443 
1444   return PreservedAnalyses::none();
1445 }
1446 
1447 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1448   if (skipModule(M))
1449     return false;
1450 
1451   auto LookupBPI = [this](Function &F) {
1452     return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1453   };
1454   auto LookupBFI = [this](Function &F) {
1455     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1456   };
1457 
1458   return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
1459 }
1460 
1461 namespace llvm {
1462 void setProfMetadata(Module *M, Instruction *TI, ArrayRef<uint64_t> EdgeCounts,
1463                      uint64_t MaxCount) {
1464   MDBuilder MDB(M->getContext());
1465   assert(MaxCount > 0 && "Bad max count");
1466   uint64_t Scale = calculateCountScale(MaxCount);
1467   SmallVector<unsigned, 4> Weights;
1468   for (const auto &ECI : EdgeCounts)
1469     Weights.push_back(scaleBranchCount(ECI, Scale));
1470 
1471   DEBUG(dbgs() << "Weight is: ";
1472         for (const auto &W : Weights) { dbgs() << W << " "; }
1473         dbgs() << "\n";);
1474   TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1475   if (EmitBranchProbability) {
1476     std::string BrCondStr = getBranchCondString(TI);
1477     if (BrCondStr.empty())
1478       return;
1479 
1480     unsigned WSum =
1481         std::accumulate(Weights.begin(), Weights.end(), 0,
1482                         [](unsigned w1, unsigned w2) { return w1 + w2; });
1483     uint64_t TotalCount =
1484         std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0,
1485                         [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1486     BranchProbability BP(Weights[0], WSum);
1487     std::string BranchProbStr;
1488     raw_string_ostream OS(BranchProbStr);
1489     OS << BP;
1490     OS << " (total count : " << TotalCount << ")";
1491     OS.flush();
1492     Function *F = TI->getParent()->getParent();
1493     OptimizationRemarkEmitter ORE(F);
1494     ORE.emit(OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1495              << BrCondStr << " is true with probability : " << BranchProbStr);
1496   }
1497 }
1498 
1499 template <> struct GraphTraits<PGOUseFunc *> {
1500   typedef const BasicBlock *NodeRef;
1501   typedef succ_const_iterator ChildIteratorType;
1502   typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1503 
1504   static NodeRef getEntryNode(const PGOUseFunc *G) {
1505     return &G->getFunc().front();
1506   }
1507   static ChildIteratorType child_begin(const NodeRef N) {
1508     return succ_begin(N);
1509   }
1510   static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1511   static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1512     return nodes_iterator(G->getFunc().begin());
1513   }
1514   static nodes_iterator nodes_end(const PGOUseFunc *G) {
1515     return nodes_iterator(G->getFunc().end());
1516   }
1517 };
1518 
1519 static std::string getSimpleNodeName(const BasicBlock *Node) {
1520   if (!Node->getName().empty())
1521     return Node->getName();
1522 
1523   std::string SimpleNodeName;
1524   raw_string_ostream OS(SimpleNodeName);
1525   Node->printAsOperand(OS, false);
1526   return OS.str();
1527 }
1528 
1529 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1530   explicit DOTGraphTraits(bool isSimple = false)
1531       : DefaultDOTGraphTraits(isSimple) {}
1532 
1533   static std::string getGraphName(const PGOUseFunc *G) {
1534     return G->getFunc().getName();
1535   }
1536 
1537   std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1538     std::string Result;
1539     raw_string_ostream OS(Result);
1540 
1541     OS << getSimpleNodeName(Node) << ":\\l";
1542     UseBBInfo *BI = Graph->findBBInfo(Node);
1543     OS << "Count : ";
1544     if (BI && BI->CountValid)
1545       OS << BI->CountValue << "\\l";
1546     else
1547       OS << "Unknown\\l";
1548 
1549     if (!PGOInstrSelect)
1550       return Result;
1551 
1552     for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1553       auto *I = &*BI;
1554       if (!isa<SelectInst>(I))
1555         continue;
1556       // Display scaled counts for SELECT instruction:
1557       OS << "SELECT : { T = ";
1558       uint64_t TC, FC;
1559       bool HasProf = I->extractProfMetadata(TC, FC);
1560       if (!HasProf)
1561         OS << "Unknown, F = Unknown }\\l";
1562       else
1563         OS << TC << ", F = " << FC << " }\\l";
1564     }
1565     return Result;
1566   }
1567 };
1568 } // namespace llvm
1569