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