1 //===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements PGO instrumentation using a minimum spanning tree based
10 // on the following paper:
11 //   [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
12 //   for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
13 //   Issue 3, pp 313-322
14 // The idea of the algorithm based on the fact that for each node (except for
15 // the entry and exit), the sum of incoming edge counts equals the sum of
16 // outgoing edge counts. The count of edge on spanning tree can be derived from
17 // those edges not on the spanning tree. Knuth proves this method instruments
18 // the minimum number of edges.
19 //
20 // The minimal spanning tree here is actually a maximum weight tree -- on-tree
21 // edges have higher frequencies (more likely to execute). The idea is to
22 // instrument those less frequently executed edges to reduce the runtime
23 // overhead of instrumented binaries.
24 //
25 // This file contains two passes:
26 // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
27 // count profile, and generates the instrumentation for indirect call
28 // profiling.
29 // (2) Pass PGOInstrumentationUse which reads the edge count profile and
30 // annotates the branch weights. It also reads the indirect call value
31 // profiling records and annotate the indirect call instructions.
32 //
33 // To get the precise counter information, These two passes need to invoke at
34 // the same compilation point (so they see the same IR). For pass
35 // PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
36 // pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
37 // the profile is opened in module level and passed to each PGOUseFunc instance.
38 // The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
39 // in class FuncPGOInstrumentation.
40 //
41 // Class PGOEdge represents a CFG edge and some auxiliary information. Class
42 // BBInfo contains auxiliary information for each BB. These two classes are used
43 // in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
44 // class of PGOEdge and BBInfo, respectively. They contains extra data structure
45 // used in populating profile counters.
46 // The MST implementation is in Class CFGMST (CFGMST.h).
47 //
48 //===----------------------------------------------------------------------===//
49 
50 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
51 #include "CFGMST.h"
52 #include "ValueProfileCollector.h"
53 #include "llvm/ADT/APInt.h"
54 #include "llvm/ADT/ArrayRef.h"
55 #include "llvm/ADT/MapVector.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/Triple.h"
61 #include "llvm/ADT/Twine.h"
62 #include "llvm/ADT/iterator.h"
63 #include "llvm/ADT/iterator_range.h"
64 #include "llvm/Analysis/BlockFrequencyInfo.h"
65 #include "llvm/Analysis/BranchProbabilityInfo.h"
66 #include "llvm/Analysis/CFG.h"
67 #include "llvm/Analysis/EHPersonalities.h"
68 #include "llvm/Analysis/LoopInfo.h"
69 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
70 #include "llvm/Analysis/ProfileSummaryInfo.h"
71 #include "llvm/IR/Attributes.h"
72 #include "llvm/IR/BasicBlock.h"
73 #include "llvm/IR/CFG.h"
74 #include "llvm/IR/Comdat.h"
75 #include "llvm/IR/Constant.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DiagnosticInfo.h"
78 #include "llvm/IR/Dominators.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GlobalAlias.h"
81 #include "llvm/IR/GlobalValue.h"
82 #include "llvm/IR/GlobalVariable.h"
83 #include "llvm/IR/IRBuilder.h"
84 #include "llvm/IR/InstVisitor.h"
85 #include "llvm/IR/InstrTypes.h"
86 #include "llvm/IR/Instruction.h"
87 #include "llvm/IR/Instructions.h"
88 #include "llvm/IR/IntrinsicInst.h"
89 #include "llvm/IR/Intrinsics.h"
90 #include "llvm/IR/LLVMContext.h"
91 #include "llvm/IR/MDBuilder.h"
92 #include "llvm/IR/Module.h"
93 #include "llvm/IR/PassManager.h"
94 #include "llvm/IR/ProfileSummary.h"
95 #include "llvm/IR/Type.h"
96 #include "llvm/IR/Value.h"
97 #include "llvm/InitializePasses.h"
98 #include "llvm/Pass.h"
99 #include "llvm/ProfileData/InstrProf.h"
100 #include "llvm/ProfileData/InstrProfReader.h"
101 #include "llvm/Support/BranchProbability.h"
102 #include "llvm/Support/CRC.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CommandLine.h"
105 #include "llvm/Support/DOTGraphTraits.h"
106 #include "llvm/Support/Debug.h"
107 #include "llvm/Support/Error.h"
108 #include "llvm/Support/ErrorHandling.h"
109 #include "llvm/Support/GraphWriter.h"
110 #include "llvm/Support/raw_ostream.h"
111 #include "llvm/Transforms/Instrumentation.h"
112 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
113 #include "llvm/Transforms/Utils/MisExpect.h"
114 #include <algorithm>
115 #include <cassert>
116 #include <cstdint>
117 #include <memory>
118 #include <numeric>
119 #include <string>
120 #include <unordered_map>
121 #include <utility>
122 #include <vector>
123 
124 using namespace llvm;
125 using ProfileCount = Function::ProfileCount;
126 using VPCandidateInfo = ValueProfileCollector::CandidateInfo;
127 
128 #define DEBUG_TYPE "pgo-instrumentation"
129 
130 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
131 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
132 STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
133 STATISTIC(NumOfPGOEdge, "Number of edges.");
134 STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
135 STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
136 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
137 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
138 STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
139 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
140 STATISTIC(NumOfCSPGOInstrument, "Number of edges instrumented in CSPGO.");
141 STATISTIC(NumOfCSPGOSelectInsts,
142           "Number of select instruction instrumented in CSPGO.");
143 STATISTIC(NumOfCSPGOMemIntrinsics,
144           "Number of mem intrinsics instrumented in CSPGO.");
145 STATISTIC(NumOfCSPGOEdge, "Number of edges in CSPGO.");
146 STATISTIC(NumOfCSPGOBB, "Number of basic-blocks in CSPGO.");
147 STATISTIC(NumOfCSPGOSplit, "Number of critical edge splits in CSPGO.");
148 STATISTIC(NumOfCSPGOFunc,
149           "Number of functions having valid profile counts in CSPGO.");
150 STATISTIC(NumOfCSPGOMismatch,
151           "Number of functions having mismatch profile in CSPGO.");
152 STATISTIC(NumOfCSPGOMissing, "Number of functions without profile in CSPGO.");
153 
154 // Command line option to specify the file to read profile from. This is
155 // mainly used for testing.
156 static cl::opt<std::string>
157     PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
158                        cl::value_desc("filename"),
159                        cl::desc("Specify the path of profile data file. This is"
160                                 "mainly for test purpose."));
161 static cl::opt<std::string> PGOTestProfileRemappingFile(
162     "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden,
163     cl::value_desc("filename"),
164     cl::desc("Specify the path of profile remapping file. This is mainly for "
165              "test purpose."));
166 
167 // Command line option to disable value profiling. The default is false:
168 // i.e. value profiling is enabled by default. This is for debug purpose.
169 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
170                                            cl::Hidden,
171                                            cl::desc("Disable Value Profiling"));
172 
173 // Command line option to set the maximum number of VP annotations to write to
174 // the metadata for a single indirect call callsite.
175 static cl::opt<unsigned> MaxNumAnnotations(
176     "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
177     cl::desc("Max number of annotations for a single indirect "
178              "call callsite"));
179 
180 // Command line option to set the maximum number of value annotations
181 // to write to the metadata for a single memop intrinsic.
182 static cl::opt<unsigned> MaxNumMemOPAnnotations(
183     "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
184     cl::desc("Max number of preicise value annotations for a single memop"
185              "intrinsic"));
186 
187 // Command line option to control appending FunctionHash to the name of a COMDAT
188 // function. This is to avoid the hash mismatch caused by the preinliner.
189 static cl::opt<bool> DoComdatRenaming(
190     "do-comdat-renaming", cl::init(false), cl::Hidden,
191     cl::desc("Append function hash to the name of COMDAT function to avoid "
192              "function hash mismatch due to the preinliner"));
193 
194 // Command line option to enable/disable the warning about missing profile
195 // information.
196 static cl::opt<bool>
197     PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
198                    cl::desc("Use this option to turn on/off "
199                             "warnings about missing profile data for "
200                             "functions."));
201 
202 // Command line option to enable/disable the warning about a hash mismatch in
203 // the profile data.
204 static cl::opt<bool>
205     NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
206                       cl::desc("Use this option to turn off/on "
207                                "warnings about profile cfg mismatch."));
208 
209 // Command line option to enable/disable the warning about a hash mismatch in
210 // the profile data for Comdat functions, which often turns out to be false
211 // positive due to the pre-instrumentation inline.
212 static cl::opt<bool>
213     NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
214                             cl::Hidden,
215                             cl::desc("The option is used to turn on/off "
216                                      "warnings about hash mismatch for comdat "
217                                      "functions."));
218 
219 // Command line option to enable/disable select instruction instrumentation.
220 static cl::opt<bool>
221     PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
222                    cl::desc("Use this option to turn on/off SELECT "
223                             "instruction instrumentation. "));
224 
225 // Command line option to turn on CFG dot or text dump of raw profile counts
226 static cl::opt<PGOViewCountsType> PGOViewRawCounts(
227     "pgo-view-raw-counts", cl::Hidden,
228     cl::desc("A boolean option to show CFG dag or text "
229              "with raw profile counts from "
230              "profile data. See also option "
231              "-pgo-view-counts. To limit graph "
232              "display to only one function, use "
233              "filtering option -view-bfi-func-name."),
234     cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
235                clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
236                clEnumValN(PGOVCT_Text, "text", "show in text.")));
237 
238 // Command line option to enable/disable memop intrinsic call.size profiling.
239 static cl::opt<bool>
240     PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
241                   cl::desc("Use this option to turn on/off "
242                            "memory intrinsic size profiling."));
243 
244 // Emit branch probability as optimization remarks.
245 static cl::opt<bool>
246     EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
247                           cl::desc("When this option is on, the annotated "
248                                    "branch probability will be emitted as "
249                                    "optimization remarks: -{Rpass|"
250                                    "pass-remarks}=pgo-instrumentation"));
251 
252 static cl::opt<bool> PGOInstrumentEntry(
253     "pgo-instrument-entry", cl::init(false), cl::Hidden,
254     cl::desc("Force to instrument function entry basicblock."));
255 
256 // Command line option to turn on CFG dot dump after profile annotation.
257 // Defined in Analysis/BlockFrequencyInfo.cpp:  -pgo-view-counts
258 extern cl::opt<PGOViewCountsType> PGOViewCounts;
259 
260 // Command line option to specify the name of the function for CFG dump
261 // Defined in Analysis/BlockFrequencyInfo.cpp:  -view-bfi-func-name=
262 extern cl::opt<std::string> ViewBlockFreqFuncName;
263 
264 static cl::opt<bool>
265     PGOOldCFGHashing("pgo-instr-old-cfg-hashing", cl::init(false), cl::Hidden,
266                      cl::desc("Use the old CFG function hashing"));
267 
268 // Return a string describing the branch condition that can be
269 // used in static branch probability heuristics:
270 static std::string getBranchCondString(Instruction *TI) {
271   BranchInst *BI = dyn_cast<BranchInst>(TI);
272   if (!BI || !BI->isConditional())
273     return std::string();
274 
275   Value *Cond = BI->getCondition();
276   ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
277   if (!CI)
278     return std::string();
279 
280   std::string result;
281   raw_string_ostream OS(result);
282   OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
283   CI->getOperand(0)->getType()->print(OS, true);
284 
285   Value *RHS = CI->getOperand(1);
286   ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
287   if (CV) {
288     if (CV->isZero())
289       OS << "_Zero";
290     else if (CV->isOne())
291       OS << "_One";
292     else if (CV->isMinusOne())
293       OS << "_MinusOne";
294     else
295       OS << "_Const";
296   }
297   OS.flush();
298   return result;
299 }
300 
301 static const char *ValueProfKindDescr[] = {
302 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
303 #include "llvm/ProfileData/InstrProfData.inc"
304 };
305 
306 namespace {
307 
308 /// The select instruction visitor plays three roles specified
309 /// by the mode. In \c VM_counting mode, it simply counts the number of
310 /// select instructions. In \c VM_instrument mode, it inserts code to count
311 /// the number times TrueValue of select is taken. In \c VM_annotate mode,
312 /// it reads the profile data and annotate the select instruction with metadata.
313 enum VisitMode { VM_counting, VM_instrument, VM_annotate };
314 class PGOUseFunc;
315 
316 /// Instruction Visitor class to visit select instructions.
317 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
318   Function &F;
319   unsigned NSIs = 0;             // Number of select instructions instrumented.
320   VisitMode Mode = VM_counting;  // Visiting mode.
321   unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
322   unsigned TotalNumCtrs = 0;     // Total number of counters
323   GlobalVariable *FuncNameVar = nullptr;
324   uint64_t FuncHash = 0;
325   PGOUseFunc *UseFunc = nullptr;
326 
327   SelectInstVisitor(Function &Func) : F(Func) {}
328 
329   void countSelects(Function &Func) {
330     NSIs = 0;
331     Mode = VM_counting;
332     visit(Func);
333   }
334 
335   // Visit the IR stream and instrument all select instructions. \p
336   // Ind is a pointer to the counter index variable; \p TotalNC
337   // is the total number of counters; \p FNV is the pointer to the
338   // PGO function name var; \p FHash is the function hash.
339   void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
340                          GlobalVariable *FNV, uint64_t FHash) {
341     Mode = VM_instrument;
342     CurCtrIdx = Ind;
343     TotalNumCtrs = TotalNC;
344     FuncHash = FHash;
345     FuncNameVar = FNV;
346     visit(Func);
347   }
348 
349   // Visit the IR stream and annotate all select instructions.
350   void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
351     Mode = VM_annotate;
352     UseFunc = UF;
353     CurCtrIdx = Ind;
354     visit(Func);
355   }
356 
357   void instrumentOneSelectInst(SelectInst &SI);
358   void annotateOneSelectInst(SelectInst &SI);
359 
360   // Visit \p SI instruction and perform tasks according to visit mode.
361   void visitSelectInst(SelectInst &SI);
362 
363   // Return the number of select instructions. This needs be called after
364   // countSelects().
365   unsigned getNumOfSelectInsts() const { return NSIs; }
366 };
367 
368 
369 class PGOInstrumentationGenLegacyPass : public ModulePass {
370 public:
371   static char ID;
372 
373   PGOInstrumentationGenLegacyPass(bool IsCS = false)
374       : ModulePass(ID), IsCS(IsCS) {
375     initializePGOInstrumentationGenLegacyPassPass(
376         *PassRegistry::getPassRegistry());
377   }
378 
379   StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
380 
381 private:
382   // Is this is context-sensitive instrumentation.
383   bool IsCS;
384   bool runOnModule(Module &M) override;
385 
386   void getAnalysisUsage(AnalysisUsage &AU) const override {
387     AU.addRequired<BlockFrequencyInfoWrapperPass>();
388     AU.addRequired<TargetLibraryInfoWrapperPass>();
389   }
390 };
391 
392 class PGOInstrumentationUseLegacyPass : public ModulePass {
393 public:
394   static char ID;
395 
396   // Provide the profile filename as the parameter.
397   PGOInstrumentationUseLegacyPass(std::string Filename = "", bool IsCS = false)
398       : ModulePass(ID), ProfileFileName(std::move(Filename)), IsCS(IsCS) {
399     if (!PGOTestProfileFile.empty())
400       ProfileFileName = PGOTestProfileFile;
401     initializePGOInstrumentationUseLegacyPassPass(
402         *PassRegistry::getPassRegistry());
403   }
404 
405   StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
406 
407 private:
408   std::string ProfileFileName;
409   // Is this is context-sensitive instrumentation use.
410   bool IsCS;
411 
412   bool runOnModule(Module &M) override;
413 
414   void getAnalysisUsage(AnalysisUsage &AU) const override {
415     AU.addRequired<ProfileSummaryInfoWrapperPass>();
416     AU.addRequired<BlockFrequencyInfoWrapperPass>();
417     AU.addRequired<TargetLibraryInfoWrapperPass>();
418   }
419 };
420 
421 class PGOInstrumentationGenCreateVarLegacyPass : public ModulePass {
422 public:
423   static char ID;
424   StringRef getPassName() const override {
425     return "PGOInstrumentationGenCreateVarPass";
426   }
427   PGOInstrumentationGenCreateVarLegacyPass(std::string CSInstrName = "")
428       : ModulePass(ID), InstrProfileOutput(CSInstrName) {
429     initializePGOInstrumentationGenCreateVarLegacyPassPass(
430         *PassRegistry::getPassRegistry());
431   }
432 
433 private:
434   bool runOnModule(Module &M) override {
435     createProfileFileNameVar(M, InstrProfileOutput);
436     createIRLevelProfileFlagVar(M, /* IsCS */ true, PGOInstrumentEntry);
437     return false;
438   }
439   std::string InstrProfileOutput;
440 };
441 
442 } // end anonymous namespace
443 
444 char PGOInstrumentationGenLegacyPass::ID = 0;
445 
446 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
447                       "PGO instrumentation.", false, false)
448 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
449 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
450 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
451 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
452                     "PGO instrumentation.", false, false)
453 
454 ModulePass *llvm::createPGOInstrumentationGenLegacyPass(bool IsCS) {
455   return new PGOInstrumentationGenLegacyPass(IsCS);
456 }
457 
458 char PGOInstrumentationUseLegacyPass::ID = 0;
459 
460 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
461                       "Read PGO instrumentation profile.", false, false)
462 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
463 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
464 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
465 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
466                     "Read PGO instrumentation profile.", false, false)
467 
468 ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename,
469                                                         bool IsCS) {
470   return new PGOInstrumentationUseLegacyPass(Filename.str(), IsCS);
471 }
472 
473 char PGOInstrumentationGenCreateVarLegacyPass::ID = 0;
474 
475 INITIALIZE_PASS(PGOInstrumentationGenCreateVarLegacyPass,
476                 "pgo-instr-gen-create-var",
477                 "Create PGO instrumentation version variable for CSPGO.", false,
478                 false)
479 
480 ModulePass *
481 llvm::createPGOInstrumentationGenCreateVarLegacyPass(StringRef CSInstrName) {
482   return new PGOInstrumentationGenCreateVarLegacyPass(std::string(CSInstrName));
483 }
484 
485 namespace {
486 
487 /// An MST based instrumentation for PGO
488 ///
489 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
490 /// in the function level.
491 struct PGOEdge {
492   // This class implements the CFG edges. Note the CFG can be a multi-graph.
493   // So there might be multiple edges with same SrcBB and DestBB.
494   const BasicBlock *SrcBB;
495   const BasicBlock *DestBB;
496   uint64_t Weight;
497   bool InMST = false;
498   bool Removed = false;
499   bool IsCritical = false;
500 
501   PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
502       : SrcBB(Src), DestBB(Dest), Weight(W) {}
503 
504   // Return the information string of an edge.
505   const std::string infoString() const {
506     return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
507             (IsCritical ? "c" : " ") + "  W=" + Twine(Weight)).str();
508   }
509 };
510 
511 // This class stores the auxiliary information for each BB.
512 struct BBInfo {
513   BBInfo *Group;
514   uint32_t Index;
515   uint32_t Rank = 0;
516 
517   BBInfo(unsigned IX) : Group(this), Index(IX) {}
518 
519   // Return the information string of this object.
520   const std::string infoString() const {
521     return (Twine("Index=") + Twine(Index)).str();
522   }
523 
524   // Empty function -- only applicable to UseBBInfo.
525   void addOutEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {}
526 
527   // Empty function -- only applicable to UseBBInfo.
528   void addInEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {}
529 };
530 
531 // This class implements the CFG edges. Note the CFG can be a multi-graph.
532 template <class Edge, class BBInfo> class FuncPGOInstrumentation {
533 private:
534   Function &F;
535 
536   // Is this is context-sensitive instrumentation.
537   bool IsCS;
538 
539   // If we instrument function entry BB by default.
540   bool InstrumentFuncEntry;
541 
542   // A map that stores the Comdat group in function F.
543   std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
544 
545   ValueProfileCollector VPC;
546 
547   void computeCFGHash();
548   void renameComdatFunction();
549 
550 public:
551   std::vector<std::vector<VPCandidateInfo>> ValueSites;
552   SelectInstVisitor SIVisitor;
553   std::string FuncName;
554   GlobalVariable *FuncNameVar;
555 
556   // CFG hash value for this function.
557   uint64_t FunctionHash = 0;
558 
559   // The Minimum Spanning Tree of function CFG.
560   CFGMST<Edge, BBInfo> MST;
561 
562   // Collect all the BBs that will be instrumented, and store them in
563   // InstrumentBBs.
564   void getInstrumentBBs(std::vector<BasicBlock *> &InstrumentBBs);
565 
566   // Give an edge, find the BB that will be instrumented.
567   // Return nullptr if there is no BB to be instrumented.
568   BasicBlock *getInstrBB(Edge *E);
569 
570   // Return the auxiliary BB information.
571   BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
572 
573   // Return the auxiliary BB information if available.
574   BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
575 
576   // Dump edges and BB information.
577   void dumpInfo(std::string Str = "") const {
578     MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
579                               Twine(FunctionHash) + "\t" + Str);
580   }
581 
582   FuncPGOInstrumentation(
583       Function &Func, TargetLibraryInfo &TLI,
584       std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
585       bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
586       BlockFrequencyInfo *BFI = nullptr, bool IsCS = false,
587       bool InstrumentFuncEntry = true)
588       : F(Func), IsCS(IsCS), ComdatMembers(ComdatMembers), VPC(Func, TLI),
589         ValueSites(IPVK_Last + 1), SIVisitor(Func),
590         MST(F, InstrumentFuncEntry, BPI, BFI) {
591     // This should be done before CFG hash computation.
592     SIVisitor.countSelects(Func);
593     ValueSites[IPVK_MemOPSize] = VPC.get(IPVK_MemOPSize);
594     if (!IsCS) {
595       NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
596       NumOfPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
597       NumOfPGOBB += MST.BBInfos.size();
598       ValueSites[IPVK_IndirectCallTarget] = VPC.get(IPVK_IndirectCallTarget);
599     } else {
600       NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
601       NumOfCSPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
602       NumOfCSPGOBB += MST.BBInfos.size();
603     }
604 
605     FuncName = getPGOFuncName(F);
606     computeCFGHash();
607     if (!ComdatMembers.empty())
608       renameComdatFunction();
609     LLVM_DEBUG(dumpInfo("after CFGMST"));
610 
611     for (auto &E : MST.AllEdges) {
612       if (E->Removed)
613         continue;
614       IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++;
615       if (!E->InMST)
616         IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++;
617     }
618 
619     if (CreateGlobalVar)
620       FuncNameVar = createPGOFuncNameVar(F, FuncName);
621   }
622 };
623 
624 } // end anonymous namespace
625 
626 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
627 // value of each BB in the CFG. The higher 32 bits are the CRC32 of the numbers
628 // of selects, indirect calls, mem ops and edges.
629 template <class Edge, class BBInfo>
630 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
631   std::vector<uint8_t> Indexes;
632   JamCRC JC;
633   for (auto &BB : F) {
634     const Instruction *TI = BB.getTerminator();
635     for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
636       BasicBlock *Succ = TI->getSuccessor(I);
637       auto BI = findBBInfo(Succ);
638       if (BI == nullptr)
639         continue;
640       uint32_t Index = BI->Index;
641       for (int J = 0; J < 4; J++)
642         Indexes.push_back((uint8_t)(Index >> (J * 8)));
643     }
644   }
645   JC.update(Indexes);
646 
647   JamCRC JCH;
648   if (PGOOldCFGHashing) {
649     // Hash format for context sensitive profile. Reserve 4 bits for other
650     // information.
651     FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
652                    (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
653                    //(uint64_t)ValueSites[IPVK_MemOPSize].size() << 40 |
654                    (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
655   } else {
656     // The higher 32 bits.
657     auto updateJCH = [&JCH](uint64_t Num) {
658       uint8_t Data[8];
659       support::endian::write64le(Data, Num);
660       JCH.update(Data);
661     };
662     updateJCH((uint64_t)SIVisitor.getNumOfSelectInsts());
663     updateJCH((uint64_t)ValueSites[IPVK_IndirectCallTarget].size());
664     updateJCH((uint64_t)ValueSites[IPVK_MemOPSize].size());
665     updateJCH((uint64_t)MST.AllEdges.size());
666 
667     // Hash format for context sensitive profile. Reserve 4 bits for other
668     // information.
669     FunctionHash = (((uint64_t)JCH.getCRC()) << 28) + JC.getCRC();
670   }
671 
672   // Reserve bit 60-63 for other information purpose.
673   FunctionHash &= 0x0FFFFFFFFFFFFFFF;
674   if (IsCS)
675     NamedInstrProfRecord::setCSFlagInHash(FunctionHash);
676   LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
677                     << " CRC = " << JC.getCRC()
678                     << ", Selects = " << SIVisitor.getNumOfSelectInsts()
679                     << ", Edges = " << MST.AllEdges.size() << ", ICSites = "
680                     << ValueSites[IPVK_IndirectCallTarget].size());
681   if (!PGOOldCFGHashing) {
682     LLVM_DEBUG(dbgs() << ", Memops = " << ValueSites[IPVK_MemOPSize].size()
683                       << ", High32 CRC = " << JCH.getCRC());
684   }
685   LLVM_DEBUG(dbgs() << ", Hash = " << FunctionHash << "\n";);
686 }
687 
688 // Check if we can safely rename this Comdat function.
689 static bool canRenameComdat(
690     Function &F,
691     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
692   if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
693     return false;
694 
695   // FIXME: Current only handle those Comdat groups that only containing one
696   // function.
697   // (1) For a Comdat group containing multiple functions, we need to have a
698   // unique postfix based on the hashes for each function. There is a
699   // non-trivial code refactoring to do this efficiently.
700   // (2) Variables can not be renamed, so we can not rename Comdat function in a
701   // group including global vars.
702   Comdat *C = F.getComdat();
703   for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
704     assert(!isa<GlobalAlias>(CM.second));
705     Function *FM = dyn_cast<Function>(CM.second);
706     if (FM != &F)
707       return false;
708   }
709   return true;
710 }
711 
712 // Append the CFGHash to the Comdat function name.
713 template <class Edge, class BBInfo>
714 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
715   if (!canRenameComdat(F, ComdatMembers))
716     return;
717   std::string OrigName = F.getName().str();
718   std::string NewFuncName =
719       Twine(F.getName() + "." + Twine(FunctionHash)).str();
720   F.setName(Twine(NewFuncName));
721   GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
722   FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
723   Comdat *NewComdat;
724   Module *M = F.getParent();
725   // For AvailableExternallyLinkage functions, change the linkage to
726   // LinkOnceODR and put them into comdat. This is because after renaming, there
727   // is no backup external copy available for the function.
728   if (!F.hasComdat()) {
729     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
730     NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
731     F.setLinkage(GlobalValue::LinkOnceODRLinkage);
732     F.setComdat(NewComdat);
733     return;
734   }
735 
736   // This function belongs to a single function Comdat group.
737   Comdat *OrigComdat = F.getComdat();
738   std::string NewComdatName =
739       Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
740   NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
741   NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
742 
743   for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
744     // Must be a function.
745     cast<Function>(CM.second)->setComdat(NewComdat);
746   }
747 }
748 
749 // Collect all the BBs that will be instruments and return them in
750 // InstrumentBBs and setup InEdges/OutEdge for UseBBInfo.
751 template <class Edge, class BBInfo>
752 void FuncPGOInstrumentation<Edge, BBInfo>::getInstrumentBBs(
753     std::vector<BasicBlock *> &InstrumentBBs) {
754   // Use a worklist as we will update the vector during the iteration.
755   std::vector<Edge *> EdgeList;
756   EdgeList.reserve(MST.AllEdges.size());
757   for (auto &E : MST.AllEdges)
758     EdgeList.push_back(E.get());
759 
760   for (auto &E : EdgeList) {
761     BasicBlock *InstrBB = getInstrBB(E);
762     if (InstrBB)
763       InstrumentBBs.push_back(InstrBB);
764   }
765 
766   // Set up InEdges/OutEdges for all BBs.
767   for (auto &E : MST.AllEdges) {
768     if (E->Removed)
769       continue;
770     const BasicBlock *SrcBB = E->SrcBB;
771     const BasicBlock *DestBB = E->DestBB;
772     BBInfo &SrcInfo = getBBInfo(SrcBB);
773     BBInfo &DestInfo = getBBInfo(DestBB);
774     SrcInfo.addOutEdge(E.get());
775     DestInfo.addInEdge(E.get());
776   }
777 }
778 
779 // Given a CFG E to be instrumented, find which BB to place the instrumented
780 // code. The function will split the critical edge if necessary.
781 template <class Edge, class BBInfo>
782 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
783   if (E->InMST || E->Removed)
784     return nullptr;
785 
786   BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
787   BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
788   // For a fake edge, instrument the real BB.
789   if (SrcBB == nullptr)
790     return DestBB;
791   if (DestBB == nullptr)
792     return SrcBB;
793 
794   auto canInstrument = [](BasicBlock *BB) -> BasicBlock * {
795     // There are basic blocks (such as catchswitch) cannot be instrumented.
796     // If the returned first insertion point is the end of BB, skip this BB.
797     if (BB->getFirstInsertionPt() == BB->end())
798       return nullptr;
799     return BB;
800   };
801 
802   // Instrument the SrcBB if it has a single successor,
803   // otherwise, the DestBB if this is not a critical edge.
804   Instruction *TI = SrcBB->getTerminator();
805   if (TI->getNumSuccessors() <= 1)
806     return canInstrument(SrcBB);
807   if (!E->IsCritical)
808     return canInstrument(DestBB);
809 
810   unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
811   BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
812   if (!InstrBB) {
813     LLVM_DEBUG(
814         dbgs() << "Fail to split critical edge: not instrument this edge.\n");
815     return nullptr;
816   }
817   // For a critical edge, we have to split. Instrument the newly
818   // created BB.
819   IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++;
820   LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
821                     << " --> " << getBBInfo(DestBB).Index << "\n");
822   // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB.
823   MST.addEdge(SrcBB, InstrBB, 0);
824   // Second one: Add new edge of InstrBB->DestBB.
825   Edge &NewEdge1 = MST.addEdge(InstrBB, DestBB, 0);
826   NewEdge1.InMST = true;
827   E->Removed = true;
828 
829   return canInstrument(InstrBB);
830 }
831 
832 // When generating value profiling calls on Windows routines that make use of
833 // handler funclets for exception processing an operand bundle needs to attached
834 // to the called function. This routine will set \p OpBundles to contain the
835 // funclet information, if any is needed, that should be placed on the generated
836 // value profiling call for the value profile candidate call.
837 static void
838 populateEHOperandBundle(VPCandidateInfo &Cand,
839                         DenseMap<BasicBlock *, ColorVector> &BlockColors,
840                         SmallVectorImpl<OperandBundleDef> &OpBundles) {
841   auto *OrigCall = dyn_cast<CallBase>(Cand.AnnotatedInst);
842   if (OrigCall && !isa<IntrinsicInst>(OrigCall)) {
843     // The instrumentation call should belong to the same funclet as a
844     // non-intrinsic call, so just copy the operand bundle, if any exists.
845     Optional<OperandBundleUse> ParentFunclet =
846         OrigCall->getOperandBundle(LLVMContext::OB_funclet);
847     if (ParentFunclet)
848       OpBundles.emplace_back(OperandBundleDef(*ParentFunclet));
849   } else {
850     // Intrinsics or other instructions do not get funclet information from the
851     // front-end. Need to use the BlockColors that was computed by the routine
852     // colorEHFunclets to determine whether a funclet is needed.
853     if (!BlockColors.empty()) {
854       const ColorVector &CV = BlockColors.find(OrigCall->getParent())->second;
855       assert(CV.size() == 1 && "non-unique color for block!");
856       Instruction *EHPad = CV.front()->getFirstNonPHI();
857       if (EHPad->isEHPad())
858         OpBundles.emplace_back("funclet", EHPad);
859     }
860   }
861 }
862 
863 // Visit all edge and instrument the edges not in MST, and do value profiling.
864 // Critical edges will be split.
865 static void instrumentOneFunc(
866     Function &F, Module *M, TargetLibraryInfo &TLI, BranchProbabilityInfo *BPI,
867     BlockFrequencyInfo *BFI,
868     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
869     bool IsCS) {
870   // Split indirectbr critical edges here before computing the MST rather than
871   // later in getInstrBB() to avoid invalidating it.
872   SplitIndirectBrCriticalEdges(F, BPI, BFI);
873 
874   FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(
875       F, TLI, ComdatMembers, true, BPI, BFI, IsCS, PGOInstrumentEntry);
876   std::vector<BasicBlock *> InstrumentBBs;
877   FuncInfo.getInstrumentBBs(InstrumentBBs);
878   unsigned NumCounters =
879       InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
880 
881   uint32_t I = 0;
882   Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
883   for (auto *InstrBB : InstrumentBBs) {
884     IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
885     assert(Builder.GetInsertPoint() != InstrBB->end() &&
886            "Cannot get the Instrumentation point");
887     Builder.CreateCall(
888         Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
889         {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
890          Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
891          Builder.getInt32(I++)});
892   }
893 
894   // Now instrument select instructions:
895   FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
896                                        FuncInfo.FunctionHash);
897   assert(I == NumCounters);
898 
899   if (DisableValueProfiling)
900     return;
901 
902   NumOfPGOICall += FuncInfo.ValueSites[IPVK_IndirectCallTarget].size();
903 
904   // Intrinsic function calls do not have funclet operand bundles needed for
905   // Windows exception handling attached to them. However, if value profiling is
906   // inserted for one of these calls, then a funclet value will need to be set
907   // on the instrumentation call based on the funclet coloring.
908   DenseMap<BasicBlock *, ColorVector> BlockColors;
909   if (F.hasPersonalityFn() &&
910       isFuncletEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
911     BlockColors = colorEHFunclets(F);
912 
913   // For each VP Kind, walk the VP candidates and instrument each one.
914   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
915     unsigned SiteIndex = 0;
916     if (Kind == IPVK_MemOPSize && !PGOInstrMemOP)
917       continue;
918 
919     for (VPCandidateInfo Cand : FuncInfo.ValueSites[Kind]) {
920       LLVM_DEBUG(dbgs() << "Instrument one VP " << ValueProfKindDescr[Kind]
921                         << " site: CallSite Index = " << SiteIndex << "\n");
922 
923       IRBuilder<> Builder(Cand.InsertPt);
924       assert(Builder.GetInsertPoint() != Cand.InsertPt->getParent()->end() &&
925              "Cannot get the Instrumentation point");
926 
927       Value *ToProfile = nullptr;
928       if (Cand.V->getType()->isIntegerTy())
929         ToProfile = Builder.CreateZExtOrTrunc(Cand.V, Builder.getInt64Ty());
930       else if (Cand.V->getType()->isPointerTy())
931         ToProfile = Builder.CreatePtrToInt(Cand.V, Builder.getInt64Ty());
932       assert(ToProfile && "value profiling Value is of unexpected type");
933 
934       SmallVector<OperandBundleDef, 1> OpBundles;
935       populateEHOperandBundle(Cand, BlockColors, OpBundles);
936       Builder.CreateCall(
937           Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
938           {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
939            Builder.getInt64(FuncInfo.FunctionHash), ToProfile,
940            Builder.getInt32(Kind), Builder.getInt32(SiteIndex++)},
941           OpBundles);
942     }
943   } // IPVK_First <= Kind <= IPVK_Last
944 }
945 
946 namespace {
947 
948 // This class represents a CFG edge in profile use compilation.
949 struct PGOUseEdge : public PGOEdge {
950   bool CountValid = false;
951   uint64_t CountValue = 0;
952 
953   PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
954       : PGOEdge(Src, Dest, W) {}
955 
956   // Set edge count value
957   void setEdgeCount(uint64_t Value) {
958     CountValue = Value;
959     CountValid = true;
960   }
961 
962   // Return the information string for this object.
963   const std::string infoString() const {
964     if (!CountValid)
965       return PGOEdge::infoString();
966     return (Twine(PGOEdge::infoString()) + "  Count=" + Twine(CountValue))
967         .str();
968   }
969 };
970 
971 using DirectEdges = SmallVector<PGOUseEdge *, 2>;
972 
973 // This class stores the auxiliary information for each BB.
974 struct UseBBInfo : public BBInfo {
975   uint64_t CountValue = 0;
976   bool CountValid;
977   int32_t UnknownCountInEdge = 0;
978   int32_t UnknownCountOutEdge = 0;
979   DirectEdges InEdges;
980   DirectEdges OutEdges;
981 
982   UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
983 
984   UseBBInfo(unsigned IX, uint64_t C)
985       : BBInfo(IX), CountValue(C), CountValid(true) {}
986 
987   // Set the profile count value for this BB.
988   void setBBInfoCount(uint64_t Value) {
989     CountValue = Value;
990     CountValid = true;
991   }
992 
993   // Return the information string of this object.
994   const std::string infoString() const {
995     if (!CountValid)
996       return BBInfo::infoString();
997     return (Twine(BBInfo::infoString()) + "  Count=" + Twine(CountValue)).str();
998   }
999 
1000   // Add an OutEdge and update the edge count.
1001   void addOutEdge(PGOUseEdge *E) {
1002     OutEdges.push_back(E);
1003     UnknownCountOutEdge++;
1004   }
1005 
1006   // Add an InEdge and update the edge count.
1007   void addInEdge(PGOUseEdge *E) {
1008     InEdges.push_back(E);
1009     UnknownCountInEdge++;
1010   }
1011 };
1012 
1013 } // end anonymous namespace
1014 
1015 // Sum up the count values for all the edges.
1016 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
1017   uint64_t Total = 0;
1018   for (auto &E : Edges) {
1019     if (E->Removed)
1020       continue;
1021     Total += E->CountValue;
1022   }
1023   return Total;
1024 }
1025 
1026 namespace {
1027 
1028 class PGOUseFunc {
1029 public:
1030   PGOUseFunc(Function &Func, Module *Modu, TargetLibraryInfo &TLI,
1031              std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
1032              BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFIin,
1033              ProfileSummaryInfo *PSI, bool IsCS, bool InstrumentFuncEntry)
1034       : F(Func), M(Modu), BFI(BFIin), PSI(PSI),
1035         FuncInfo(Func, TLI, ComdatMembers, false, BPI, BFIin, IsCS,
1036                  InstrumentFuncEntry),
1037         FreqAttr(FFA_Normal), IsCS(IsCS) {}
1038 
1039   // Read counts for the instrumented BB from profile.
1040   bool readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros,
1041                     bool &AllMinusOnes);
1042 
1043   // Populate the counts for all BBs.
1044   void populateCounters();
1045 
1046   // Set the branch weights based on the count values.
1047   void setBranchWeights();
1048 
1049   // Annotate the value profile call sites for all value kind.
1050   void annotateValueSites();
1051 
1052   // Annotate the value profile call sites for one value kind.
1053   void annotateValueSites(uint32_t Kind);
1054 
1055   // Annotate the irreducible loop header weights.
1056   void annotateIrrLoopHeaderWeights();
1057 
1058   // The hotness of the function from the profile count.
1059   enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
1060 
1061   // Return the function hotness from the profile.
1062   FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
1063 
1064   // Return the function hash.
1065   uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
1066 
1067   // Return the profile record for this function;
1068   InstrProfRecord &getProfileRecord() { return ProfileRecord; }
1069 
1070   // Return the auxiliary BB information.
1071   UseBBInfo &getBBInfo(const BasicBlock *BB) const {
1072     return FuncInfo.getBBInfo(BB);
1073   }
1074 
1075   // Return the auxiliary BB information if available.
1076   UseBBInfo *findBBInfo(const BasicBlock *BB) const {
1077     return FuncInfo.findBBInfo(BB);
1078   }
1079 
1080   Function &getFunc() const { return F; }
1081 
1082   void dumpInfo(std::string Str = "") const {
1083     FuncInfo.dumpInfo(Str);
1084   }
1085 
1086   uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
1087 private:
1088   Function &F;
1089   Module *M;
1090   BlockFrequencyInfo *BFI;
1091   ProfileSummaryInfo *PSI;
1092 
1093   // This member stores the shared information with class PGOGenFunc.
1094   FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
1095 
1096   // The maximum count value in the profile. This is only used in PGO use
1097   // compilation.
1098   uint64_t ProgramMaxCount;
1099 
1100   // Position of counter that remains to be read.
1101   uint32_t CountPosition = 0;
1102 
1103   // Total size of the profile count for this function.
1104   uint32_t ProfileCountSize = 0;
1105 
1106   // ProfileRecord for this function.
1107   InstrProfRecord ProfileRecord;
1108 
1109   // Function hotness info derived from profile.
1110   FuncFreqAttr FreqAttr;
1111 
1112   // Is to use the context sensitive profile.
1113   bool IsCS;
1114 
1115   // Find the Instrumented BB and set the value. Return false on error.
1116   bool setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
1117 
1118   // Set the edge counter value for the unknown edge -- there should be only
1119   // one unknown edge.
1120   void setEdgeCount(DirectEdges &Edges, uint64_t Value);
1121 
1122   // Return FuncName string;
1123   const std::string getFuncName() const { return FuncInfo.FuncName; }
1124 
1125   // Set the hot/cold inline hints based on the count values.
1126   // FIXME: This function should be removed once the functionality in
1127   // the inliner is implemented.
1128   void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
1129     if (PSI->isHotCount(EntryCount))
1130       FreqAttr = FFA_Hot;
1131     else if (PSI->isColdCount(MaxCount))
1132       FreqAttr = FFA_Cold;
1133   }
1134 };
1135 
1136 } // end anonymous namespace
1137 
1138 // Visit all the edges and assign the count value for the instrumented
1139 // edges and the BB. Return false on error.
1140 bool PGOUseFunc::setInstrumentedCounts(
1141     const std::vector<uint64_t> &CountFromProfile) {
1142 
1143   std::vector<BasicBlock *> InstrumentBBs;
1144   FuncInfo.getInstrumentBBs(InstrumentBBs);
1145   unsigned NumCounters =
1146       InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
1147   // The number of counters here should match the number of counters
1148   // in profile. Return if they mismatch.
1149   if (NumCounters != CountFromProfile.size()) {
1150     return false;
1151   }
1152   auto *FuncEntry = &*F.begin();
1153 
1154   // Set the profile count to the Instrumented BBs.
1155   uint32_t I = 0;
1156   for (BasicBlock *InstrBB : InstrumentBBs) {
1157     uint64_t CountValue = CountFromProfile[I++];
1158     UseBBInfo &Info = getBBInfo(InstrBB);
1159     // If we reach here, we know that we have some nonzero count
1160     // values in this function. The entry count should not be 0.
1161     // Fix it if necessary.
1162     if (InstrBB == FuncEntry && CountValue == 0)
1163       CountValue = 1;
1164     Info.setBBInfoCount(CountValue);
1165   }
1166   ProfileCountSize = CountFromProfile.size();
1167   CountPosition = I;
1168 
1169   // Set the edge count and update the count of unknown edges for BBs.
1170   auto setEdgeCount = [this](PGOUseEdge *E, uint64_t Value) -> void {
1171     E->setEdgeCount(Value);
1172     this->getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1173     this->getBBInfo(E->DestBB).UnknownCountInEdge--;
1174   };
1175 
1176   // Set the profile count the Instrumented edges. There are BBs that not in
1177   // MST but not instrumented. Need to set the edge count value so that we can
1178   // populate the profile counts later.
1179   for (auto &E : FuncInfo.MST.AllEdges) {
1180     if (E->Removed || E->InMST)
1181       continue;
1182     const BasicBlock *SrcBB = E->SrcBB;
1183     UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1184 
1185     // If only one out-edge, the edge profile count should be the same as BB
1186     // profile count.
1187     if (SrcInfo.CountValid && SrcInfo.OutEdges.size() == 1)
1188       setEdgeCount(E.get(), SrcInfo.CountValue);
1189     else {
1190       const BasicBlock *DestBB = E->DestBB;
1191       UseBBInfo &DestInfo = getBBInfo(DestBB);
1192       // If only one in-edge, the edge profile count should be the same as BB
1193       // profile count.
1194       if (DestInfo.CountValid && DestInfo.InEdges.size() == 1)
1195         setEdgeCount(E.get(), DestInfo.CountValue);
1196     }
1197     if (E->CountValid)
1198       continue;
1199     // E's count should have been set from profile. If not, this meenas E skips
1200     // the instrumentation. We set the count to 0.
1201     setEdgeCount(E.get(), 0);
1202   }
1203   return true;
1204 }
1205 
1206 // Set the count value for the unknown edge. There should be one and only one
1207 // unknown edge in Edges vector.
1208 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
1209   for (auto &E : Edges) {
1210     if (E->CountValid)
1211       continue;
1212     E->setEdgeCount(Value);
1213 
1214     getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1215     getBBInfo(E->DestBB).UnknownCountInEdge--;
1216     return;
1217   }
1218   llvm_unreachable("Cannot find the unknown count edge");
1219 }
1220 
1221 // Read the profile from ProfileFileName and assign the value to the
1222 // instrumented BB and the edges. This function also updates ProgramMaxCount.
1223 // Return true if the profile are successfully read, and false on errors.
1224 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros,
1225                               bool &AllMinusOnes) {
1226   auto &Ctx = M->getContext();
1227   Expected<InstrProfRecord> Result =
1228       PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
1229   if (Error E = Result.takeError()) {
1230     handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1231       auto Err = IPE.get();
1232       bool SkipWarning = false;
1233       LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
1234                         << FuncInfo.FuncName << ": ");
1235       if (Err == instrprof_error::unknown_function) {
1236         IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++;
1237         SkipWarning = !PGOWarnMissing;
1238         LLVM_DEBUG(dbgs() << "unknown function");
1239       } else if (Err == instrprof_error::hash_mismatch ||
1240                  Err == instrprof_error::malformed) {
1241         IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++;
1242         SkipWarning =
1243             NoPGOWarnMismatch ||
1244             (NoPGOWarnMismatchComdat &&
1245              (F.hasComdat() ||
1246               F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
1247         LLVM_DEBUG(dbgs() << "hash mismatch (skip=" << SkipWarning << ")");
1248       }
1249 
1250       LLVM_DEBUG(dbgs() << " IsCS=" << IsCS << "\n");
1251       if (SkipWarning)
1252         return;
1253 
1254       std::string Msg = IPE.message() + std::string(" ") + F.getName().str() +
1255                         std::string(" Hash = ") +
1256                         std::to_string(FuncInfo.FunctionHash);
1257 
1258       Ctx.diagnose(
1259           DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1260     });
1261     return false;
1262   }
1263   ProfileRecord = std::move(Result.get());
1264   std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
1265 
1266   IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1267   LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1268   AllMinusOnes = (CountFromProfile.size() > 0);
1269   uint64_t ValueSum = 0;
1270   for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1271     LLVM_DEBUG(dbgs() << "  " << I << ": " << CountFromProfile[I] << "\n");
1272     ValueSum += CountFromProfile[I];
1273     if (CountFromProfile[I] != (uint64_t)-1)
1274       AllMinusOnes = false;
1275   }
1276   AllZeros = (ValueSum == 0);
1277 
1278   LLVM_DEBUG(dbgs() << "SUM =  " << ValueSum << "\n");
1279 
1280   getBBInfo(nullptr).UnknownCountOutEdge = 2;
1281   getBBInfo(nullptr).UnknownCountInEdge = 2;
1282 
1283   if (!setInstrumentedCounts(CountFromProfile)) {
1284     LLVM_DEBUG(
1285         dbgs() << "Inconsistent number of counts, skipping this function");
1286     Ctx.diagnose(DiagnosticInfoPGOProfile(
1287         M->getName().data(),
1288         Twine("Inconsistent number of counts in ") + F.getName().str()
1289         + Twine(": the profile may be stale or there is a function name collision."),
1290         DS_Warning));
1291     return false;
1292   }
1293   ProgramMaxCount = PGOReader->getMaximumFunctionCount(IsCS);
1294   return true;
1295 }
1296 
1297 // Populate the counters from instrumented BBs to all BBs.
1298 // In the end of this operation, all BBs should have a valid count value.
1299 void PGOUseFunc::populateCounters() {
1300   bool Changes = true;
1301   unsigned NumPasses = 0;
1302   while (Changes) {
1303     NumPasses++;
1304     Changes = false;
1305 
1306     // For efficient traversal, it's better to start from the end as most
1307     // of the instrumented edges are at the end.
1308     for (auto &BB : reverse(F)) {
1309       UseBBInfo *Count = findBBInfo(&BB);
1310       if (Count == nullptr)
1311         continue;
1312       if (!Count->CountValid) {
1313         if (Count->UnknownCountOutEdge == 0) {
1314           Count->CountValue = sumEdgeCount(Count->OutEdges);
1315           Count->CountValid = true;
1316           Changes = true;
1317         } else if (Count->UnknownCountInEdge == 0) {
1318           Count->CountValue = sumEdgeCount(Count->InEdges);
1319           Count->CountValid = true;
1320           Changes = true;
1321         }
1322       }
1323       if (Count->CountValid) {
1324         if (Count->UnknownCountOutEdge == 1) {
1325           uint64_t Total = 0;
1326           uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1327           // If the one of the successor block can early terminate (no-return),
1328           // we can end up with situation where out edge sum count is larger as
1329           // the source BB's count is collected by a post-dominated block.
1330           if (Count->CountValue > OutSum)
1331             Total = Count->CountValue - OutSum;
1332           setEdgeCount(Count->OutEdges, Total);
1333           Changes = true;
1334         }
1335         if (Count->UnknownCountInEdge == 1) {
1336           uint64_t Total = 0;
1337           uint64_t InSum = sumEdgeCount(Count->InEdges);
1338           if (Count->CountValue > InSum)
1339             Total = Count->CountValue - InSum;
1340           setEdgeCount(Count->InEdges, Total);
1341           Changes = true;
1342         }
1343       }
1344     }
1345   }
1346 
1347   LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
1348 #ifndef NDEBUG
1349   // Assert every BB has a valid counter.
1350   for (auto &BB : F) {
1351     auto BI = findBBInfo(&BB);
1352     if (BI == nullptr)
1353       continue;
1354     assert(BI->CountValid && "BB count is not valid");
1355   }
1356 #endif
1357   uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
1358   uint64_t FuncMaxCount = FuncEntryCount;
1359   for (auto &BB : F) {
1360     auto BI = findBBInfo(&BB);
1361     if (BI == nullptr)
1362       continue;
1363     FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1364   }
1365 
1366   // Fix the obviously inconsistent entry count.
1367   if (FuncMaxCount > 0 && FuncEntryCount == 0)
1368     FuncEntryCount = 1;
1369   F.setEntryCount(ProfileCount(FuncEntryCount, Function::PCT_Real));
1370   markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1371 
1372   // Now annotate select instructions
1373   FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1374   assert(CountPosition == ProfileCountSize);
1375 
1376   LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
1377 }
1378 
1379 // Assign the scaled count values to the BB with multiple out edges.
1380 void PGOUseFunc::setBranchWeights() {
1381   // Generate MD_prof metadata for every branch instruction.
1382   LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F.getName()
1383                     << " IsCS=" << IsCS << "\n");
1384   for (auto &BB : F) {
1385     Instruction *TI = BB.getTerminator();
1386     if (TI->getNumSuccessors() < 2)
1387       continue;
1388     if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1389           isa<IndirectBrInst>(TI) || isa<InvokeInst>(TI)))
1390       continue;
1391 
1392     if (getBBInfo(&BB).CountValue == 0)
1393       continue;
1394 
1395     // We have a non-zero Branch BB.
1396     const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1397     unsigned Size = BBCountInfo.OutEdges.size();
1398     SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
1399     uint64_t MaxCount = 0;
1400     for (unsigned s = 0; s < Size; s++) {
1401       const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1402       const BasicBlock *SrcBB = E->SrcBB;
1403       const BasicBlock *DestBB = E->DestBB;
1404       if (DestBB == nullptr)
1405         continue;
1406       unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1407       uint64_t EdgeCount = E->CountValue;
1408       if (EdgeCount > MaxCount)
1409         MaxCount = EdgeCount;
1410       EdgeCounts[SuccNum] = EdgeCount;
1411     }
1412     setProfMetadata(M, TI, EdgeCounts, MaxCount);
1413   }
1414 }
1415 
1416 static bool isIndirectBrTarget(BasicBlock *BB) {
1417   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1418     if (isa<IndirectBrInst>((*PI)->getTerminator()))
1419       return true;
1420   }
1421   return false;
1422 }
1423 
1424 void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1425   LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1426   // Find irr loop headers
1427   for (auto &BB : F) {
1428     // As a heuristic also annotate indrectbr targets as they have a high chance
1429     // to become an irreducible loop header after the indirectbr tail
1430     // duplication.
1431     if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
1432       Instruction *TI = BB.getTerminator();
1433       const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1434       setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1435     }
1436   }
1437 }
1438 
1439 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1440   Module *M = F.getParent();
1441   IRBuilder<> Builder(&SI);
1442   Type *Int64Ty = Builder.getInt64Ty();
1443   Type *I8PtrTy = Builder.getInt8PtrTy();
1444   auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1445   Builder.CreateCall(
1446       Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1447       {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1448        Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1449        Builder.getInt32(*CurCtrIdx), Step});
1450   ++(*CurCtrIdx);
1451 }
1452 
1453 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1454   std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1455   assert(*CurCtrIdx < CountFromProfile.size() &&
1456          "Out of bound access of counters");
1457   uint64_t SCounts[2];
1458   SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1459   ++(*CurCtrIdx);
1460   uint64_t TotalCount = 0;
1461   auto BI = UseFunc->findBBInfo(SI.getParent());
1462   if (BI != nullptr)
1463     TotalCount = BI->CountValue;
1464   // False Count
1465   SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1466   uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1467   if (MaxCount)
1468     setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
1469 }
1470 
1471 void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1472   if (!PGOInstrSelect)
1473     return;
1474   // FIXME: do not handle this yet.
1475   if (SI.getCondition()->getType()->isVectorTy())
1476     return;
1477 
1478   switch (Mode) {
1479   case VM_counting:
1480     NSIs++;
1481     return;
1482   case VM_instrument:
1483     instrumentOneSelectInst(SI);
1484     return;
1485   case VM_annotate:
1486     annotateOneSelectInst(SI);
1487     return;
1488   }
1489 
1490   llvm_unreachable("Unknown visiting mode");
1491 }
1492 
1493 // Traverse all valuesites and annotate the instructions for all value kind.
1494 void PGOUseFunc::annotateValueSites() {
1495   if (DisableValueProfiling)
1496     return;
1497 
1498   // Create the PGOFuncName meta data.
1499   createPGOFuncNameMetadata(F, FuncInfo.FuncName);
1500 
1501   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1502     annotateValueSites(Kind);
1503 }
1504 
1505 // Annotate the instructions for a specific value kind.
1506 void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1507   assert(Kind <= IPVK_Last);
1508   unsigned ValueSiteIndex = 0;
1509   auto &ValueSites = FuncInfo.ValueSites[Kind];
1510   unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1511   if (NumValueSites != ValueSites.size()) {
1512     auto &Ctx = M->getContext();
1513     Ctx.diagnose(DiagnosticInfoPGOProfile(
1514         M->getName().data(),
1515         Twine("Inconsistent number of value sites for ") +
1516             Twine(ValueProfKindDescr[Kind]) +
1517             Twine(" profiling in \"") + F.getName().str() +
1518             Twine("\", possibly due to the use of a stale profile."),
1519         DS_Warning));
1520     return;
1521   }
1522 
1523   for (VPCandidateInfo &I : ValueSites) {
1524     LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1525                       << "): Index = " << ValueSiteIndex << " out of "
1526                       << NumValueSites << "\n");
1527     annotateValueSite(*M, *I.AnnotatedInst, ProfileRecord,
1528                       static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1529                       Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1530                                              : MaxNumAnnotations);
1531     ValueSiteIndex++;
1532   }
1533 }
1534 
1535 // Collect the set of members for each Comdat in module M and store
1536 // in ComdatMembers.
1537 static void collectComdatMembers(
1538     Module &M,
1539     std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1540   if (!DoComdatRenaming)
1541     return;
1542   for (Function &F : M)
1543     if (Comdat *C = F.getComdat())
1544       ComdatMembers.insert(std::make_pair(C, &F));
1545   for (GlobalVariable &GV : M.globals())
1546     if (Comdat *C = GV.getComdat())
1547       ComdatMembers.insert(std::make_pair(C, &GV));
1548   for (GlobalAlias &GA : M.aliases())
1549     if (Comdat *C = GA.getComdat())
1550       ComdatMembers.insert(std::make_pair(C, &GA));
1551 }
1552 
1553 static bool InstrumentAllFunctions(
1554     Module &M, function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
1555     function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1556     function_ref<BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS) {
1557   // For the context-sensitve instrumentation, we should have a separated pass
1558   // (before LTO/ThinLTO linking) to create these variables.
1559   if (!IsCS)
1560     createIRLevelProfileFlagVar(M, /* IsCS */ false, PGOInstrumentEntry);
1561   std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1562   collectComdatMembers(M, ComdatMembers);
1563 
1564   for (auto &F : M) {
1565     if (F.isDeclaration())
1566       continue;
1567     auto &TLI = LookupTLI(F);
1568     auto *BPI = LookupBPI(F);
1569     auto *BFI = LookupBFI(F);
1570     instrumentOneFunc(F, &M, TLI, BPI, BFI, ComdatMembers, IsCS);
1571   }
1572   return true;
1573 }
1574 
1575 PreservedAnalyses
1576 PGOInstrumentationGenCreateVar::run(Module &M, ModuleAnalysisManager &AM) {
1577   createProfileFileNameVar(M, CSInstrName);
1578   createIRLevelProfileFlagVar(M, /* IsCS */ true, PGOInstrumentEntry);
1579   return PreservedAnalyses::all();
1580 }
1581 
1582 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
1583   if (skipModule(M))
1584     return false;
1585 
1586   auto LookupTLI = [this](Function &F) -> TargetLibraryInfo & {
1587     return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1588   };
1589   auto LookupBPI = [this](Function &F) {
1590     return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1591   };
1592   auto LookupBFI = [this](Function &F) {
1593     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1594   };
1595   return InstrumentAllFunctions(M, LookupTLI, LookupBPI, LookupBFI, IsCS);
1596 }
1597 
1598 PreservedAnalyses PGOInstrumentationGen::run(Module &M,
1599                                              ModuleAnalysisManager &AM) {
1600   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1601   auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
1602     return FAM.getResult<TargetLibraryAnalysis>(F);
1603   };
1604   auto LookupBPI = [&FAM](Function &F) {
1605     return &FAM.getResult<BranchProbabilityAnalysis>(F);
1606   };
1607   auto LookupBFI = [&FAM](Function &F) {
1608     return &FAM.getResult<BlockFrequencyAnalysis>(F);
1609   };
1610 
1611   if (!InstrumentAllFunctions(M, LookupTLI, LookupBPI, LookupBFI, IsCS))
1612     return PreservedAnalyses::all();
1613 
1614   return PreservedAnalyses::none();
1615 }
1616 
1617 static bool annotateAllFunctions(
1618     Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName,
1619     function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
1620     function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1621     function_ref<BlockFrequencyInfo *(Function &)> LookupBFI,
1622     ProfileSummaryInfo *PSI, bool IsCS) {
1623   LLVM_DEBUG(dbgs() << "Read in profile counters: ");
1624   auto &Ctx = M.getContext();
1625   // Read the counter array from file.
1626   auto ReaderOrErr =
1627       IndexedInstrProfReader::create(ProfileFileName, ProfileRemappingFileName);
1628   if (Error E = ReaderOrErr.takeError()) {
1629     handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1630       Ctx.diagnose(
1631           DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1632     });
1633     return false;
1634   }
1635 
1636   std::unique_ptr<IndexedInstrProfReader> PGOReader =
1637       std::move(ReaderOrErr.get());
1638   if (!PGOReader) {
1639     Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
1640                                           StringRef("Cannot get PGOReader")));
1641     return false;
1642   }
1643   if (!PGOReader->hasCSIRLevelProfile() && IsCS)
1644     return false;
1645 
1646   // TODO: might need to change the warning once the clang option is finalized.
1647   if (!PGOReader->isIRLevelProfile()) {
1648     Ctx.diagnose(DiagnosticInfoPGOProfile(
1649         ProfileFileName.data(), "Not an IR level instrumentation profile"));
1650     return false;
1651   }
1652 
1653   // Add the profile summary (read from the header of the indexed summary) here
1654   // so that we can use it below when reading counters (which checks if the
1655   // function should be marked with a cold or inlinehint attribute).
1656   M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()),
1657                       IsCS ? ProfileSummary::PSK_CSInstr
1658                            : ProfileSummary::PSK_Instr);
1659   PSI->refresh();
1660 
1661   std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1662   collectComdatMembers(M, ComdatMembers);
1663   std::vector<Function *> HotFunctions;
1664   std::vector<Function *> ColdFunctions;
1665 
1666   // If the profile marked as always instrument the entry BB, do the
1667   // same. Note this can be overwritten by the internal option in CFGMST.h
1668   bool InstrumentFuncEntry = PGOReader->instrEntryBBEnabled();
1669   if (PGOInstrumentEntry.getNumOccurrences() > 0)
1670     InstrumentFuncEntry = PGOInstrumentEntry;
1671   for (auto &F : M) {
1672     if (F.isDeclaration())
1673       continue;
1674     auto &TLI = LookupTLI(F);
1675     auto *BPI = LookupBPI(F);
1676     auto *BFI = LookupBFI(F);
1677     // Split indirectbr critical edges here before computing the MST rather than
1678     // later in getInstrBB() to avoid invalidating it.
1679     SplitIndirectBrCriticalEdges(F, BPI, BFI);
1680     PGOUseFunc Func(F, &M, TLI, ComdatMembers, BPI, BFI, PSI, IsCS,
1681                     InstrumentFuncEntry);
1682     // When AllMinusOnes is true, it means the profile for the function
1683     // is unrepresentative and this function is actually hot. Set the
1684     // entry count of the function to be multiple times of hot threshold
1685     // and drop all its internal counters.
1686     bool AllMinusOnes = false;
1687     bool AllZeros = false;
1688     if (!Func.readCounters(PGOReader.get(), AllZeros, AllMinusOnes))
1689       continue;
1690     if (AllZeros) {
1691       F.setEntryCount(ProfileCount(0, Function::PCT_Real));
1692       if (Func.getProgramMaxCount() != 0)
1693         ColdFunctions.push_back(&F);
1694       continue;
1695     }
1696     const unsigned MultiplyFactor = 3;
1697     if (AllMinusOnes) {
1698       uint64_t HotThreshold = PSI->getHotCountThreshold();
1699       if (HotThreshold)
1700         F.setEntryCount(
1701             ProfileCount(HotThreshold * MultiplyFactor, Function::PCT_Real));
1702       HotFunctions.push_back(&F);
1703       continue;
1704     }
1705     Func.populateCounters();
1706     Func.setBranchWeights();
1707     Func.annotateValueSites();
1708     Func.annotateIrrLoopHeaderWeights();
1709     PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1710     if (FreqAttr == PGOUseFunc::FFA_Cold)
1711       ColdFunctions.push_back(&F);
1712     else if (FreqAttr == PGOUseFunc::FFA_Hot)
1713       HotFunctions.push_back(&F);
1714     if (PGOViewCounts != PGOVCT_None &&
1715         (ViewBlockFreqFuncName.empty() ||
1716          F.getName().equals(ViewBlockFreqFuncName))) {
1717       LoopInfo LI{DominatorTree(F)};
1718       std::unique_ptr<BranchProbabilityInfo> NewBPI =
1719           std::make_unique<BranchProbabilityInfo>(F, LI);
1720       std::unique_ptr<BlockFrequencyInfo> NewBFI =
1721           std::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1722       if (PGOViewCounts == PGOVCT_Graph)
1723         NewBFI->view();
1724       else if (PGOViewCounts == PGOVCT_Text) {
1725         dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1726         NewBFI->print(dbgs());
1727       }
1728     }
1729     if (PGOViewRawCounts != PGOVCT_None &&
1730         (ViewBlockFreqFuncName.empty() ||
1731          F.getName().equals(ViewBlockFreqFuncName))) {
1732       if (PGOViewRawCounts == PGOVCT_Graph)
1733         if (ViewBlockFreqFuncName.empty())
1734           WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1735         else
1736           ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1737       else if (PGOViewRawCounts == PGOVCT_Text) {
1738         dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1739         Func.dumpInfo();
1740       }
1741     }
1742   }
1743 
1744   // Set function hotness attribute from the profile.
1745   // We have to apply these attributes at the end because their presence
1746   // can affect the BranchProbabilityInfo of any callers, resulting in an
1747   // inconsistent MST between prof-gen and prof-use.
1748   for (auto &F : HotFunctions) {
1749     F->addFnAttr(Attribute::InlineHint);
1750     LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1751                       << "\n");
1752   }
1753   for (auto &F : ColdFunctions) {
1754     F->addFnAttr(Attribute::Cold);
1755     LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
1756                       << "\n");
1757   }
1758   return true;
1759 }
1760 
1761 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename,
1762                                              std::string RemappingFilename,
1763                                              bool IsCS)
1764     : ProfileFileName(std::move(Filename)),
1765       ProfileRemappingFileName(std::move(RemappingFilename)), IsCS(IsCS) {
1766   if (!PGOTestProfileFile.empty())
1767     ProfileFileName = PGOTestProfileFile;
1768   if (!PGOTestProfileRemappingFile.empty())
1769     ProfileRemappingFileName = PGOTestProfileRemappingFile;
1770 }
1771 
1772 PreservedAnalyses PGOInstrumentationUse::run(Module &M,
1773                                              ModuleAnalysisManager &AM) {
1774 
1775   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1776   auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
1777     return FAM.getResult<TargetLibraryAnalysis>(F);
1778   };
1779   auto LookupBPI = [&FAM](Function &F) {
1780     return &FAM.getResult<BranchProbabilityAnalysis>(F);
1781   };
1782   auto LookupBFI = [&FAM](Function &F) {
1783     return &FAM.getResult<BlockFrequencyAnalysis>(F);
1784   };
1785 
1786   auto *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
1787 
1788   if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName,
1789                             LookupTLI, LookupBPI, LookupBFI, PSI, IsCS))
1790     return PreservedAnalyses::all();
1791 
1792   return PreservedAnalyses::none();
1793 }
1794 
1795 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1796   if (skipModule(M))
1797     return false;
1798 
1799   auto LookupTLI = [this](Function &F) -> TargetLibraryInfo & {
1800     return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1801   };
1802   auto LookupBPI = [this](Function &F) {
1803     return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1804   };
1805   auto LookupBFI = [this](Function &F) {
1806     return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1807   };
1808 
1809   auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1810   return annotateAllFunctions(M, ProfileFileName, "", LookupTLI, LookupBPI,
1811                               LookupBFI, PSI, IsCS);
1812 }
1813 
1814 static std::string getSimpleNodeName(const BasicBlock *Node) {
1815   if (!Node->getName().empty())
1816     return std::string(Node->getName());
1817 
1818   std::string SimpleNodeName;
1819   raw_string_ostream OS(SimpleNodeName);
1820   Node->printAsOperand(OS, false);
1821   return OS.str();
1822 }
1823 
1824 void llvm::setProfMetadata(Module *M, Instruction *TI,
1825                            ArrayRef<uint64_t> EdgeCounts,
1826                            uint64_t MaxCount) {
1827   MDBuilder MDB(M->getContext());
1828   assert(MaxCount > 0 && "Bad max count");
1829   uint64_t Scale = calculateCountScale(MaxCount);
1830   SmallVector<unsigned, 4> Weights;
1831   for (const auto &ECI : EdgeCounts)
1832     Weights.push_back(scaleBranchCount(ECI, Scale));
1833 
1834   LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W
1835                                            : Weights) {
1836     dbgs() << W << " ";
1837   } dbgs() << "\n";);
1838 
1839   misexpect::verifyMisExpect(TI, Weights, TI->getContext());
1840 
1841   TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1842   if (EmitBranchProbability) {
1843     std::string BrCondStr = getBranchCondString(TI);
1844     if (BrCondStr.empty())
1845       return;
1846 
1847     uint64_t WSum =
1848         std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
1849                         [](uint64_t w1, uint64_t w2) { return w1 + w2; });
1850     uint64_t TotalCount =
1851         std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
1852                         [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1853     Scale = calculateCountScale(WSum);
1854     BranchProbability BP(scaleBranchCount(Weights[0], Scale),
1855                          scaleBranchCount(WSum, Scale));
1856     std::string BranchProbStr;
1857     raw_string_ostream OS(BranchProbStr);
1858     OS << BP;
1859     OS << " (total count : " << TotalCount << ")";
1860     OS.flush();
1861     Function *F = TI->getParent()->getParent();
1862     OptimizationRemarkEmitter ORE(F);
1863     ORE.emit([&]() {
1864       return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1865              << BrCondStr << " is true with probability : " << BranchProbStr;
1866     });
1867   }
1868 }
1869 
1870 namespace llvm {
1871 
1872 void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1873   MDBuilder MDB(M->getContext());
1874   TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1875                   MDB.createIrrLoopHeaderWeight(Count));
1876 }
1877 
1878 template <> struct GraphTraits<PGOUseFunc *> {
1879   using NodeRef = const BasicBlock *;
1880   using ChildIteratorType = const_succ_iterator;
1881   using nodes_iterator = pointer_iterator<Function::const_iterator>;
1882 
1883   static NodeRef getEntryNode(const PGOUseFunc *G) {
1884     return &G->getFunc().front();
1885   }
1886 
1887   static ChildIteratorType child_begin(const NodeRef N) {
1888     return succ_begin(N);
1889   }
1890 
1891   static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1892 
1893   static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1894     return nodes_iterator(G->getFunc().begin());
1895   }
1896 
1897   static nodes_iterator nodes_end(const PGOUseFunc *G) {
1898     return nodes_iterator(G->getFunc().end());
1899   }
1900 };
1901 
1902 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1903   explicit DOTGraphTraits(bool isSimple = false)
1904       : DefaultDOTGraphTraits(isSimple) {}
1905 
1906   static std::string getGraphName(const PGOUseFunc *G) {
1907     return std::string(G->getFunc().getName());
1908   }
1909 
1910   std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1911     std::string Result;
1912     raw_string_ostream OS(Result);
1913 
1914     OS << getSimpleNodeName(Node) << ":\\l";
1915     UseBBInfo *BI = Graph->findBBInfo(Node);
1916     OS << "Count : ";
1917     if (BI && BI->CountValid)
1918       OS << BI->CountValue << "\\l";
1919     else
1920       OS << "Unknown\\l";
1921 
1922     if (!PGOInstrSelect)
1923       return Result;
1924 
1925     for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1926       auto *I = &*BI;
1927       if (!isa<SelectInst>(I))
1928         continue;
1929       // Display scaled counts for SELECT instruction:
1930       OS << "SELECT : { T = ";
1931       uint64_t TC, FC;
1932       bool HasProf = I->extractProfMetadata(TC, FC);
1933       if (!HasProf)
1934         OS << "Unknown, F = Unknown }\\l";
1935       else
1936         OS << TC << ", F = " << FC << " }\\l";
1937     }
1938     return Result;
1939   }
1940 };
1941 
1942 } // end namespace llvm
1943