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