LLVM  10.0.0svn
PGOInstrumentation.cpp
Go to the documentation of this file.
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 "CFGMST.h"
51 #include "llvm/ADT/APInt.h"
52 #include "llvm/ADT/ArrayRef.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/Triple.h"
58 #include "llvm/ADT/Twine.h"
59 #include "llvm/ADT/iterator.h"
63 #include "llvm/Analysis/CFG.h"
65 #include "llvm/Analysis/LoopInfo.h"
68 #include "llvm/IR/Attributes.h"
69 #include "llvm/IR/BasicBlock.h"
70 #include "llvm/IR/CFG.h"
71 #include "llvm/IR/CallSite.h"
72 #include "llvm/IR/Comdat.h"
73 #include "llvm/IR/Constant.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DiagnosticInfo.h"
76 #include "llvm/IR/Dominators.h"
77 #include "llvm/IR/Function.h"
78 #include "llvm/IR/GlobalAlias.h"
79 #include "llvm/IR/GlobalValue.h"
80 #include "llvm/IR/GlobalVariable.h"
81 #include "llvm/IR/IRBuilder.h"
82 #include "llvm/IR/InstVisitor.h"
83 #include "llvm/IR/InstrTypes.h"
84 #include "llvm/IR/Instruction.h"
85 #include "llvm/IR/Instructions.h"
86 #include "llvm/IR/IntrinsicInst.h"
87 #include "llvm/IR/Intrinsics.h"
88 #include "llvm/IR/LLVMContext.h"
89 #include "llvm/IR/MDBuilder.h"
90 #include "llvm/IR/Module.h"
91 #include "llvm/IR/PassManager.h"
92 #include "llvm/IR/ProfileSummary.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/Pass.h"
99 #include "llvm/Support/Casting.h"
102 #include "llvm/Support/Debug.h"
103 #include "llvm/Support/Error.h"
106 #include "llvm/Support/JamCRC.h"
112 #include <algorithm>
113 #include <cassert>
114 #include <cstdint>
115 #include <memory>
116 #include <numeric>
117 #include <string>
118 #include <unordered_map>
119 #include <utility>
120 #include <vector>
121 
122 using namespace llvm;
124 
125 #define DEBUG_TYPE "pgo-instrumentation"
126 
127 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
128 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
129 STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
130 STATISTIC(NumOfPGOEdge, "Number of edges.");
131 STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
132 STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
133 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
134 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
135 STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
136 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
137 STATISTIC(NumOfCSPGOInstrument, "Number of edges instrumented in CSPGO.");
138 STATISTIC(NumOfCSPGOSelectInsts,
139  "Number of select instruction instrumented in CSPGO.");
140 STATISTIC(NumOfCSPGOMemIntrinsics,
141  "Number of mem intrinsics instrumented in CSPGO.");
142 STATISTIC(NumOfCSPGOEdge, "Number of edges in CSPGO.");
143 STATISTIC(NumOfCSPGOBB, "Number of basic-blocks in CSPGO.");
144 STATISTIC(NumOfCSPGOSplit, "Number of critical edge splits in CSPGO.");
145 STATISTIC(NumOfCSPGOFunc,
146  "Number of functions having valid profile counts in CSPGO.");
147 STATISTIC(NumOfCSPGOMismatch,
148  "Number of functions having mismatch profile in CSPGO.");
149 STATISTIC(NumOfCSPGOMissing, "Number of functions without profile in CSPGO.");
150 
151 // Command line option to specify the file to read profile from. This is
152 // mainly used for testing.
154  PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
155  cl::value_desc("filename"),
156  cl::desc("Specify the path of profile data file. This is"
157  "mainly for test purpose."));
159  "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden,
160  cl::value_desc("filename"),
161  cl::desc("Specify the path of profile remapping file. This is mainly for "
162  "test purpose."));
163 
164 // Command line option to disable value profiling. The default is false:
165 // i.e. value profiling is enabled by default. This is for debug purpose.
166 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
167  cl::Hidden,
168  cl::desc("Disable Value Profiling"));
169 
170 // Command line option to set the maximum number of VP annotations to write to
171 // the metadata for a single indirect call callsite.
173  "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
174  cl::desc("Max number of annotations for a single indirect "
175  "call callsite"));
176 
177 // Command line option to set the maximum number of value annotations
178 // to write to the metadata for a single memop intrinsic.
180  "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
181  cl::desc("Max number of preicise value annotations for a single memop"
182  "intrinsic"));
183 
184 // Command line option to control appending FunctionHash to the name of a COMDAT
185 // function. This is to avoid the hash mismatch caused by the preinliner.
187  "do-comdat-renaming", cl::init(false), cl::Hidden,
188  cl::desc("Append function hash to the name of COMDAT function to avoid "
189  "function hash mismatch due to the preinliner"));
190 
191 // Command line option to enable/disable the warning about missing profile
192 // information.
193 static cl::opt<bool>
194  PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
195  cl::desc("Use this option to turn on/off "
196  "warnings about missing profile data for "
197  "functions."));
198 
199 // Command line option to enable/disable the warning about a hash mismatch in
200 // the profile data.
201 static cl::opt<bool>
202  NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
203  cl::desc("Use this option to turn off/on "
204  "warnings about profile cfg mismatch."));
205 
206 // Command line option to enable/disable the warning about a hash mismatch in
207 // the profile data for Comdat functions, which often turns out to be false
208 // positive due to the pre-instrumentation inline.
209 static cl::opt<bool>
210  NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
211  cl::Hidden,
212  cl::desc("The option is used to turn on/off "
213  "warnings about hash mismatch for comdat "
214  "functions."));
215 
216 // Command line option to enable/disable select instruction instrumentation.
217 static cl::opt<bool>
218  PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
219  cl::desc("Use this option to turn on/off SELECT "
220  "instruction instrumentation. "));
221 
222 // Command line option to turn on CFG dot or text dump of raw profile counts
224  "pgo-view-raw-counts", cl::Hidden,
225  cl::desc("A boolean option to show CFG dag or text "
226  "with raw profile counts from "
227  "profile data. See also option "
228  "-pgo-view-counts. To limit graph "
229  "display to only one function, use "
230  "filtering option -view-bfi-func-name."),
231  cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
232  clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
233  clEnumValN(PGOVCT_Text, "text", "show in text.")));
234 
235 // Command line option to enable/disable memop intrinsic call.size profiling.
236 static cl::opt<bool>
237  PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
238  cl::desc("Use this option to turn on/off "
239  "memory intrinsic size profiling."));
240 
241 // Emit branch probability as optimization remarks.
242 static cl::opt<bool>
243  EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
244  cl::desc("When this option is on, the annotated "
245  "branch probability will be emitted as "
246  "optimization remarks: -{Rpass|"
247  "pass-remarks}=pgo-instrumentation"));
248 
249 // Command line option to turn on CFG dot dump after profile annotation.
250 // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
252 
253 // Command line option to specify the name of the function for CFG dump
254 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
256 
257 // Return a string describing the branch condition that can be
258 // used in static branch probability heuristics:
259 static std::string getBranchCondString(Instruction *TI) {
260  BranchInst *BI = dyn_cast<BranchInst>(TI);
261  if (!BI || !BI->isConditional())
262  return std::string();
263 
264  Value *Cond = BI->getCondition();
265  ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
266  if (!CI)
267  return std::string();
268 
269  std::string result;
270  raw_string_ostream OS(result);
271  OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
272  CI->getOperand(0)->getType()->print(OS, true);
273 
274  Value *RHS = CI->getOperand(1);
275  ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
276  if (CV) {
277  if (CV->isZero())
278  OS << "_Zero";
279  else if (CV->isOne())
280  OS << "_One";
281  else if (CV->isMinusOne())
282  OS << "_MinusOne";
283  else
284  OS << "_Const";
285  }
286  OS.flush();
287  return result;
288 }
289 
290 namespace {
291 
292 /// The select instruction visitor plays three roles specified
293 /// by the mode. In \c VM_counting mode, it simply counts the number of
294 /// select instructions. In \c VM_instrument mode, it inserts code to count
295 /// the number times TrueValue of select is taken. In \c VM_annotate mode,
296 /// it reads the profile data and annotate the select instruction with metadata.
297 enum VisitMode { VM_counting, VM_instrument, VM_annotate };
298 class PGOUseFunc;
299 
300 /// Instruction Visitor class to visit select instructions.
301 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
302  Function &F;
303  unsigned NSIs = 0; // Number of select instructions instrumented.
304  VisitMode Mode = VM_counting; // Visiting mode.
305  unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
306  unsigned TotalNumCtrs = 0; // Total number of counters
307  GlobalVariable *FuncNameVar = nullptr;
308  uint64_t FuncHash = 0;
309  PGOUseFunc *UseFunc = nullptr;
310 
311  SelectInstVisitor(Function &Func) : F(Func) {}
312 
313  void countSelects(Function &Func) {
314  NSIs = 0;
315  Mode = VM_counting;
316  visit(Func);
317  }
318 
319  // Visit the IR stream and instrument all select instructions. \p
320  // Ind is a pointer to the counter index variable; \p TotalNC
321  // is the total number of counters; \p FNV is the pointer to the
322  // PGO function name var; \p FHash is the function hash.
323  void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
324  GlobalVariable *FNV, uint64_t FHash) {
325  Mode = VM_instrument;
326  CurCtrIdx = Ind;
327  TotalNumCtrs = TotalNC;
328  FuncHash = FHash;
329  FuncNameVar = FNV;
330  visit(Func);
331  }
332 
333  // Visit the IR stream and annotate all select instructions.
334  void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
335  Mode = VM_annotate;
336  UseFunc = UF;
337  CurCtrIdx = Ind;
338  visit(Func);
339  }
340 
341  void instrumentOneSelectInst(SelectInst &SI);
342  void annotateOneSelectInst(SelectInst &SI);
343 
344  // Visit \p SI instruction and perform tasks according to visit mode.
345  void visitSelectInst(SelectInst &SI);
346 
347  // Return the number of select instructions. This needs be called after
348  // countSelects().
349  unsigned getNumOfSelectInsts() const { return NSIs; }
350 };
351 
352 /// Instruction Visitor class to visit memory intrinsic calls.
353 struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
354  Function &F;
355  unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
356  VisitMode Mode = VM_counting; // Visiting mode.
357  unsigned CurCtrId = 0; // Current counter index.
358  unsigned TotalNumCtrs = 0; // Total number of counters
359  GlobalVariable *FuncNameVar = nullptr;
360  uint64_t FuncHash = 0;
361  PGOUseFunc *UseFunc = nullptr;
362  std::vector<Instruction *> Candidates;
363 
364  MemIntrinsicVisitor(Function &Func) : F(Func) {}
365 
366  void countMemIntrinsics(Function &Func) {
367  NMemIs = 0;
368  Mode = VM_counting;
369  visit(Func);
370  }
371 
372  void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
373  GlobalVariable *FNV, uint64_t FHash) {
374  Mode = VM_instrument;
375  TotalNumCtrs = TotalNC;
376  FuncHash = FHash;
377  FuncNameVar = FNV;
378  visit(Func);
379  }
380 
381  std::vector<Instruction *> findMemIntrinsics(Function &Func) {
382  Candidates.clear();
383  Mode = VM_annotate;
384  visit(Func);
385  return Candidates;
386  }
387 
388  // Visit the IR stream and annotate all mem intrinsic call instructions.
389  void instrumentOneMemIntrinsic(MemIntrinsic &MI);
390 
391  // Visit \p MI instruction and perform tasks according to visit mode.
392  void visitMemIntrinsic(MemIntrinsic &SI);
393 
394  unsigned getNumOfMemIntrinsics() const { return NMemIs; }
395 };
396 
397 class PGOInstrumentationGenLegacyPass : public ModulePass {
398 public:
399  static char ID;
400 
401  PGOInstrumentationGenLegacyPass(bool IsCS = false)
402  : ModulePass(ID), IsCS(IsCS) {
405  }
406 
407  StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
408 
409 private:
410  // Is this is context-sensitive instrumentation.
411  bool IsCS;
412  bool runOnModule(Module &M) override;
413 
414  void getAnalysisUsage(AnalysisUsage &AU) const override {
416  }
417 };
418 
419 class PGOInstrumentationUseLegacyPass : public ModulePass {
420 public:
421  static char ID;
422 
423  // Provide the profile filename as the parameter.
424  PGOInstrumentationUseLegacyPass(std::string Filename = "", bool IsCS = false)
425  : ModulePass(ID), ProfileFileName(std::move(Filename)), IsCS(IsCS) {
426  if (!PGOTestProfileFile.empty())
427  ProfileFileName = PGOTestProfileFile;
430  }
431 
432  StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
433 
434 private:
435  std::string ProfileFileName;
436  // Is this is context-sensitive instrumentation use.
437  bool IsCS;
438 
439  bool runOnModule(Module &M) override;
440 
441  void getAnalysisUsage(AnalysisUsage &AU) const override {
444  }
445 };
446 
447 class PGOInstrumentationGenCreateVarLegacyPass : public ModulePass {
448 public:
449  static char ID;
450  StringRef getPassName() const override {
451  return "PGOInstrumentationGenCreateVarPass";
452  }
453  PGOInstrumentationGenCreateVarLegacyPass(std::string CSInstrName = "")
454  : ModulePass(ID), InstrProfileOutput(CSInstrName) {
457  }
458 
459 private:
460  bool runOnModule(Module &M) override {
461  createProfileFileNameVar(M, InstrProfileOutput);
463  return false;
464  }
465  std::string InstrProfileOutput;
466 };
467 
468 } // end anonymous namespace
469 
471 
472 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
473  "PGO instrumentation.", false, false)
476 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
477  "PGO instrumentation.", false, false)
478 
480  return new PGOInstrumentationGenLegacyPass(IsCS);
481 }
482 
484 
485 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
486  "Read PGO instrumentation profile.", false, false)
490 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
491  "Read PGO instrumentation profile.", false, false)
492 
494  bool IsCS) {
495  return new PGOInstrumentationUseLegacyPass(Filename.str(), IsCS);
496 }
497 
499 
500 INITIALIZE_PASS(PGOInstrumentationGenCreateVarLegacyPass,
501  "pgo-instr-gen-create-var",
502  "Create PGO instrumentation version variable for CSPGO.", false,
503  false)
504 
505 ModulePass *
507  return new PGOInstrumentationGenCreateVarLegacyPass(CSInstrName);
508 }
509 
510 namespace {
511 
512 /// An MST based instrumentation for PGO
513 ///
514 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
515 /// in the function level.
516 struct PGOEdge {
517  // This class implements the CFG edges. Note the CFG can be a multi-graph.
518  // So there might be multiple edges with same SrcBB and DestBB.
519  const BasicBlock *SrcBB;
520  const BasicBlock *DestBB;
521  uint64_t Weight;
522  bool InMST = false;
523  bool Removed = false;
524  bool IsCritical = false;
525 
526  PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
527  : SrcBB(Src), DestBB(Dest), Weight(W) {}
528 
529  // Return the information string of an edge.
530  const std::string infoString() const {
531  return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
532  (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
533  }
534 };
535 
536 // This class stores the auxiliary information for each BB.
537 struct BBInfo {
538  BBInfo *Group;
539  uint32_t Index;
540  uint32_t Rank = 0;
541 
542  BBInfo(unsigned IX) : Group(this), Index(IX) {}
543 
544  // Return the information string of this object.
545  const std::string infoString() const {
546  return (Twine("Index=") + Twine(Index)).str();
547  }
548 
549  // Empty function -- only applicable to UseBBInfo.
550  void addOutEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {}
551 
552  // Empty function -- only applicable to UseBBInfo.
553  void addInEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {}
554 };
555 
556 // This class implements the CFG edges. Note the CFG can be a multi-graph.
557 template <class Edge, class BBInfo> class FuncPGOInstrumentation {
558 private:
559  Function &F;
560 
561  // Is this is context-sensitive instrumentation.
562  bool IsCS;
563 
564  // A map that stores the Comdat group in function F.
565  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
566 
567  void computeCFGHash();
568  void renameComdatFunction();
569 
570 public:
571  std::vector<std::vector<Instruction *>> ValueSites;
572  SelectInstVisitor SIVisitor;
573  MemIntrinsicVisitor MIVisitor;
574  std::string FuncName;
575  GlobalVariable *FuncNameVar;
576 
577  // CFG hash value for this function.
578  uint64_t FunctionHash = 0;
579 
580  // The Minimum Spanning Tree of function CFG.
582 
583  // Collect all the BBs that will be instrumented, and store them in
584  // InstrumentBBs.
585  void getInstrumentBBs(std::vector<BasicBlock *> &InstrumentBBs);
586 
587  // Give an edge, find the BB that will be instrumented.
588  // Return nullptr if there is no BB to be instrumented.
589  BasicBlock *getInstrBB(Edge *E);
590 
591  // Return the auxiliary BB information.
592  BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
593 
594  // Return the auxiliary BB information if available.
595  BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
596 
597  // Dump edges and BB information.
598  void dumpInfo(std::string Str = "") const {
599  MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
600  Twine(FunctionHash) + "\t" + Str);
601  }
602 
603  FuncPGOInstrumentation(
604  Function &Func,
605  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
606  bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
607  BlockFrequencyInfo *BFI = nullptr, bool IsCS = false)
608  : F(Func), IsCS(IsCS), ComdatMembers(ComdatMembers),
609  ValueSites(IPVK_Last + 1), SIVisitor(Func), MIVisitor(Func),
610  MST(F, BPI, BFI) {
611  // This should be done before CFG hash computation.
612  SIVisitor.countSelects(Func);
613  MIVisitor.countMemIntrinsics(Func);
614  if (!IsCS) {
615  NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
616  NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
617  NumOfPGOBB += MST.BBInfos.size();
618  ValueSites[IPVK_IndirectCallTarget] = findIndirectCalls(Func);
619  } else {
620  NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
621  NumOfCSPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
622  NumOfCSPGOBB += MST.BBInfos.size();
623  }
624  ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
625 
626  FuncName = getPGOFuncName(F);
627  computeCFGHash();
628  if (!ComdatMembers.empty())
629  renameComdatFunction();
630  LLVM_DEBUG(dumpInfo("after CFGMST"));
631 
632  for (auto &E : MST.AllEdges) {
633  if (E->Removed)
634  continue;
635  IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++;
636  if (!E->InMST)
637  IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++;
638  }
639 
640  if (CreateGlobalVar)
641  FuncNameVar = createPGOFuncNameVar(F, FuncName);
642  }
643 };
644 
645 } // end anonymous namespace
646 
647 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
648 // value of each BB in the CFG. The higher 32 bits record the number of edges.
649 template <class Edge, class BBInfo>
650 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
651  std::vector<char> Indexes;
652  JamCRC JC;
653  for (auto &BB : F) {
654  const Instruction *TI = BB.getTerminator();
655  for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
656  BasicBlock *Succ = TI->getSuccessor(I);
657  auto BI = findBBInfo(Succ);
658  if (BI == nullptr)
659  continue;
660  uint32_t Index = BI->Index;
661  for (int J = 0; J < 4; J++)
662  Indexes.push_back((char)(Index >> (J * 8)));
663  }
664  }
665  JC.update(Indexes);
666 
667  // Hash format for context sensitive profile. Reserve 4 bits for other
668  // information.
669  FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
670  (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
671  //(uint64_t)ValueSites[IPVK_MemOPSize].size() << 40 |
672  (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
673  // Reserve bit 60-63 for other information purpose.
674  FunctionHash &= 0x0FFFFFFFFFFFFFFF;
675  if (IsCS)
677  LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
678  << " CRC = " << JC.getCRC()
679  << ", Selects = " << SIVisitor.getNumOfSelectInsts()
680  << ", Edges = " << MST.AllEdges.size() << ", ICSites = "
681  << ValueSites[IPVK_IndirectCallTarget].size()
682  << ", Hash = " << FunctionHash << "\n";);
683 }
684 
685 // Check if we can safely rename this Comdat function.
686 static bool canRenameComdat(
687  Function &F,
688  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
689  if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
690  return false;
691 
692  // FIXME: Current only handle those Comdat groups that only containing one
693  // function and function aliases.
694  // (1) For a Comdat group containing multiple functions, we need to have a
695  // unique postfix based on the hashes for each function. There is a
696  // non-trivial code refactoring to do this efficiently.
697  // (2) Variables can not be renamed, so we can not rename Comdat function in a
698  // group including global vars.
699  Comdat *C = F.getComdat();
700  for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
701  if (dyn_cast<GlobalAlias>(CM.second))
702  continue;
703  Function *FM = dyn_cast<Function>(CM.second);
704  if (FM != &F)
705  return false;
706  }
707  return true;
708 }
709 
710 // Append the CFGHash to the Comdat function name.
711 template <class Edge, class BBInfo>
712 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
713  if (!canRenameComdat(F, ComdatMembers))
714  return;
715  std::string OrigName = F.getName().str();
716  std::string NewFuncName =
717  Twine(F.getName() + "." + Twine(FunctionHash)).str();
718  F.setName(Twine(NewFuncName));
720  FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
721  Comdat *NewComdat;
722  Module *M = F.getParent();
723  // For AvailableExternallyLinkage functions, change the linkage to
724  // LinkOnceODR and put them into comdat. This is because after renaming, there
725  // is no backup external copy available for the function.
726  if (!F.hasComdat()) {
728  NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
730  F.setComdat(NewComdat);
731  return;
732  }
733 
734  // This function belongs to a single function Comdat group.
735  Comdat *OrigComdat = F.getComdat();
736  std::string NewComdatName =
737  Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
738  NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
739  NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
740 
741  for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
742  if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
743  // For aliases, change the name directly.
744  assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
745  std::string OrigGAName = GA->getName().str();
746  GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
748  continue;
749  }
750  // Must be a function.
751  Function *CF = dyn_cast<Function>(CM.second);
752  assert(CF);
753  CF->setComdat(NewComdat);
754  }
755 }
756 
757 // Collect all the BBs that will be instruments and return them in
758 // InstrumentBBs and setup InEdges/OutEdge for UseBBInfo.
759 template <class Edge, class BBInfo>
760 void FuncPGOInstrumentation<Edge, BBInfo>::getInstrumentBBs(
761  std::vector<BasicBlock *> &InstrumentBBs) {
762  // Use a worklist as we will update the vector during the iteration.
763  std::vector<Edge *> EdgeList;
764  EdgeList.reserve(MST.AllEdges.size());
765  for (auto &E : MST.AllEdges)
766  EdgeList.push_back(E.get());
767 
768  for (auto &E : EdgeList) {
769  BasicBlock *InstrBB = getInstrBB(E);
770  if (InstrBB)
771  InstrumentBBs.push_back(InstrBB);
772  }
773 
774  // Set up InEdges/OutEdges for all BBs.
775  for (auto &E : MST.AllEdges) {
776  if (E->Removed)
777  continue;
778  const BasicBlock *SrcBB = E->SrcBB;
779  const BasicBlock *DestBB = E->DestBB;
780  BBInfo &SrcInfo = getBBInfo(SrcBB);
781  BBInfo &DestInfo = getBBInfo(DestBB);
782  SrcInfo.addOutEdge(E.get());
783  DestInfo.addInEdge(E.get());
784  }
785 }
786 
787 // Given a CFG E to be instrumented, find which BB to place the instrumented
788 // code. The function will split the critical edge if necessary.
789 template <class Edge, class BBInfo>
790 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
791  if (E->InMST || E->Removed)
792  return nullptr;
793 
794  BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
795  BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
796  // For a fake edge, instrument the real BB.
797  if (SrcBB == nullptr)
798  return DestBB;
799  if (DestBB == nullptr)
800  return SrcBB;
801 
802  auto canInstrument = [](BasicBlock *BB) -> BasicBlock * {
803  // There are basic blocks (such as catchswitch) cannot be instrumented.
804  // If the returned first insertion point is the end of BB, skip this BB.
805  if (BB->getFirstInsertionPt() == BB->end())
806  return nullptr;
807  return BB;
808  };
809 
810  // Instrument the SrcBB if it has a single successor,
811  // otherwise, the DestBB if this is not a critical edge.
812  Instruction *TI = SrcBB->getTerminator();
813  if (TI->getNumSuccessors() <= 1)
814  return canInstrument(SrcBB);
815  if (!E->IsCritical)
816  return canInstrument(DestBB);
817 
818  unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
819  BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
820  if (!InstrBB) {
821  LLVM_DEBUG(
822  dbgs() << "Fail to split critical edge: not instrument this edge.\n");
823  return nullptr;
824  }
825  // For a critical edge, we have to split. Instrument the newly
826  // created BB.
827  IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++;
828  LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
829  << " --> " << getBBInfo(DestBB).Index << "\n");
830  // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB.
831  MST.addEdge(SrcBB, InstrBB, 0);
832  // Second one: Add new edge of InstrBB->DestBB.
833  Edge &NewEdge1 = MST.addEdge(InstrBB, DestBB, 0);
834  NewEdge1.InMST = true;
835  E->Removed = true;
836 
837  return canInstrument(InstrBB);
838 }
839 
840 // Visit all edge and instrument the edges not in MST, and do value profiling.
841 // Critical edges will be split.
842 static void instrumentOneFunc(
844  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
845  bool IsCS) {
846  // Split indirectbr critical edges here before computing the MST rather than
847  // later in getInstrBB() to avoid invalidating it.
848  SplitIndirectBrCriticalEdges(F, BPI, BFI);
849 
850  FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
851  BFI, IsCS);
852  std::vector<BasicBlock *> InstrumentBBs;
853  FuncInfo.getInstrumentBBs(InstrumentBBs);
854  unsigned NumCounters =
855  InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
856 
857  uint32_t I = 0;
858  Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
859  for (auto *InstrBB : InstrumentBBs) {
860  IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
861  assert(Builder.GetInsertPoint() != InstrBB->end() &&
862  "Cannot get the Instrumentation point");
863  Builder.CreateCall(
864  Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
865  {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
866  Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
867  Builder.getInt32(I++)});
868  }
869 
870  // Now instrument select instructions:
871  FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
872  FuncInfo.FunctionHash);
873  assert(I == NumCounters);
874 
876  return;
877 
878  unsigned NumIndirectCalls = 0;
879  for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
880  CallSite CS(I);
881  Value *Callee = CS.getCalledValue();
882  LLVM_DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
883  << NumIndirectCalls << "\n");
884  IRBuilder<> Builder(I);
885  assert(Builder.GetInsertPoint() != I->getParent()->end() &&
886  "Cannot get the Instrumentation point");
887  Builder.CreateCall(
888  Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
889  {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
890  Builder.getInt64(FuncInfo.FunctionHash),
891  Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
892  Builder.getInt32(IPVK_IndirectCallTarget),
893  Builder.getInt32(NumIndirectCalls++)});
894  }
895  NumOfPGOICall += NumIndirectCalls;
896 
897  // Now instrument memop intrinsic calls.
898  FuncInfo.MIVisitor.instrumentMemIntrinsics(
899  F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
900 }
901 
902 namespace {
903 
904 // This class represents a CFG edge in profile use compilation.
905 struct PGOUseEdge : public PGOEdge {
906  bool CountValid = false;
907  uint64_t CountValue = 0;
908 
909  PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
910  : PGOEdge(Src, Dest, W) {}
911 
912  // Set edge count value
913  void setEdgeCount(uint64_t Value) {
914  CountValue = Value;
915  CountValid = true;
916  }
917 
918  // Return the information string for this object.
919  const std::string infoString() const {
920  if (!CountValid)
921  return PGOEdge::infoString();
922  return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
923  .str();
924  }
925 };
926 
927 using DirectEdges = SmallVector<PGOUseEdge *, 2>;
928 
929 // This class stores the auxiliary information for each BB.
930 struct UseBBInfo : public BBInfo {
931  uint64_t CountValue = 0;
932  bool CountValid;
933  int32_t UnknownCountInEdge = 0;
934  int32_t UnknownCountOutEdge = 0;
935  DirectEdges InEdges;
936  DirectEdges OutEdges;
937 
938  UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
939 
940  UseBBInfo(unsigned IX, uint64_t C)
941  : BBInfo(IX), CountValue(C), CountValid(true) {}
942 
943  // Set the profile count value for this BB.
944  void setBBInfoCount(uint64_t Value) {
945  CountValue = Value;
946  CountValid = true;
947  }
948 
949  // Return the information string of this object.
950  const std::string infoString() const {
951  if (!CountValid)
952  return BBInfo::infoString();
953  return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
954  }
955 
956  // Add an OutEdge and update the edge count.
957  void addOutEdge(PGOUseEdge *E) {
958  OutEdges.push_back(E);
959  UnknownCountOutEdge++;
960  }
961 
962  // Add an InEdge and update the edge count.
963  void addInEdge(PGOUseEdge *E) {
964  InEdges.push_back(E);
965  UnknownCountInEdge++;
966  }
967 };
968 
969 } // end anonymous namespace
970 
971 // Sum up the count values for all the edges.
972 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
973  uint64_t Total = 0;
974  for (auto &E : Edges) {
975  if (E->Removed)
976  continue;
977  Total += E->CountValue;
978  }
979  return Total;
980 }
981 
982 namespace {
983 
984 class PGOUseFunc {
985 public:
986  PGOUseFunc(Function &Func, Module *Modu,
987  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
988  BranchProbabilityInfo *BPI = nullptr,
989  BlockFrequencyInfo *BFIin = nullptr, bool IsCS = false)
990  : F(Func), M(Modu), BFI(BFIin),
991  FuncInfo(Func, ComdatMembers, false, BPI, BFIin, IsCS),
992  FreqAttr(FFA_Normal), IsCS(IsCS) {}
993 
994  // Read counts for the instrumented BB from profile.
995  bool readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros);
996 
997  // Populate the counts for all BBs.
998  void populateCounters();
999 
1000  // Set the branch weights based on the count values.
1001  void setBranchWeights();
1002 
1003  // Annotate the value profile call sites for all value kind.
1004  void annotateValueSites();
1005 
1006  // Annotate the value profile call sites for one value kind.
1007  void annotateValueSites(uint32_t Kind);
1008 
1009  // Annotate the irreducible loop header weights.
1010  void annotateIrrLoopHeaderWeights();
1011 
1012  // The hotness of the function from the profile count.
1013  enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
1014 
1015  // Return the function hotness from the profile.
1016  FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
1017 
1018  // Return the function hash.
1019  uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
1020 
1021  // Return the profile record for this function;
1022  InstrProfRecord &getProfileRecord() { return ProfileRecord; }
1023 
1024  // Return the auxiliary BB information.
1025  UseBBInfo &getBBInfo(const BasicBlock *BB) const {
1026  return FuncInfo.getBBInfo(BB);
1027  }
1028 
1029  // Return the auxiliary BB information if available.
1030  UseBBInfo *findBBInfo(const BasicBlock *BB) const {
1031  return FuncInfo.findBBInfo(BB);
1032  }
1033 
1034  Function &getFunc() const { return F; }
1035 
1036  void dumpInfo(std::string Str = "") const {
1037  FuncInfo.dumpInfo(Str);
1038  }
1039 
1040  uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
1041 private:
1042  Function &F;
1043  Module *M;
1045 
1046  // This member stores the shared information with class PGOGenFunc.
1047  FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
1048 
1049  // The maximum count value in the profile. This is only used in PGO use
1050  // compilation.
1051  uint64_t ProgramMaxCount;
1052 
1053  // Position of counter that remains to be read.
1054  uint32_t CountPosition = 0;
1055 
1056  // Total size of the profile count for this function.
1057  uint32_t ProfileCountSize = 0;
1058 
1059  // ProfileRecord for this function.
1060  InstrProfRecord ProfileRecord;
1061 
1062  // Function hotness info derived from profile.
1063  FuncFreqAttr FreqAttr;
1064 
1065  // Is to use the context sensitive profile.
1066  bool IsCS;
1067 
1068  // Find the Instrumented BB and set the value. Return false on error.
1069  bool setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
1070 
1071  // Set the edge counter value for the unknown edge -- there should be only
1072  // one unknown edge.
1073  void setEdgeCount(DirectEdges &Edges, uint64_t Value);
1074 
1075  // Return FuncName string;
1076  const std::string getFuncName() const { return FuncInfo.FuncName; }
1077 
1078  // Set the hot/cold inline hints based on the count values.
1079  // FIXME: This function should be removed once the functionality in
1080  // the inliner is implemented.
1081  void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
1082  if (ProgramMaxCount == 0)
1083  return;
1084  // Threshold of the hot functions.
1085  const BranchProbability HotFunctionThreshold(1, 100);
1086  // Threshold of the cold functions.
1087  const BranchProbability ColdFunctionThreshold(2, 10000);
1088  if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
1089  FreqAttr = FFA_Hot;
1090  else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
1091  FreqAttr = FFA_Cold;
1092  }
1093 };
1094 
1095 } // end anonymous namespace
1096 
1097 // Visit all the edges and assign the count value for the instrumented
1098 // edges and the BB. Return false on error.
1099 bool PGOUseFunc::setInstrumentedCounts(
1100  const std::vector<uint64_t> &CountFromProfile) {
1101 
1102  std::vector<BasicBlock *> InstrumentBBs;
1103  FuncInfo.getInstrumentBBs(InstrumentBBs);
1104  unsigned NumCounters =
1105  InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
1106  // The number of counters here should match the number of counters
1107  // in profile. Return if they mismatch.
1108  if (NumCounters != CountFromProfile.size()) {
1109  return false;
1110  }
1111  // Set the profile count to the Instrumented BBs.
1112  uint32_t I = 0;
1113  for (BasicBlock *InstrBB : InstrumentBBs) {
1114  uint64_t CountValue = CountFromProfile[I++];
1115  UseBBInfo &Info = getBBInfo(InstrBB);
1116  Info.setBBInfoCount(CountValue);
1117  }
1118  ProfileCountSize = CountFromProfile.size();
1119  CountPosition = I;
1120 
1121  // Set the edge count and update the count of unknown edges for BBs.
1122  auto setEdgeCount = [this](PGOUseEdge *E, uint64_t Value) -> void {
1123  E->setEdgeCount(Value);
1124  this->getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1125  this->getBBInfo(E->DestBB).UnknownCountInEdge--;
1126  };
1127 
1128  // Set the profile count the Instrumented edges. There are BBs that not in
1129  // MST but not instrumented. Need to set the edge count value so that we can
1130  // populate the profile counts later.
1131  for (auto &E : FuncInfo.MST.AllEdges) {
1132  if (E->Removed || E->InMST)
1133  continue;
1134  const BasicBlock *SrcBB = E->SrcBB;
1135  UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1136 
1137  // If only one out-edge, the edge profile count should be the same as BB
1138  // profile count.
1139  if (SrcInfo.CountValid && SrcInfo.OutEdges.size() == 1)
1140  setEdgeCount(E.get(), SrcInfo.CountValue);
1141  else {
1142  const BasicBlock *DestBB = E->DestBB;
1143  UseBBInfo &DestInfo = getBBInfo(DestBB);
1144  // If only one in-edge, the edge profile count should be the same as BB
1145  // profile count.
1146  if (DestInfo.CountValid && DestInfo.InEdges.size() == 1)
1147  setEdgeCount(E.get(), DestInfo.CountValue);
1148  }
1149  if (E->CountValid)
1150  continue;
1151  // E's count should have been set from profile. If not, this meenas E skips
1152  // the instrumentation. We set the count to 0.
1153  setEdgeCount(E.get(), 0);
1154  }
1155  return true;
1156 }
1157 
1158 // Set the count value for the unknown edge. There should be one and only one
1159 // unknown edge in Edges vector.
1160 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
1161  for (auto &E : Edges) {
1162  if (E->CountValid)
1163  continue;
1164  E->setEdgeCount(Value);
1165 
1166  getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1167  getBBInfo(E->DestBB).UnknownCountInEdge--;
1168  return;
1169  }
1170  llvm_unreachable("Cannot find the unknown count edge");
1171 }
1172 
1173 // Read the profile from ProfileFileName and assign the value to the
1174 // instrumented BB and the edges. This function also updates ProgramMaxCount.
1175 // Return true if the profile are successfully read, and false on errors.
1176 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros) {
1177  auto &Ctx = M->getContext();
1178  Expected<InstrProfRecord> Result =
1179  PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
1180  if (Error E = Result.takeError()) {
1181  handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1182  auto Err = IPE.get();
1183  bool SkipWarning = false;
1184  LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
1185  << FuncInfo.FuncName << ": ");
1186  if (Err == instrprof_error::unknown_function) {
1187  IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++;
1188  SkipWarning = !PGOWarnMissing;
1189  LLVM_DEBUG(dbgs() << "unknown function");
1190  } else if (Err == instrprof_error::hash_mismatch ||
1191  Err == instrprof_error::malformed) {
1192  IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++;
1193  SkipWarning =
1196  (F.hasComdat() ||
1197  F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
1198  LLVM_DEBUG(dbgs() << "hash mismatch (skip=" << SkipWarning << ")");
1199  }
1200 
1201  LLVM_DEBUG(dbgs() << " IsCS=" << IsCS << "\n");
1202  if (SkipWarning)
1203  return;
1204 
1205  std::string Msg = IPE.message() + std::string(" ") + F.getName().str() +
1206  std::string(" Hash = ") +
1207  std::to_string(FuncInfo.FunctionHash);
1208 
1209  Ctx.diagnose(
1210  DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1211  });
1212  return false;
1213  }
1214  ProfileRecord = std::move(Result.get());
1215  std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
1216 
1217  IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1218  LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1219  uint64_t ValueSum = 0;
1220  for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1221  LLVM_DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
1222  ValueSum += CountFromProfile[I];
1223  }
1224  AllZeros = (ValueSum == 0);
1225 
1226  LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
1227 
1228  getBBInfo(nullptr).UnknownCountOutEdge = 2;
1229  getBBInfo(nullptr).UnknownCountInEdge = 2;
1230 
1231  if (!setInstrumentedCounts(CountFromProfile)) {
1232  LLVM_DEBUG(
1233  dbgs() << "Inconsistent number of counts, skipping this function");
1234  Ctx.diagnose(DiagnosticInfoPGOProfile(
1235  M->getName().data(),
1236  Twine("Inconsistent number of counts in ") + F.getName().str()
1237  + Twine(": the profile may be stale or there is a function name collision."),
1238  DS_Warning));
1239  return false;
1240  }
1241  ProgramMaxCount = PGOReader->getMaximumFunctionCount(IsCS);
1242  return true;
1243 }
1244 
1245 // Populate the counters from instrumented BBs to all BBs.
1246 // In the end of this operation, all BBs should have a valid count value.
1247 void PGOUseFunc::populateCounters() {
1248  bool Changes = true;
1249  unsigned NumPasses = 0;
1250  while (Changes) {
1251  NumPasses++;
1252  Changes = false;
1253 
1254  // For efficient traversal, it's better to start from the end as most
1255  // of the instrumented edges are at the end.
1256  for (auto &BB : reverse(F)) {
1257  UseBBInfo *Count = findBBInfo(&BB);
1258  if (Count == nullptr)
1259  continue;
1260  if (!Count->CountValid) {
1261  if (Count->UnknownCountOutEdge == 0) {
1262  Count->CountValue = sumEdgeCount(Count->OutEdges);
1263  Count->CountValid = true;
1264  Changes = true;
1265  } else if (Count->UnknownCountInEdge == 0) {
1266  Count->CountValue = sumEdgeCount(Count->InEdges);
1267  Count->CountValid = true;
1268  Changes = true;
1269  }
1270  }
1271  if (Count->CountValid) {
1272  if (Count->UnknownCountOutEdge == 1) {
1273  uint64_t Total = 0;
1274  uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1275  // If the one of the successor block can early terminate (no-return),
1276  // we can end up with situation where out edge sum count is larger as
1277  // the source BB's count is collected by a post-dominated block.
1278  if (Count->CountValue > OutSum)
1279  Total = Count->CountValue - OutSum;
1280  setEdgeCount(Count->OutEdges, Total);
1281  Changes = true;
1282  }
1283  if (Count->UnknownCountInEdge == 1) {
1284  uint64_t Total = 0;
1285  uint64_t InSum = sumEdgeCount(Count->InEdges);
1286  if (Count->CountValue > InSum)
1287  Total = Count->CountValue - InSum;
1288  setEdgeCount(Count->InEdges, Total);
1289  Changes = true;
1290  }
1291  }
1292  }
1293  }
1294 
1295  LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
1296 #ifndef NDEBUG
1297  // Assert every BB has a valid counter.
1298  for (auto &BB : F) {
1299  auto BI = findBBInfo(&BB);
1300  if (BI == nullptr)
1301  continue;
1302  assert(BI->CountValid && "BB count is not valid");
1303  }
1304 #endif
1305  uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
1306  F.setEntryCount(ProfileCount(FuncEntryCount, Function::PCT_Real));
1307  uint64_t FuncMaxCount = FuncEntryCount;
1308  for (auto &BB : F) {
1309  auto BI = findBBInfo(&BB);
1310  if (BI == nullptr)
1311  continue;
1312  FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1313  }
1314  markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1315 
1316  // Now annotate select instructions
1317  FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1318  assert(CountPosition == ProfileCountSize);
1319 
1320  LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
1321 }
1322 
1323 // Assign the scaled count values to the BB with multiple out edges.
1325  // Generate MD_prof metadata for every branch instruction.
1326  LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F.getName()
1327  << " IsCS=" << IsCS << "\n");
1328  for (auto &BB : F) {
1329  Instruction *TI = BB.getTerminator();
1330  if (TI->getNumSuccessors() < 2)
1331  continue;
1332  if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1333  isa<IndirectBrInst>(TI)))
1334  continue;
1335 
1336  if (getBBInfo(&BB).CountValue == 0)
1337  continue;
1338 
1339  // We have a non-zero Branch BB.
1340  const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1341  unsigned Size = BBCountInfo.OutEdges.size();
1342  SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
1343  uint64_t MaxCount = 0;
1344  for (unsigned s = 0; s < Size; s++) {
1345  const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1346  const BasicBlock *SrcBB = E->SrcBB;
1347  const BasicBlock *DestBB = E->DestBB;
1348  if (DestBB == nullptr)
1349  continue;
1350  unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1351  uint64_t EdgeCount = E->CountValue;
1352  if (EdgeCount > MaxCount)
1353  MaxCount = EdgeCount;
1354  EdgeCounts[SuccNum] = EdgeCount;
1355  }
1356  setProfMetadata(M, TI, EdgeCounts, MaxCount);
1357  }
1358 }
1359 
1360 static bool isIndirectBrTarget(BasicBlock *BB) {
1361  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1362  if (isa<IndirectBrInst>((*PI)->getTerminator()))
1363  return true;
1364  }
1365  return false;
1366 }
1367 
1368 void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1369  LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1370  // Find irr loop headers
1371  for (auto &BB : F) {
1372  // As a heuristic also annotate indrectbr targets as they have a high chance
1373  // to become an irreducible loop header after the indirectbr tail
1374  // duplication.
1375  if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
1376  Instruction *TI = BB.getTerminator();
1377  const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1378  setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1379  }
1380  }
1381 }
1382 
1383 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1384  Module *M = F.getParent();
1385  IRBuilder<> Builder(&SI);
1386  Type *Int64Ty = Builder.getInt64Ty();
1387  Type *I8PtrTy = Builder.getInt8PtrTy();
1388  auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1389  Builder.CreateCall(
1390  Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1391  {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1392  Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1393  Builder.getInt32(*CurCtrIdx), Step});
1394  ++(*CurCtrIdx);
1395 }
1396 
1397 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1398  std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1399  assert(*CurCtrIdx < CountFromProfile.size() &&
1400  "Out of bound access of counters");
1401  uint64_t SCounts[2];
1402  SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1403  ++(*CurCtrIdx);
1404  uint64_t TotalCount = 0;
1405  auto BI = UseFunc->findBBInfo(SI.getParent());
1406  if (BI != nullptr)
1407  TotalCount = BI->CountValue;
1408  // False Count
1409  SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1410  uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1411  if (MaxCount)
1412  setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
1413 }
1414 
1415 void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1416  if (!PGOInstrSelect)
1417  return;
1418  // FIXME: do not handle this yet.
1419  if (SI.getCondition()->getType()->isVectorTy())
1420  return;
1421 
1422  switch (Mode) {
1423  case VM_counting:
1424  NSIs++;
1425  return;
1426  case VM_instrument:
1427  instrumentOneSelectInst(SI);
1428  return;
1429  case VM_annotate:
1430  annotateOneSelectInst(SI);
1431  return;
1432  }
1433 
1434  llvm_unreachable("Unknown visiting mode");
1435 }
1436 
1437 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1438  Module *M = F.getParent();
1439  IRBuilder<> Builder(&MI);
1440  Type *Int64Ty = Builder.getInt64Ty();
1441  Type *I8PtrTy = Builder.getInt8PtrTy();
1442  Value *Length = MI.getLength();
1443  assert(!isa<ConstantInt>(Length));
1444  Builder.CreateCall(
1445  Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
1446  {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1447  Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
1448  Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1449  ++CurCtrId;
1450 }
1451 
1452 void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1453  if (!PGOInstrMemOP)
1454  return;
1455  Value *Length = MI.getLength();
1456  // Not instrument constant length calls.
1457  if (dyn_cast<ConstantInt>(Length))
1458  return;
1459 
1460  switch (Mode) {
1461  case VM_counting:
1462  NMemIs++;
1463  return;
1464  case VM_instrument:
1465  instrumentOneMemIntrinsic(MI);
1466  return;
1467  case VM_annotate:
1468  Candidates.push_back(&MI);
1469  return;
1470  }
1471  llvm_unreachable("Unknown visiting mode");
1472 }
1473 
1474 // Traverse all valuesites and annotate the instructions for all value kind.
1475 void PGOUseFunc::annotateValueSites() {
1477  return;
1478 
1479  // Create the PGOFuncName meta data.
1480  createPGOFuncNameMetadata(F, FuncInfo.FuncName);
1481 
1482  for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1483  annotateValueSites(Kind);
1484 }
1485 
1486 static const char *ValueProfKindDescr[] = {
1487 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
1489 };
1490 
1491 // Annotate the instructions for a specific value kind.
1492 void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1493  assert(Kind <= IPVK_Last);
1494  unsigned ValueSiteIndex = 0;
1495  auto &ValueSites = FuncInfo.ValueSites[Kind];
1496  unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1497  if (NumValueSites != ValueSites.size()) {
1498  auto &Ctx = M->getContext();
1499  Ctx.diagnose(DiagnosticInfoPGOProfile(
1500  M->getName().data(),
1501  Twine("Inconsistent number of value sites for ") +
1502  Twine(ValueProfKindDescr[Kind]) +
1503  Twine(" profiling in \"") + F.getName().str() +
1504  Twine("\", possibly due to the use of a stale profile."),
1505  DS_Warning));
1506  return;
1507  }
1508 
1509  for (auto &I : ValueSites) {
1510  LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1511  << "): Index = " << ValueSiteIndex << " out of "
1512  << NumValueSites << "\n");
1513  annotateValueSite(*M, *I, ProfileRecord,
1514  static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1515  Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1516  : MaxNumAnnotations);
1517  ValueSiteIndex++;
1518  }
1519 }
1520 
1521 // Collect the set of members for each Comdat in module M and store
1522 // in ComdatMembers.
1524  Module &M,
1525  std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1526  if (!DoComdatRenaming)
1527  return;
1528  for (Function &F : M)
1529  if (Comdat *C = F.getComdat())
1530  ComdatMembers.insert(std::make_pair(C, &F));
1531  for (GlobalVariable &GV : M.globals())
1532  if (Comdat *C = GV.getComdat())
1533  ComdatMembers.insert(std::make_pair(C, &GV));
1534  for (GlobalAlias &GA : M.aliases())
1535  if (Comdat *C = GA.getComdat())
1536  ComdatMembers.insert(std::make_pair(C, &GA));
1537 }
1538 
1540  Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1541  function_ref<BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS) {
1542  // For the context-sensitve instrumentation, we should have a separated pass
1543  // (before LTO/ThinLTO linking) to create these variables.
1544  if (!IsCS)
1545  createIRLevelProfileFlagVar(M, /* IsCS */ false);
1546  std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1547  collectComdatMembers(M, ComdatMembers);
1548 
1549  for (auto &F : M) {
1550  if (F.isDeclaration())
1551  continue;
1552  auto *BPI = LookupBPI(F);
1553  auto *BFI = LookupBFI(F);
1554  instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers, IsCS);
1555  }
1556  return true;
1557 }
1558 
1561  createProfileFileNameVar(M, CSInstrName);
1562  createIRLevelProfileFlagVar(M, /* IsCS */ true);
1563  return PreservedAnalyses::all();
1564 }
1565 
1566 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
1567  if (skipModule(M))
1568  return false;
1569 
1570  auto LookupBPI = [this](Function &F) {
1571  return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1572  };
1573  auto LookupBFI = [this](Function &F) {
1574  return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1575  };
1576  return InstrumentAllFunctions(M, LookupBPI, LookupBFI, IsCS);
1577 }
1578 
1580  ModuleAnalysisManager &AM) {
1581  auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1582  auto LookupBPI = [&FAM](Function &F) {
1583  return &FAM.getResult<BranchProbabilityAnalysis>(F);
1584  };
1585 
1586  auto LookupBFI = [&FAM](Function &F) {
1587  return &FAM.getResult<BlockFrequencyAnalysis>(F);
1588  };
1589 
1590  if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI, IsCS))
1591  return PreservedAnalyses::all();
1592 
1593  return PreservedAnalyses::none();
1594 }
1595 
1597  Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName,
1599  function_ref<BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS) {
1600  LLVM_DEBUG(dbgs() << "Read in profile counters: ");
1601  auto &Ctx = M.getContext();
1602  // Read the counter array from file.
1603  auto ReaderOrErr =
1604  IndexedInstrProfReader::create(ProfileFileName, ProfileRemappingFileName);
1605  if (Error E = ReaderOrErr.takeError()) {
1606  handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1607  Ctx.diagnose(
1608  DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1609  });
1610  return false;
1611  }
1612 
1613  std::unique_ptr<IndexedInstrProfReader> PGOReader =
1614  std::move(ReaderOrErr.get());
1615  if (!PGOReader) {
1616  Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
1617  StringRef("Cannot get PGOReader")));
1618  return false;
1619  }
1620  if (!PGOReader->hasCSIRLevelProfile() && IsCS)
1621  return false;
1622 
1623  // TODO: might need to change the warning once the clang option is finalized.
1624  if (!PGOReader->isIRLevelProfile()) {
1625  Ctx.diagnose(DiagnosticInfoPGOProfile(
1626  ProfileFileName.data(), "Not an IR level instrumentation profile"));
1627  return false;
1628  }
1629 
1630  std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1631  collectComdatMembers(M, ComdatMembers);
1632  std::vector<Function *> HotFunctions;
1633  std::vector<Function *> ColdFunctions;
1634  for (auto &F : M) {
1635  if (F.isDeclaration())
1636  continue;
1637  auto *BPI = LookupBPI(F);
1638  auto *BFI = LookupBFI(F);
1639  // Split indirectbr critical edges here before computing the MST rather than
1640  // later in getInstrBB() to avoid invalidating it.
1642  PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI, IsCS);
1643  bool AllZeros = false;
1644  if (!Func.readCounters(PGOReader.get(), AllZeros))
1645  continue;
1646  if (AllZeros) {
1647  F.setEntryCount(ProfileCount(0, Function::PCT_Real));
1648  if (Func.getProgramMaxCount() != 0)
1649  ColdFunctions.push_back(&F);
1650  continue;
1651  }
1652  Func.populateCounters();
1653  Func.setBranchWeights();
1654  Func.annotateValueSites();
1655  Func.annotateIrrLoopHeaderWeights();
1656  PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1657  if (FreqAttr == PGOUseFunc::FFA_Cold)
1658  ColdFunctions.push_back(&F);
1659  else if (FreqAttr == PGOUseFunc::FFA_Hot)
1660  HotFunctions.push_back(&F);
1661  if (PGOViewCounts != PGOVCT_None &&
1662  (ViewBlockFreqFuncName.empty() ||
1663  F.getName().equals(ViewBlockFreqFuncName))) {
1664  LoopInfo LI{DominatorTree(F)};
1665  std::unique_ptr<BranchProbabilityInfo> NewBPI =
1666  std::make_unique<BranchProbabilityInfo>(F, LI);
1667  std::unique_ptr<BlockFrequencyInfo> NewBFI =
1668  std::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1669  if (PGOViewCounts == PGOVCT_Graph)
1670  NewBFI->view();
1671  else if (PGOViewCounts == PGOVCT_Text) {
1672  dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1673  NewBFI->print(dbgs());
1674  }
1675  }
1676  if (PGOViewRawCounts != PGOVCT_None &&
1677  (ViewBlockFreqFuncName.empty() ||
1678  F.getName().equals(ViewBlockFreqFuncName))) {
1680  if (ViewBlockFreqFuncName.empty())
1681  WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1682  else
1683  ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1684  else if (PGOViewRawCounts == PGOVCT_Text) {
1685  dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1686  Func.dumpInfo();
1687  }
1688  }
1689  }
1690  M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()),
1693 
1694  // Set function hotness attribute from the profile.
1695  // We have to apply these attributes at the end because their presence
1696  // can affect the BranchProbabilityInfo of any callers, resulting in an
1697  // inconsistent MST between prof-gen and prof-use.
1698  for (auto &F : HotFunctions) {
1699  F->addFnAttr(Attribute::InlineHint);
1700  LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1701  << "\n");
1702  }
1703  for (auto &F : ColdFunctions) {
1704  F->addFnAttr(Attribute::Cold);
1705  LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
1706  << "\n");
1707  }
1708  return true;
1709 }
1710 
1712  std::string RemappingFilename,
1713  bool IsCS)
1714  : ProfileFileName(std::move(Filename)),
1715  ProfileRemappingFileName(std::move(RemappingFilename)), IsCS(IsCS) {
1716  if (!PGOTestProfileFile.empty())
1717  ProfileFileName = PGOTestProfileFile;
1718  if (!PGOTestProfileRemappingFile.empty())
1719  ProfileRemappingFileName = PGOTestProfileRemappingFile;
1720 }
1721 
1723  ModuleAnalysisManager &AM) {
1724 
1725  auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1726  auto LookupBPI = [&FAM](Function &F) {
1727  return &FAM.getResult<BranchProbabilityAnalysis>(F);
1728  };
1729 
1730  auto LookupBFI = [&FAM](Function &F) {
1731  return &FAM.getResult<BlockFrequencyAnalysis>(F);
1732  };
1733 
1734  if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName,
1735  LookupBPI, LookupBFI, IsCS))
1736  return PreservedAnalyses::all();
1737 
1738  return PreservedAnalyses::none();
1739 }
1740 
1741 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1742  if (skipModule(M))
1743  return false;
1744 
1745  auto LookupBPI = [this](Function &F) {
1746  return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1747  };
1748  auto LookupBFI = [this](Function &F) {
1749  return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1750  };
1751 
1752  return annotateAllFunctions(M, ProfileFileName, "", LookupBPI, LookupBFI,
1753  IsCS);
1754 }
1755 
1756 static std::string getSimpleNodeName(const BasicBlock *Node) {
1757  if (!Node->getName().empty())
1758  return Node->getName();
1759 
1760  std::string SimpleNodeName;
1761  raw_string_ostream OS(SimpleNodeName);
1762  Node->printAsOperand(OS, false);
1763  return OS.str();
1764 }
1765 
1767  ArrayRef<uint64_t> EdgeCounts,
1768  uint64_t MaxCount) {
1769  MDBuilder MDB(M->getContext());
1770  assert(MaxCount > 0 && "Bad max count");
1771  uint64_t Scale = calculateCountScale(MaxCount);
1772  SmallVector<unsigned, 4> Weights;
1773  for (const auto &ECI : EdgeCounts)
1774  Weights.push_back(scaleBranchCount(ECI, Scale));
1775 
1776  LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W
1777  : Weights) {
1778  dbgs() << W << " ";
1779  } dbgs() << "\n";);
1780 
1781  misexpect::verifyMisExpect(TI, Weights, TI->getContext());
1782 
1783  TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1784  if (EmitBranchProbability) {
1785  std::string BrCondStr = getBranchCondString(TI);
1786  if (BrCondStr.empty())
1787  return;
1788 
1789  uint64_t WSum =
1790  std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
1791  [](uint64_t w1, uint64_t w2) { return w1 + w2; });
1792  uint64_t TotalCount =
1793  std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
1794  [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1795  Scale = calculateCountScale(WSum);
1796  BranchProbability BP(scaleBranchCount(Weights[0], Scale),
1797  scaleBranchCount(WSum, Scale));
1798  std::string BranchProbStr;
1799  raw_string_ostream OS(BranchProbStr);
1800  OS << BP;
1801  OS << " (total count : " << TotalCount << ")";
1802  OS.flush();
1803  Function *F = TI->getParent()->getParent();
1805  ORE.emit([&]() {
1806  return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1807  << BrCondStr << " is true with probability : " << BranchProbStr;
1808  });
1809  }
1810 }
1811 
1812 namespace llvm {
1813 
1814 void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1815  MDBuilder MDB(M->getContext());
1816  TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1817  MDB.createIrrLoopHeaderWeight(Count));
1818 }
1819 
1820 template <> struct GraphTraits<PGOUseFunc *> {
1821  using NodeRef = const BasicBlock *;
1824 
1825  static NodeRef getEntryNode(const PGOUseFunc *G) {
1826  return &G->getFunc().front();
1827  }
1828 
1830  return succ_begin(N);
1831  }
1832 
1833  static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1834 
1835  static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1836  return nodes_iterator(G->getFunc().begin());
1837  }
1838 
1839  static nodes_iterator nodes_end(const PGOUseFunc *G) {
1840  return nodes_iterator(G->getFunc().end());
1841  }
1842 };
1843 
1844 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1845  explicit DOTGraphTraits(bool isSimple = false)
1847 
1848  static std::string getGraphName(const PGOUseFunc *G) {
1849  return G->getFunc().getName();
1850  }
1851 
1852  std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1853  std::string Result;
1854  raw_string_ostream OS(Result);
1855 
1856  OS << getSimpleNodeName(Node) << ":\\l";
1857  UseBBInfo *BI = Graph->findBBInfo(Node);
1858  OS << "Count : ";
1859  if (BI && BI->CountValid)
1860  OS << BI->CountValue << "\\l";
1861  else
1862  OS << "Unknown\\l";
1863 
1864  if (!PGOInstrSelect)
1865  return Result;
1866 
1867  for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1868  auto *I = &*BI;
1869  if (!isa<SelectInst>(I))
1870  continue;
1871  // Display scaled counts for SELECT instruction:
1872  OS << "SELECT : { T = ";
1873  uint64_t TC, FC;
1874  bool HasProf = I->extractProfMetadata(TC, FC);
1875  if (!HasProf)
1876  OS << "Unknown, F = Unknown }\\l";
1877  else
1878  OS << TC << ", F = " << FC << " }\\l";
1879  }
1880  return Result;
1881  }
1882 };
1883 
1884 } // end namespace llvm
ModulePass * createPGOInstrumentationGenLegacyPass(bool IsCS=false)
uint64_t CallInst * C
static uint64_t sumEdgeCount(const ArrayRef< PGOUseEdge *> Edges)
uint32_t getCRC() const
Definition: JamCRC.h:41
void setProfMetadata(Module *M, Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
static cl::opt< bool > NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden, cl::desc("Use this option to turn off/on " "warnings about profile cfg mismatch."))
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Base class for instruction visitors.
Definition: InstVisitor.h:80
SI Whole Quad Mode
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:1888
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:776
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static cl::opt< bool > PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden, cl::desc("Use this option to turn on/off " "warnings about missing profile data for " "functions."))
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
static ChildIteratorType child_begin(const NodeRef N)
std::vector< std::unique_ptr< Edge > > AllEdges
Definition: CFGMST.h:43
Diagnostic information for the PGO profiler.
Available for inspection, not emission.
Definition: GlobalValue.h:49
void push_back(const T &Elt)
Definition: SmallVector.h:211
std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:1090
PGOInstrumentationUse(std::string Filename="", std::string RemappingFilename="", bool IsCS=false)
pgo instr gen
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:104
INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", "PGO instrumentation.", false, false) INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:56
static cl::opt< bool > PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off " "memory intrinsic size profiling."))
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:733
static bool InstrumentAllFunctions(Module &M, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS)
STATISTIC(NumFunctions, "Total number of functions")
F(f)
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:137
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:229
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
SuccIterator< const Instruction, const BasicBlock > succ_const_iterator
Definition: CFG.h:241
Value * getLength() const
Base class for error info classes.
Definition: Error.h:48
An union-find based Minimum Spanning Tree for CFG.
Definition: CFGMST.h:37
*ViewGraph Emit a dot run run gv on the postscript *then cleanup For use from the debugger *void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
Definition: GraphWriter.h:366
Function::ProfileCount ProfileCount
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:268
ModulePass * createPGOInstrumentationGenCreateVarLegacyPass(StringRef CSInstrName=StringRef(""))
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
Definition: BitVector.h:937
This class represents the LLVM &#39;select&#39; instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:388
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:244
ValTy * getCalledValue() const
Return the pointer to function that is being called.
Definition: CallSite.h:104
static bool annotateAllFunctions(Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS)
static cl::opt< std::string > PGOTestProfileRemappingFile("pgo-test-profile-remapping-file", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path of profile remapping file. This is mainly for " "test purpose."))
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:779
This file contains the simple types necessary to represent the attributes associated with functions a...
Legacy analysis pass which computes BlockFrequencyInfo.
static std::string getGraphName(const PGOUseFunc *G)
void initializePGOInstrumentationGenCreateVarLegacyPassPass(PassRegistry &)
VisitMode
The select instruction visitor plays three roles specified by the mode.
Tagged union holding either a T or a Error.
Definition: yaml2obj.h:21
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:140
This file implements a class to represent arbitrary precision integral constant values and operations...
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:102
static bool isSimple(Instruction *I)
Analysis pass which computes BranchProbabilityInfo.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:261
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition: Constants.h:200
This file provides the interface for IR based instrumentation passes ( (profile-gen, and profile-use).
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
static cl::opt< bool > DisableValueProfiling("disable-vp", cl::init(false), cl::Hidden, cl::desc("Disable Value Profiling"))
static NodeRef getEntryNode(const PGOUseFunc *G)
static bool isIndirectBrTarget(BasicBlock *BB)
void setComdat(Comdat *C)
Definition: GlobalObject.h:107
static void setBranchWeights(SwitchInst *SI, ArrayRef< uint32_t > Weights)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
Definition: GraphWriter.h:309
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
void verifyMisExpect(llvm::Instruction *I, const llvm::SmallVector< uint32_t, 4 > &Weights, llvm::LLVMContext &Ctx)
verifyMisExpect - compares PGO counters to the thresholds used for llvm.expect and warns if the PGO c...
Definition: MisExpect.cpp:95
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
void initializePGOInstrumentationGenLegacyPassPass(PassRegistry &)
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition: Constants.h:208
static bool canRenameComdat(Function &F, std::unordered_multimap< Comdat *, GlobalValue *> &ComdatMembers)
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1878
static nodes_iterator nodes_end(const PGOUseFunc *G)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1057
instrprof_error get() const
Definition: InstrProf.h:319
Legacy analysis pass which computes BranchProbabilityInfo.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
Definition: User.h:169
Analysis containing CSE Info
Definition: CSEInfo.cpp:20
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
static ChildIteratorType child_end(const NodeRef N)
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:105
static cl::opt< unsigned > MaxNumMemOPAnnotations("memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of preicise value annotations for a single memop" "intrinsic"))
std::string message() const override
Return the error message as a string.
Definition: InstrProf.cpp:209
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1804
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:51
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
StringRef getName() const
Definition: Comdat.cpp:26
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
Definition: InstrProf.cpp:1153
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
Conditional or Unconditional Branch instruction.
#define DEBUG_TYPE
void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:652
static StringRef getPredicateName(Predicate P)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Diagnostic information for applied optimization remarks.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:112
Represent the analysis usage information of a pass.
static cl::opt< PGOViewCountsType > PGOViewRawCounts("pgo-view-raw-counts", cl::Hidden, cl::desc("A boolean option to show CFG dag or text " "with raw profile counts from " "profile data. See also option " "-pgo-view-counts. To limit graph " "display to only one function, use " "filtering option -view-bfi-func-name."), cl::values(clEnumValN(PGOVCT_None, "none", "do not show."), clEnumValN(PGOVCT_Graph, "graph", "show a graph."), clEnumValN(PGOVCT_Text, "text", "show in text.")))
static cl::opt< bool > DoComdatRenaming("do-comdat-renaming", cl::init(false), cl::Hidden, cl::desc("Append function hash to the name of COMDAT function to avoid " "function hash mismatch due to the preinliner"))
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:172
This instruction compares its operands according to the predicate given to the constructor.
static std::string getBranchCondString(Instruction *TI)
static const char * ValueProfKindDescr[]
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:115
static uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:348
INITIALIZE_PASS(PGOInstrumentationGenCreateVarLegacyPass, "pgo-instr-gen-create-var", "Create PGO instrumentation version variable for CSPGO.", false, false) ModulePass *llvm
static cl::opt< bool > NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true), cl::Hidden, cl::desc("The option is used to turn on/off " "warnings about hash mismatch for comdat " "functions."))
void initializePGOInstrumentationUseLegacyPassPass(PassRegistry &)
DenseMap< const BasicBlock *, std::unique_ptr< BBInfo > > BBInfos
Definition: CFGMST.h:46
const Value * getCondition() const
static uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:482
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
Definition: InstrProf.cpp:931
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
Class to represent profile counts.
Definition: Function.h:260
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function&#39;s raw name.
Definition: InstrProf.cpp:1032
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:421
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:219
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:4355
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:519
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1222
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to &#39;dot...
BBInfo * findBBInfo(const BasicBlock *BB) const
Definition: CFGMST.h:88
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:904
Analysis pass which computes BlockFrequencyInfo.
This is the common base class for memset/memcpy/memmove.
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:45
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file. ...
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1146
static nodes_iterator nodes_begin(const PGOUseFunc *G)
static cl::opt< bool > PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden, cl::desc("Use this option to turn on/off SELECT " "instruction instrumentation. "))
iterator end()
Definition: BasicBlock.h:270
uint64_t getMaximumFunctionCount(bool UseCS)
Return the maximum of all known function counts.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Module.h This file contains the declarations for the Module class.
pgo instr PGO instrumentation
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static void instrumentOneFunc(Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI, std::unordered_multimap< Comdat *, GlobalValue *> &ComdatMembers, bool IsCS)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:343
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
uint64_t scale(uint64_t Num) const
Scale a large integer.
reference get()
Returns a reference to the stored T value.
Definition: Error.h:532
bool isConditional() const
void dumpEdges(raw_ostream &OS, const Twine &Message) const
Definition: CFGMST.h:234
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
ModulePass * createPGOInstrumentationUseLegacyPass(StringRef Filename=StringRef(""), bool IsCS=false)
static cl::opt< std::string > PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path of profile data file. This is" "mainly for test purpose."))
amdgpu Simplify well known AMD library false FunctionCallee Callee
static void setCSFlagInHash(uint64_t &FuncHash)
Definition: InstrProf.h:861
BBInfo & getBBInfo(const BasicBlock *BB) const
Definition: CFGMST.h:81
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:627
const Comdat * getComdat() const
Definition: GlobalObject.h:105
pgo instr Read PGO instrumentation profile
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:807
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
std::vector< Instruction * > findIndirectCalls(Function &F)
Analysis providing branch probability information.
unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition: CFG.cpp:72
Profiling information for a single function.
Definition: InstrProf.h:689
Expected< InstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Definition: AsmWriter.cpp:4252
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Return the modified name for function F suitable to be used the key for profile lookup.
Definition: InstrProf.cpp:253
bool SplitIndirectBrCriticalEdges(Function &F, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr)
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:224
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
Definition: InstrProf.cpp:332
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:192
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
uint32_t Size
Definition: Profile.cpp:46
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2237
static cl::opt< unsigned > MaxNumAnnotations("icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore, cl::desc("Max number of annotations for a single indirect " "call callsite"))
pgo instr use
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
cl::opt< PGOViewCountsType > PGOViewCounts
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1954
const std::string to_string(const T &Value)
Definition: ScopedPrinter.h:61
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:136
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:503
LLVM Value Representation.
Definition: Value.h:73
void createIRLevelProfileFlagVar(Module &M, bool IsCS)
Definition: InstrProf.cpp:1135
void update(ArrayRef< char > Data)
Definition: JamCRC.cpp:91
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:127
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
IRTranslator LLVM IR MI
cl::opt< std::string > ViewBlockFreqFuncName
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Reader for the indexed binary instrprof format.
A container for analyses that lazily runs them and caches their results.
static void collectComdatMembers(Module &M, std::unordered_multimap< Comdat *, GlobalValue *> &ComdatMembers)
This header defines various interfaces for pass management in LLVM.
static std::string getSimpleNodeName(const BasicBlock *Node)
static cl::opt< bool > EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden, cl::desc("When this option is on, the annotated " "branch probability will be emitted as " "optimization remarks: -{Rpass|" "pass-remarks}=pgo-instrumentation"))
#define LLVM_DEBUG(X)
Definition: Debug.h:122
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, const Twine &RemappingPath="")
Factory method to create an indexed reader.
The optimization diagnostic interface.
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:485
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
const BasicBlock * getParent() const
Definition: Instruction.h:66
SelectionKind getSelectionKind() const
Definition: Comdat.h:44
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:1044