[llvm-exegesis] [NFC] Fixing typo.
[llvm-complete.git] / lib / Transforms / Instrumentation / PGOInstrumentation.cpp
blobbb2e3359881c077bd2c7f4cf3f2f7c6e10495cf9
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.
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.
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.
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.
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).
48 //===----------------------------------------------------------------------===//
50 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
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"
61 #include "llvm/ADT/iterator_range.h"
62 #include "llvm/Analysis/BlockFrequencyInfo.h"
63 #include "llvm/Analysis/BranchProbabilityInfo.h"
64 #include "llvm/Analysis/CFG.h"
65 #include "llvm/Analysis/IndirectCallVisitor.h"
66 #include "llvm/Analysis/LoopInfo.h"
67 #include "llvm/Analysis/OptimizationRemarkEmitter.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"
96 #include "llvm/ProfileData/InstrProf.h"
97 #include "llvm/ProfileData/InstrProfReader.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CommandLine.h"
101 #include "llvm/Support/DOTGraphTraits.h"
102 #include "llvm/Support/Debug.h"
103 #include "llvm/Support/Error.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/GraphWriter.h"
106 #include "llvm/Support/JamCRC.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Transforms/Instrumentation.h"
109 #include "llvm/Transforms/Utils/BasicBlockUtils.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>
120 using namespace llvm;
121 using ProfileCount = Function::ProfileCount;
123 #define DEBUG_TYPE "pgo-instrumentation"
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.");
136 // Command line option to specify the file to read profile from. This is
137 // mainly used for testing.
138 static cl::opt<std::string>
139 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
140 cl::value_desc("filename"),
141 cl::desc("Specify the path of profile data file. This is"
142 "mainly for test purpose."));
143 static cl::opt<std::string> PGOTestProfileRemappingFile(
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."));
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"));
155 // Command line option to set the maximum number of VP annotations to write to
156 // the metadata for a single indirect call callsite.
157 static cl::opt<unsigned> MaxNumAnnotations(
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"));
162 // Command line option to set the maximum number of value annotations
163 // to write to the metadata for a single memop intrinsic.
164 static cl::opt<unsigned> MaxNumMemOPAnnotations(
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"));
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.
171 static cl::opt<bool> DoComdatRenaming(
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"));
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."));
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."));
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."));
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. "));
207 // Command line option to turn on CFG dot or text dump of raw profile counts
208 static cl::opt<PGOViewCountsType> PGOViewRawCounts(
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.")));
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."));
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"));
234 // Command line option to turn on CFG dot dump after profile annotation.
235 // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
236 extern cl::opt<PGOViewCountsType> PGOViewCounts;
238 // Command line option to specify the name of the function for CFG dump
239 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
240 extern cl::opt<std::string> ViewBlockFreqFuncName;
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();
249 Value *Cond = BI->getCondition();
250 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
251 if (!CI)
252 return std::string();
254 std::string result;
255 raw_string_ostream OS(result);
256 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
257 CI->getOperand(0)->getType()->print(OS, true);
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";
271 OS.flush();
272 return result;
275 namespace {
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;
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;
296 SelectInstVisitor(Function &Func) : F(Func) {}
298 void countSelects(Function &Func) {
299 NSIs = 0;
300 Mode = VM_counting;
301 visit(Func);
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);
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);
326 void instrumentOneSelectInst(SelectInst &SI);
327 void annotateOneSelectInst(SelectInst &SI);
329 // Visit \p SI instruction and perform tasks according to visit mode.
330 void visitSelectInst(SelectInst &SI);
332 // Return the number of select instructions. This needs be called after
333 // countSelects().
334 unsigned getNumOfSelectInsts() const { return NSIs; }
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;
349 MemIntrinsicVisitor(Function &Func) : F(Func) {}
351 void countMemIntrinsics(Function &Func) {
352 NMemIs = 0;
353 Mode = VM_counting;
354 visit(Func);
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);
366 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
367 Candidates.clear();
368 Mode = VM_annotate;
369 visit(Func);
370 return Candidates;
373 // Visit the IR stream and annotate all mem intrinsic call instructions.
374 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
376 // Visit \p MI instruction and perform tasks according to visit mode.
377 void visitMemIntrinsic(MemIntrinsic &SI);
379 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
382 class PGOInstrumentationGenLegacyPass : public ModulePass {
383 public:
384 static char ID;
386 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
387 initializePGOInstrumentationGenLegacyPassPass(
388 *PassRegistry::getPassRegistry());
391 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
393 private:
394 bool runOnModule(Module &M) override;
396 void getAnalysisUsage(AnalysisUsage &AU) const override {
397 AU.addRequired<BlockFrequencyInfoWrapperPass>();
401 class PGOInstrumentationUseLegacyPass : public ModulePass {
402 public:
403 static char ID;
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;
410 initializePGOInstrumentationUseLegacyPassPass(
411 *PassRegistry::getPassRegistry());
414 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
416 private:
417 std::string ProfileFileName;
419 bool runOnModule(Module &M) override;
421 void getAnalysisUsage(AnalysisUsage &AU) const override {
422 AU.addRequired<BlockFrequencyInfoWrapperPass>();
426 } // end anonymous namespace
428 char PGOInstrumentationGenLegacyPass::ID = 0;
430 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
431 "PGO instrumentation.", false, false)
432 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
433 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
434 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
435 "PGO instrumentation.", false, false)
437 ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
438 return new PGOInstrumentationGenLegacyPass();
441 char PGOInstrumentationUseLegacyPass::ID = 0;
443 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
444 "Read PGO instrumentation profile.", false, false)
445 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
446 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
447 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
448 "Read PGO instrumentation profile.", false, false)
450 ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
451 return new PGOInstrumentationUseLegacyPass(Filename.str());
454 namespace {
456 /// An MST based instrumentation for PGO
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;
470 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
471 : SrcBB(Src), DestBB(Dest), Weight(W) {}
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();
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;
486 BBInfo(unsigned IX) : Group(this), Index(IX) {}
488 // Return the information string of this object.
489 const std::string infoString() const {
490 return (Twine("Index=") + Twine(Index)).str();
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;
499 // A map that stores the Comdat group in function F.
500 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
502 void computeCFGHash();
503 void renameComdatFunction();
505 public:
506 std::vector<std::vector<Instruction *>> ValueSites;
507 SelectInstVisitor SIVisitor;
508 MemIntrinsicVisitor MIVisitor;
509 std::string FuncName;
510 GlobalVariable *FuncNameVar;
512 // CFG hash value for this function.
513 uint64_t FunctionHash = 0;
515 // The Minimum Spanning Tree of function CFG.
516 CFGMST<Edge, BBInfo> MST;
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);
522 // Return the auxiliary BB information.
523 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
525 // Return the auxiliary BB information if available.
526 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
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);
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);
549 FuncName = getPGOFuncName(F);
550 computeCFGHash();
551 if (!ComdatMembers.empty())
552 renameComdatFunction();
553 LLVM_DEBUG(dumpInfo("after CFGMST"));
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++;
564 if (CreateGlobalVar)
565 FuncNameVar = createPGOFuncNameVar(F, FuncName);
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++;
575 return NumCounters + SIVisitor.getNumOfSelectInsts();
579 } // end anonymous namespace
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)));
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";);
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;
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;
633 return true;
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));
645 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
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()) {
653 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
654 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
655 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
656 F.setComdat(NewComdat);
657 return;
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());
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)));
673 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
674 continue;
676 // Must be a function.
677 Function *CF = dyn_cast<Function>(CM.second);
678 assert(CF);
679 CF->setComdat(NewComdat);
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;
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;
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;
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");
715 E->Removed = true;
716 return InstrBB;
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(
722 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
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();
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;
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++)});
748 // Now instrument select instructions:
749 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
750 FuncInfo.FunctionHash);
751 assert(I == NumCounters);
753 if (DisableValueProfiling)
754 return;
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++)});
773 NumOfPGOICall += NumIndirectCalls;
775 // Now instrument memop intrinsic calls.
776 FuncInfo.MIVisitor.instrumentMemIntrinsics(
777 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
780 namespace {
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;
787 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
788 : PGOEdge(Src, Dest, W) {}
790 // Set edge count value
791 void setEdgeCount(uint64_t Value) {
792 CountValue = Value;
793 CountValid = true;
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();
805 using DirectEdges = SmallVector<PGOUseEdge *, 2>;
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;
816 UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
818 UseBBInfo(unsigned IX, uint64_t C)
819 : BBInfo(IX), CountValue(C), CountValid(true) {}
821 // Set the profile count value for this BB.
822 void setBBInfoCount(uint64_t Value) {
823 CountValue = Value;
824 CountValid = true;
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();
835 } // end anonymous namespace
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;
845 return Total;
848 namespace {
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) {}
860 // Read counts for the instrumented BB from profile.
861 bool readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros);
863 // Populate the counts for all BBs.
864 void populateCounters();
866 // Set the branch weights based on the count values.
867 void setBranchWeights();
869 // Annotate the value profile call sites for all value kind.
870 void annotateValueSites();
872 // Annotate the value profile call sites for one value kind.
873 void annotateValueSites(uint32_t Kind);
875 // Annotate the irreducible loop header weights.
876 void annotateIrrLoopHeaderWeights();
878 // The hotness of the function from the profile count.
879 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
881 // Return the function hotness from the profile.
882 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
884 // Return the function hash.
885 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
887 // Return the profile record for this function;
888 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
890 // Return the auxiliary BB information.
891 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
892 return FuncInfo.getBBInfo(BB);
895 // Return the auxiliary BB information if available.
896 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
897 return FuncInfo.findBBInfo(BB);
900 Function &getFunc() const { return F; }
902 void dumpInfo(std::string Str = "") const {
903 FuncInfo.dumpInfo(Str);
906 uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
907 private:
908 Function &F;
909 Module *M;
910 BlockFrequencyInfo *BFI;
912 // This member stores the shared information with class PGOGenFunc.
913 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
915 // The maximum count value in the profile. This is only used in PGO use
916 // compilation.
917 uint64_t ProgramMaxCount;
919 // Position of counter that remains to be read.
920 uint32_t CountPosition = 0;
922 // Total size of the profile count for this function.
923 uint32_t ProfileCountSize = 0;
925 // ProfileRecord for this function.
926 InstrProfRecord ProfileRecord;
928 // Function hotness info derived from profile.
929 FuncFreqAttr FreqAttr;
931 // Find the Instrumented BB and set the value.
932 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
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);
938 // Return FuncName string;
939 const std::string getFuncName() const { return FuncInfo.FuncName; }
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;
958 } // end anonymous namespace
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());
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;
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);
994 ProfileCountSize = CountFromProfile.size();
995 CountPosition = I;
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);
1006 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1007 getBBInfo(E->DestBB).UnknownCountInEdge--;
1008 return;
1010 llvm_unreachable("Cannot find the unknown count edge");
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 =
1031 NoPGOWarnMismatch ||
1032 (NoPGOWarnMismatchComdat &&
1033 (F.hasComdat() ||
1034 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
1037 if (SkipWarning)
1038 return;
1040 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
1041 Ctx.diagnose(
1042 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1044 return false;
1046 ProfileRecord = std::move(Result.get());
1047 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
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];
1056 AllZeros = (ValueSum == 0);
1058 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
1060 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1061 getBBInfo(nullptr).UnknownCountInEdge = 2;
1063 setInstrumentedCounts(CountFromProfile);
1064 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
1065 return true;
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;
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++;
1085 if (!E->CountValid)
1086 continue;
1087 DestInfo.UnknownCountInEdge--;
1088 SrcInfo.UnknownCountOutEdge--;
1091 bool Changes = true;
1092 unsigned NumPasses = 0;
1093 while (Changes) {
1094 NumPasses++;
1095 Changes = false;
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;
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;
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;
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");
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);
1157 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1159 // Now annotate select instructions
1160 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1161 assert(CountPosition == ProfileCountSize);
1163 LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
1166 // Assign the scaled count values to the BB with multiple out edges.
1167 void PGOUseFunc::setBranchWeights() {
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;
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;
1197 setProfMetadata(M, TI, EdgeCounts, MaxCount);
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;
1206 return false;
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);
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);
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);
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;
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;
1275 llvm_unreachable("Unknown visiting mode");
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;
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;
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;
1312 llvm_unreachable("Unknown visiting mode");
1315 // Traverse all valuesites and annotate the instructions for all value kind.
1316 void PGOUseFunc::annotateValueSites() {
1317 if (DisableValueProfiling)
1318 return;
1320 // Create the PGOFuncName meta data.
1321 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
1323 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1324 annotateValueSites(Kind);
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;
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++;
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.
1356 static void createIRLevelProfileFlagVariable(Module &M) {
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))));
1372 // Collect the set of members for each Comdat in module M and store
1373 // in ComdatMembers.
1374 static void collectComdatMembers(
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));
1390 static bool InstrumentAllFunctions(
1391 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1392 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
1393 createIRLevelProfileFlagVariable(M);
1394 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1395 collectComdatMembers(M, ComdatMembers);
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);
1404 return true;
1407 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
1408 if (skipModule(M))
1409 return false;
1411 auto LookupBPI = [this](Function &F) {
1412 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1414 auto LookupBFI = [this](Function &F) {
1415 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1417 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1420 PreservedAnalyses PGOInstrumentationGen::run(Module &M,
1421 ModuleAnalysisManager &AM) {
1422 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1423 auto LookupBPI = [&FAM](Function &F) {
1424 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1427 auto LookupBFI = [&FAM](Function &F) {
1428 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1431 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1432 return PreservedAnalyses::all();
1434 return PreservedAnalyses::none();
1437 static bool annotateAllFunctions(
1438 Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName,
1439 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
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()));
1451 return false;
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;
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;
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.
1479 SplitIndirectBrCriticalEdges(F, BPI, BFI);
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;
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());
1514 if (PGOViewRawCounts != PGOVCT_None &&
1515 (ViewBlockFreqFuncName.empty() ||
1516 F.getName().equals(ViewBlockFreqFuncName))) {
1517 if (PGOViewRawCounts == PGOVCT_Graph)
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();
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");
1538 for (auto &F : ColdFunctions) {
1539 F->addFnAttr(Attribute::Cold);
1540 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
1541 << "\n");
1543 return true;
1546 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename,
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;
1556 PreservedAnalyses PGOInstrumentationUse::run(Module &M,
1557 ModuleAnalysisManager &AM) {
1559 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1560 auto LookupBPI = [&FAM](Function &F) {
1561 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1564 auto LookupBFI = [&FAM](Function &F) {
1565 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1568 if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName,
1569 LookupBPI, LookupBFI))
1570 return PreservedAnalyses::all();
1572 return PreservedAnalyses::none();
1575 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1576 if (skipModule(M))
1577 return false;
1579 auto LookupBPI = [this](Function &F) {
1580 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1582 auto LookupBFI = [this](Function &F) {
1583 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
1586 return annotateAllFunctions(M, ProfileFileName, "", LookupBPI, LookupBFI);
1589 static std::string getSimpleNodeName(const BasicBlock *Node) {
1590 if (!Node->getName().empty())
1591 return Node->getName();
1593 std::string SimpleNodeName;
1594 raw_string_ostream OS(SimpleNodeName);
1595 Node->printAsOperand(OS, false);
1596 return OS.str();
1599 void llvm::setProfMetadata(Module *M, Instruction *TI,
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));
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;
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();
1634 OptimizationRemarkEmitter ORE(F);
1635 ORE.emit([&]() {
1636 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1637 << BrCondStr << " is true with probability : " << BranchProbStr;
1642 namespace llvm {
1644 void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1645 MDBuilder MDB(M->getContext());
1646 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1647 MDB.createIrrLoopHeaderWeight(Count));
1650 template <> struct GraphTraits<PGOUseFunc *> {
1651 using NodeRef = const BasicBlock *;
1652 using ChildIteratorType = succ_const_iterator;
1653 using nodes_iterator = pointer_iterator<Function::const_iterator>;
1655 static NodeRef getEntryNode(const PGOUseFunc *G) {
1656 return &G->getFunc().front();
1659 static ChildIteratorType child_begin(const NodeRef N) {
1660 return succ_begin(N);
1663 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1665 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1666 return nodes_iterator(G->getFunc().begin());
1669 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1670 return nodes_iterator(G->getFunc().end());
1674 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1675 explicit DOTGraphTraits(bool isSimple = false)
1676 : DefaultDOTGraphTraits(isSimple) {}
1678 static std::string getGraphName(const PGOUseFunc *G) {
1679 return G->getFunc().getName();
1682 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1683 std::string Result;
1684 raw_string_ostream OS(Result);
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";
1694 if (!PGOInstrSelect)
1695 return Result;
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";
1710 return Result;
1714 } // end namespace llvm