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