1 //===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
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
7 //===----------------------------------------------------------------------===//
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
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 //===----------------------------------------------------------------------===//
51 #include "llvm/ADT/APInt.h"
52 #include "llvm/ADT/ArrayRef.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/ADT/Triple.h"
58 #include "llvm/ADT/Twine.h"
59 #include "llvm/ADT/iterator.h"
60 #include "llvm/ADT/iterator_range.h"
61 #include "llvm/Analysis/BlockFrequencyInfo.h"
62 #include "llvm/Analysis/BranchProbabilityInfo.h"
63 #include "llvm/Analysis/CFG.h"
64 #include "llvm/Analysis/IndirectCallVisitor.h"
65 #include "llvm/Analysis/LoopInfo.h"
66 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
67 #include "llvm/Analysis/ProfileSummaryInfo.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/Instrumentation/PGOInstrumentation.h"
110 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
111 #include "llvm/Transforms/Utils/MisExpect.h"
118 #include <unordered_map>
122 using namespace llvm
;
123 using ProfileCount
= Function::ProfileCount
;
125 #define DEBUG_TYPE "pgo-instrumentation"
127 STATISTIC(NumOfPGOInstrument
, "Number of edges instrumented.");
128 STATISTIC(NumOfPGOSelectInsts
, "Number of select instruction instrumented.");
129 STATISTIC(NumOfPGOMemIntrinsics
, "Number of mem intrinsics instrumented.");
130 STATISTIC(NumOfPGOEdge
, "Number of edges.");
131 STATISTIC(NumOfPGOBB
, "Number of basic-blocks.");
132 STATISTIC(NumOfPGOSplit
, "Number of critical edge splits.");
133 STATISTIC(NumOfPGOFunc
, "Number of functions having valid profile counts.");
134 STATISTIC(NumOfPGOMismatch
, "Number of functions having mismatch profile.");
135 STATISTIC(NumOfPGOMissing
, "Number of functions without profile.");
136 STATISTIC(NumOfPGOICall
, "Number of indirect call value instrumentations.");
137 STATISTIC(NumOfCSPGOInstrument
, "Number of edges instrumented in CSPGO.");
138 STATISTIC(NumOfCSPGOSelectInsts
,
139 "Number of select instruction instrumented in CSPGO.");
140 STATISTIC(NumOfCSPGOMemIntrinsics
,
141 "Number of mem intrinsics instrumented in CSPGO.");
142 STATISTIC(NumOfCSPGOEdge
, "Number of edges in CSPGO.");
143 STATISTIC(NumOfCSPGOBB
, "Number of basic-blocks in CSPGO.");
144 STATISTIC(NumOfCSPGOSplit
, "Number of critical edge splits in CSPGO.");
145 STATISTIC(NumOfCSPGOFunc
,
146 "Number of functions having valid profile counts in CSPGO.");
147 STATISTIC(NumOfCSPGOMismatch
,
148 "Number of functions having mismatch profile in CSPGO.");
149 STATISTIC(NumOfCSPGOMissing
, "Number of functions without profile in CSPGO.");
151 // Command line option to specify the file to read profile from. This is
152 // mainly used for testing.
153 static cl::opt
<std::string
>
154 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden
,
155 cl::value_desc("filename"),
156 cl::desc("Specify the path of profile data file. This is"
157 "mainly for test purpose."));
158 static cl::opt
<std::string
> PGOTestProfileRemappingFile(
159 "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden
,
160 cl::value_desc("filename"),
161 cl::desc("Specify the path of profile remapping file. This is mainly for "
164 // Command line option to disable value profiling. The default is false:
165 // i.e. value profiling is enabled by default. This is for debug purpose.
166 static cl::opt
<bool> DisableValueProfiling("disable-vp", cl::init(false),
168 cl::desc("Disable Value Profiling"));
170 // Command line option to set the maximum number of VP annotations to write to
171 // the metadata for a single indirect call callsite.
172 static cl::opt
<unsigned> MaxNumAnnotations(
173 "icp-max-annotations", cl::init(3), cl::Hidden
, cl::ZeroOrMore
,
174 cl::desc("Max number of annotations for a single indirect "
177 // Command line option to set the maximum number of value annotations
178 // to write to the metadata for a single memop intrinsic.
179 static cl::opt
<unsigned> MaxNumMemOPAnnotations(
180 "memop-max-annotations", cl::init(4), cl::Hidden
, cl::ZeroOrMore
,
181 cl::desc("Max number of preicise value annotations for a single memop"
184 // Command line option to control appending FunctionHash to the name of a COMDAT
185 // function. This is to avoid the hash mismatch caused by the preinliner.
186 static cl::opt
<bool> DoComdatRenaming(
187 "do-comdat-renaming", cl::init(false), cl::Hidden
,
188 cl::desc("Append function hash to the name of COMDAT function to avoid "
189 "function hash mismatch due to the preinliner"));
191 // Command line option to enable/disable the warning about missing profile
194 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden
,
195 cl::desc("Use this option to turn on/off "
196 "warnings about missing profile data for "
199 // Command line option to enable/disable the warning about a hash mismatch in
202 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden
,
203 cl::desc("Use this option to turn off/on "
204 "warnings about profile cfg mismatch."));
206 // Command line option to enable/disable the warning about a hash mismatch in
207 // the profile data for Comdat functions, which often turns out to be false
208 // positive due to the pre-instrumentation inline.
210 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
212 cl::desc("The option is used to turn on/off "
213 "warnings about hash mismatch for comdat "
216 // Command line option to enable/disable select instruction instrumentation.
218 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden
,
219 cl::desc("Use this option to turn on/off SELECT "
220 "instruction instrumentation. "));
222 // Command line option to turn on CFG dot or text dump of raw profile counts
223 static cl::opt
<PGOViewCountsType
> PGOViewRawCounts(
224 "pgo-view-raw-counts", cl::Hidden
,
225 cl::desc("A boolean option to show CFG dag or text "
226 "with raw profile counts from "
227 "profile data. See also option "
228 "-pgo-view-counts. To limit graph "
229 "display to only one function, use "
230 "filtering option -view-bfi-func-name."),
231 cl::values(clEnumValN(PGOVCT_None
, "none", "do not show."),
232 clEnumValN(PGOVCT_Graph
, "graph", "show a graph."),
233 clEnumValN(PGOVCT_Text
, "text", "show in text.")));
235 // Command line option to enable/disable memop intrinsic call.size profiling.
237 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden
,
238 cl::desc("Use this option to turn on/off "
239 "memory intrinsic size profiling."));
241 // Emit branch probability as optimization remarks.
243 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden
,
244 cl::desc("When this option is on, the annotated "
245 "branch probability will be emitted as "
246 "optimization remarks: -{Rpass|"
247 "pass-remarks}=pgo-instrumentation"));
249 // Command line option to turn on CFG dot dump after profile annotation.
250 // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
251 extern cl::opt
<PGOViewCountsType
> PGOViewCounts
;
253 // Command line option to specify the name of the function for CFG dump
254 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
255 extern cl::opt
<std::string
> ViewBlockFreqFuncName
;
257 // Return a string describing the branch condition that can be
258 // used in static branch probability heuristics:
259 static std::string
getBranchCondString(Instruction
*TI
) {
260 BranchInst
*BI
= dyn_cast
<BranchInst
>(TI
);
261 if (!BI
|| !BI
->isConditional())
262 return std::string();
264 Value
*Cond
= BI
->getCondition();
265 ICmpInst
*CI
= dyn_cast
<ICmpInst
>(Cond
);
267 return std::string();
270 raw_string_ostream
OS(result
);
271 OS
<< CmpInst::getPredicateName(CI
->getPredicate()) << "_";
272 CI
->getOperand(0)->getType()->print(OS
, true);
274 Value
*RHS
= CI
->getOperand(1);
275 ConstantInt
*CV
= dyn_cast
<ConstantInt
>(RHS
);
279 else if (CV
->isOne())
281 else if (CV
->isMinusOne())
292 /// The select instruction visitor plays three roles specified
293 /// by the mode. In \c VM_counting mode, it simply counts the number of
294 /// select instructions. In \c VM_instrument mode, it inserts code to count
295 /// the number times TrueValue of select is taken. In \c VM_annotate mode,
296 /// it reads the profile data and annotate the select instruction with metadata.
297 enum VisitMode
{ VM_counting
, VM_instrument
, VM_annotate
};
300 /// Instruction Visitor class to visit select instructions.
301 struct SelectInstVisitor
: public InstVisitor
<SelectInstVisitor
> {
303 unsigned NSIs
= 0; // Number of select instructions instrumented.
304 VisitMode Mode
= VM_counting
; // Visiting mode.
305 unsigned *CurCtrIdx
= nullptr; // Pointer to current counter index.
306 unsigned TotalNumCtrs
= 0; // Total number of counters
307 GlobalVariable
*FuncNameVar
= nullptr;
308 uint64_t FuncHash
= 0;
309 PGOUseFunc
*UseFunc
= nullptr;
311 SelectInstVisitor(Function
&Func
) : F(Func
) {}
313 void countSelects(Function
&Func
) {
319 // Visit the IR stream and instrument all select instructions. \p
320 // Ind is a pointer to the counter index variable; \p TotalNC
321 // is the total number of counters; \p FNV is the pointer to the
322 // PGO function name var; \p FHash is the function hash.
323 void instrumentSelects(Function
&Func
, unsigned *Ind
, unsigned TotalNC
,
324 GlobalVariable
*FNV
, uint64_t FHash
) {
325 Mode
= VM_instrument
;
327 TotalNumCtrs
= TotalNC
;
333 // Visit the IR stream and annotate all select instructions.
334 void annotateSelects(Function
&Func
, PGOUseFunc
*UF
, unsigned *Ind
) {
341 void instrumentOneSelectInst(SelectInst
&SI
);
342 void annotateOneSelectInst(SelectInst
&SI
);
344 // Visit \p SI instruction and perform tasks according to visit mode.
345 void visitSelectInst(SelectInst
&SI
);
347 // Return the number of select instructions. This needs be called after
349 unsigned getNumOfSelectInsts() const { return NSIs
; }
352 /// Instruction Visitor class to visit memory intrinsic calls.
353 struct MemIntrinsicVisitor
: public InstVisitor
<MemIntrinsicVisitor
> {
355 unsigned NMemIs
= 0; // Number of memIntrinsics instrumented.
356 VisitMode Mode
= VM_counting
; // Visiting mode.
357 unsigned CurCtrId
= 0; // Current counter index.
358 unsigned TotalNumCtrs
= 0; // Total number of counters
359 GlobalVariable
*FuncNameVar
= nullptr;
360 uint64_t FuncHash
= 0;
361 PGOUseFunc
*UseFunc
= nullptr;
362 std::vector
<Instruction
*> Candidates
;
364 MemIntrinsicVisitor(Function
&Func
) : F(Func
) {}
366 void countMemIntrinsics(Function
&Func
) {
372 void instrumentMemIntrinsics(Function
&Func
, unsigned TotalNC
,
373 GlobalVariable
*FNV
, uint64_t FHash
) {
374 Mode
= VM_instrument
;
375 TotalNumCtrs
= TotalNC
;
381 std::vector
<Instruction
*> findMemIntrinsics(Function
&Func
) {
388 // Visit the IR stream and annotate all mem intrinsic call instructions.
389 void instrumentOneMemIntrinsic(MemIntrinsic
&MI
);
391 // Visit \p MI instruction and perform tasks according to visit mode.
392 void visitMemIntrinsic(MemIntrinsic
&SI
);
394 unsigned getNumOfMemIntrinsics() const { return NMemIs
; }
397 class PGOInstrumentationGenLegacyPass
: public ModulePass
{
401 PGOInstrumentationGenLegacyPass(bool IsCS
= false)
402 : ModulePass(ID
), IsCS(IsCS
) {
403 initializePGOInstrumentationGenLegacyPassPass(
404 *PassRegistry::getPassRegistry());
407 StringRef
getPassName() const override
{ return "PGOInstrumentationGenPass"; }
410 // Is this is context-sensitive instrumentation.
412 bool runOnModule(Module
&M
) override
;
414 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
415 AU
.addRequired
<BlockFrequencyInfoWrapperPass
>();
419 class PGOInstrumentationUseLegacyPass
: public ModulePass
{
423 // Provide the profile filename as the parameter.
424 PGOInstrumentationUseLegacyPass(std::string Filename
= "", bool IsCS
= false)
425 : ModulePass(ID
), ProfileFileName(std::move(Filename
)), IsCS(IsCS
) {
426 if (!PGOTestProfileFile
.empty())
427 ProfileFileName
= PGOTestProfileFile
;
428 initializePGOInstrumentationUseLegacyPassPass(
429 *PassRegistry::getPassRegistry());
432 StringRef
getPassName() const override
{ return "PGOInstrumentationUsePass"; }
435 std::string ProfileFileName
;
436 // Is this is context-sensitive instrumentation use.
439 bool runOnModule(Module
&M
) override
;
441 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
442 AU
.addRequired
<ProfileSummaryInfoWrapperPass
>();
443 AU
.addRequired
<BlockFrequencyInfoWrapperPass
>();
447 class PGOInstrumentationGenCreateVarLegacyPass
: public ModulePass
{
450 StringRef
getPassName() const override
{
451 return "PGOInstrumentationGenCreateVarPass";
453 PGOInstrumentationGenCreateVarLegacyPass(std::string CSInstrName
= "")
454 : ModulePass(ID
), InstrProfileOutput(CSInstrName
) {
455 initializePGOInstrumentationGenCreateVarLegacyPassPass(
456 *PassRegistry::getPassRegistry());
460 bool runOnModule(Module
&M
) override
{
461 createProfileFileNameVar(M
, InstrProfileOutput
);
462 createIRLevelProfileFlagVar(M
, true);
465 std::string InstrProfileOutput
;
468 } // end anonymous namespace
470 char PGOInstrumentationGenLegacyPass::ID
= 0;
472 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass
, "pgo-instr-gen",
473 "PGO instrumentation.", false, false)
474 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass
)
475 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass
)
476 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass
, "pgo-instr-gen",
477 "PGO instrumentation.", false, false)
479 ModulePass
*llvm::createPGOInstrumentationGenLegacyPass(bool IsCS
) {
480 return new PGOInstrumentationGenLegacyPass(IsCS
);
483 char PGOInstrumentationUseLegacyPass::ID
= 0;
485 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass
, "pgo-instr-use",
486 "Read PGO instrumentation profile.", false, false)
487 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass
)
488 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass
)
489 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass
)
490 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass
, "pgo-instr-use",
491 "Read PGO instrumentation profile.", false, false)
493 ModulePass
*llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename
,
495 return new PGOInstrumentationUseLegacyPass(Filename
.str(), IsCS
);
498 char PGOInstrumentationGenCreateVarLegacyPass::ID
= 0;
500 INITIALIZE_PASS(PGOInstrumentationGenCreateVarLegacyPass
,
501 "pgo-instr-gen-create-var",
502 "Create PGO instrumentation version variable for CSPGO.", false,
506 llvm::createPGOInstrumentationGenCreateVarLegacyPass(StringRef CSInstrName
) {
507 return new PGOInstrumentationGenCreateVarLegacyPass(CSInstrName
);
512 /// An MST based instrumentation for PGO
514 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
515 /// in the function level.
517 // This class implements the CFG edges. Note the CFG can be a multi-graph.
518 // So there might be multiple edges with same SrcBB and DestBB.
519 const BasicBlock
*SrcBB
;
520 const BasicBlock
*DestBB
;
523 bool Removed
= false;
524 bool IsCritical
= false;
526 PGOEdge(const BasicBlock
*Src
, const BasicBlock
*Dest
, uint64_t W
= 1)
527 : SrcBB(Src
), DestBB(Dest
), Weight(W
) {}
529 // Return the information string of an edge.
530 const std::string
infoString() const {
531 return (Twine(Removed
? "-" : " ") + (InMST
? " " : "*") +
532 (IsCritical
? "c" : " ") + " W=" + Twine(Weight
)).str();
536 // This class stores the auxiliary information for each BB.
542 BBInfo(unsigned IX
) : Group(this), Index(IX
) {}
544 // Return the information string of this object.
545 const std::string
infoString() const {
546 return (Twine("Index=") + Twine(Index
)).str();
549 // Empty function -- only applicable to UseBBInfo.
550 void addOutEdge(PGOEdge
*E LLVM_ATTRIBUTE_UNUSED
) {}
552 // Empty function -- only applicable to UseBBInfo.
553 void addInEdge(PGOEdge
*E LLVM_ATTRIBUTE_UNUSED
) {}
556 // This class implements the CFG edges. Note the CFG can be a multi-graph.
557 template <class Edge
, class BBInfo
> class FuncPGOInstrumentation
{
561 // Is this is context-sensitive instrumentation.
564 // A map that stores the Comdat group in function F.
565 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
;
567 void computeCFGHash();
568 void renameComdatFunction();
571 std::vector
<std::vector
<Instruction
*>> ValueSites
;
572 SelectInstVisitor SIVisitor
;
573 MemIntrinsicVisitor MIVisitor
;
574 std::string FuncName
;
575 GlobalVariable
*FuncNameVar
;
577 // CFG hash value for this function.
578 uint64_t FunctionHash
= 0;
580 // The Minimum Spanning Tree of function CFG.
581 CFGMST
<Edge
, BBInfo
> MST
;
583 // Collect all the BBs that will be instrumented, and store them in
585 void getInstrumentBBs(std::vector
<BasicBlock
*> &InstrumentBBs
);
587 // Give an edge, find the BB that will be instrumented.
588 // Return nullptr if there is no BB to be instrumented.
589 BasicBlock
*getInstrBB(Edge
*E
);
591 // Return the auxiliary BB information.
592 BBInfo
&getBBInfo(const BasicBlock
*BB
) const { return MST
.getBBInfo(BB
); }
594 // Return the auxiliary BB information if available.
595 BBInfo
*findBBInfo(const BasicBlock
*BB
) const { return MST
.findBBInfo(BB
); }
597 // Dump edges and BB information.
598 void dumpInfo(std::string Str
= "") const {
599 MST
.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName
+ " Hash: " +
600 Twine(FunctionHash
) + "\t" + Str
);
603 FuncPGOInstrumentation(
605 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
,
606 bool CreateGlobalVar
= false, BranchProbabilityInfo
*BPI
= nullptr,
607 BlockFrequencyInfo
*BFI
= nullptr, bool IsCS
= false)
608 : F(Func
), IsCS(IsCS
), ComdatMembers(ComdatMembers
),
609 ValueSites(IPVK_Last
+ 1), SIVisitor(Func
), MIVisitor(Func
),
611 // This should be done before CFG hash computation.
612 SIVisitor
.countSelects(Func
);
613 MIVisitor
.countMemIntrinsics(Func
);
615 NumOfPGOSelectInsts
+= SIVisitor
.getNumOfSelectInsts();
616 NumOfPGOMemIntrinsics
+= MIVisitor
.getNumOfMemIntrinsics();
617 NumOfPGOBB
+= MST
.BBInfos
.size();
618 ValueSites
[IPVK_IndirectCallTarget
] = findIndirectCalls(Func
);
620 NumOfCSPGOSelectInsts
+= SIVisitor
.getNumOfSelectInsts();
621 NumOfCSPGOMemIntrinsics
+= MIVisitor
.getNumOfMemIntrinsics();
622 NumOfCSPGOBB
+= MST
.BBInfos
.size();
624 ValueSites
[IPVK_MemOPSize
] = MIVisitor
.findMemIntrinsics(Func
);
626 FuncName
= getPGOFuncName(F
);
628 if (!ComdatMembers
.empty())
629 renameComdatFunction();
630 LLVM_DEBUG(dumpInfo("after CFGMST"));
632 for (auto &E
: MST
.AllEdges
) {
635 IsCS
? NumOfCSPGOEdge
++ : NumOfPGOEdge
++;
637 IsCS
? NumOfCSPGOInstrument
++ : NumOfPGOInstrument
++;
641 FuncNameVar
= createPGOFuncNameVar(F
, FuncName
);
645 } // end anonymous namespace
647 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
648 // value of each BB in the CFG. The higher 32 bits record the number of edges.
649 template <class Edge
, class BBInfo
>
650 void FuncPGOInstrumentation
<Edge
, BBInfo
>::computeCFGHash() {
651 std::vector
<char> Indexes
;
654 const Instruction
*TI
= BB
.getTerminator();
655 for (unsigned I
= 0, E
= TI
->getNumSuccessors(); I
!= E
; ++I
) {
656 BasicBlock
*Succ
= TI
->getSuccessor(I
);
657 auto BI
= findBBInfo(Succ
);
660 uint32_t Index
= BI
->Index
;
661 for (int J
= 0; J
< 4; J
++)
662 Indexes
.push_back((char)(Index
>> (J
* 8)));
667 // Hash format for context sensitive profile. Reserve 4 bits for other
669 FunctionHash
= (uint64_t)SIVisitor
.getNumOfSelectInsts() << 56 |
670 (uint64_t)ValueSites
[IPVK_IndirectCallTarget
].size() << 48 |
671 //(uint64_t)ValueSites[IPVK_MemOPSize].size() << 40 |
672 (uint64_t)MST
.AllEdges
.size() << 32 | JC
.getCRC();
673 // Reserve bit 60-63 for other information purpose.
674 FunctionHash
&= 0x0FFFFFFFFFFFFFFF;
676 NamedInstrProfRecord::setCSFlagInHash(FunctionHash
);
677 LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F
.getName() << ":\n"
678 << " CRC = " << JC
.getCRC()
679 << ", Selects = " << SIVisitor
.getNumOfSelectInsts()
680 << ", Edges = " << MST
.AllEdges
.size() << ", ICSites = "
681 << ValueSites
[IPVK_IndirectCallTarget
].size()
682 << ", Hash = " << FunctionHash
<< "\n";);
685 // Check if we can safely rename this Comdat function.
686 static bool canRenameComdat(
688 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
) {
689 if (!DoComdatRenaming
|| !canRenameComdatFunc(F
, true))
692 // FIXME: Current only handle those Comdat groups that only containing one
693 // function and function aliases.
694 // (1) For a Comdat group containing multiple functions, we need to have a
695 // unique postfix based on the hashes for each function. There is a
696 // non-trivial code refactoring to do this efficiently.
697 // (2) Variables can not be renamed, so we can not rename Comdat function in a
698 // group including global vars.
699 Comdat
*C
= F
.getComdat();
700 for (auto &&CM
: make_range(ComdatMembers
.equal_range(C
))) {
701 if (dyn_cast
<GlobalAlias
>(CM
.second
))
703 Function
*FM
= dyn_cast
<Function
>(CM
.second
);
710 // Append the CFGHash to the Comdat function name.
711 template <class Edge
, class BBInfo
>
712 void FuncPGOInstrumentation
<Edge
, BBInfo
>::renameComdatFunction() {
713 if (!canRenameComdat(F
, ComdatMembers
))
715 std::string OrigName
= F
.getName().str();
716 std::string NewFuncName
=
717 Twine(F
.getName() + "." + Twine(FunctionHash
)).str();
718 F
.setName(Twine(NewFuncName
));
719 GlobalAlias::create(GlobalValue::WeakAnyLinkage
, OrigName
, &F
);
720 FuncName
= Twine(FuncName
+ "." + Twine(FunctionHash
)).str();
722 Module
*M
= F
.getParent();
723 // For AvailableExternallyLinkage functions, change the linkage to
724 // LinkOnceODR and put them into comdat. This is because after renaming, there
725 // is no backup external copy available for the function.
726 if (!F
.hasComdat()) {
727 assert(F
.getLinkage() == GlobalValue::AvailableExternallyLinkage
);
728 NewComdat
= M
->getOrInsertComdat(StringRef(NewFuncName
));
729 F
.setLinkage(GlobalValue::LinkOnceODRLinkage
);
730 F
.setComdat(NewComdat
);
734 // This function belongs to a single function Comdat group.
735 Comdat
*OrigComdat
= F
.getComdat();
736 std::string NewComdatName
=
737 Twine(OrigComdat
->getName() + "." + Twine(FunctionHash
)).str();
738 NewComdat
= M
->getOrInsertComdat(StringRef(NewComdatName
));
739 NewComdat
->setSelectionKind(OrigComdat
->getSelectionKind());
741 for (auto &&CM
: make_range(ComdatMembers
.equal_range(OrigComdat
))) {
742 if (GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(CM
.second
)) {
743 // For aliases, change the name directly.
744 assert(dyn_cast
<Function
>(GA
->getAliasee()->stripPointerCasts()) == &F
);
745 std::string OrigGAName
= GA
->getName().str();
746 GA
->setName(Twine(GA
->getName() + "." + Twine(FunctionHash
)));
747 GlobalAlias::create(GlobalValue::WeakAnyLinkage
, OrigGAName
, GA
);
750 // Must be a function.
751 Function
*CF
= dyn_cast
<Function
>(CM
.second
);
753 CF
->setComdat(NewComdat
);
757 // Collect all the BBs that will be instruments and return them in
758 // InstrumentBBs and setup InEdges/OutEdge for UseBBInfo.
759 template <class Edge
, class BBInfo
>
760 void FuncPGOInstrumentation
<Edge
, BBInfo
>::getInstrumentBBs(
761 std::vector
<BasicBlock
*> &InstrumentBBs
) {
762 // Use a worklist as we will update the vector during the iteration.
763 std::vector
<Edge
*> EdgeList
;
764 EdgeList
.reserve(MST
.AllEdges
.size());
765 for (auto &E
: MST
.AllEdges
)
766 EdgeList
.push_back(E
.get());
768 for (auto &E
: EdgeList
) {
769 BasicBlock
*InstrBB
= getInstrBB(E
);
771 InstrumentBBs
.push_back(InstrBB
);
774 // Set up InEdges/OutEdges for all BBs.
775 for (auto &E
: MST
.AllEdges
) {
778 const BasicBlock
*SrcBB
= E
->SrcBB
;
779 const BasicBlock
*DestBB
= E
->DestBB
;
780 BBInfo
&SrcInfo
= getBBInfo(SrcBB
);
781 BBInfo
&DestInfo
= getBBInfo(DestBB
);
782 SrcInfo
.addOutEdge(E
.get());
783 DestInfo
.addInEdge(E
.get());
787 // Given a CFG E to be instrumented, find which BB to place the instrumented
788 // code. The function will split the critical edge if necessary.
789 template <class Edge
, class BBInfo
>
790 BasicBlock
*FuncPGOInstrumentation
<Edge
, BBInfo
>::getInstrBB(Edge
*E
) {
791 if (E
->InMST
|| E
->Removed
)
794 BasicBlock
*SrcBB
= const_cast<BasicBlock
*>(E
->SrcBB
);
795 BasicBlock
*DestBB
= const_cast<BasicBlock
*>(E
->DestBB
);
796 // For a fake edge, instrument the real BB.
797 if (SrcBB
== nullptr)
799 if (DestBB
== nullptr)
802 auto canInstrument
= [](BasicBlock
*BB
) -> BasicBlock
* {
803 // There are basic blocks (such as catchswitch) cannot be instrumented.
804 // If the returned first insertion point is the end of BB, skip this BB.
805 if (BB
->getFirstInsertionPt() == BB
->end())
810 // Instrument the SrcBB if it has a single successor,
811 // otherwise, the DestBB if this is not a critical edge.
812 Instruction
*TI
= SrcBB
->getTerminator();
813 if (TI
->getNumSuccessors() <= 1)
814 return canInstrument(SrcBB
);
816 return canInstrument(DestBB
);
818 unsigned SuccNum
= GetSuccessorNumber(SrcBB
, DestBB
);
819 BasicBlock
*InstrBB
= SplitCriticalEdge(TI
, SuccNum
);
822 dbgs() << "Fail to split critical edge: not instrument this edge.\n");
825 // For a critical edge, we have to split. Instrument the newly
827 IsCS
? NumOfCSPGOSplit
++ : NumOfPGOSplit
++;
828 LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB
).Index
829 << " --> " << getBBInfo(DestBB
).Index
<< "\n");
830 // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB.
831 MST
.addEdge(SrcBB
, InstrBB
, 0);
832 // Second one: Add new edge of InstrBB->DestBB.
833 Edge
&NewEdge1
= MST
.addEdge(InstrBB
, DestBB
, 0);
834 NewEdge1
.InMST
= true;
837 return canInstrument(InstrBB
);
840 // Visit all edge and instrument the edges not in MST, and do value profiling.
841 // Critical edges will be split.
842 static void instrumentOneFunc(
843 Function
&F
, Module
*M
, BranchProbabilityInfo
*BPI
, BlockFrequencyInfo
*BFI
,
844 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
,
846 // Split indirectbr critical edges here before computing the MST rather than
847 // later in getInstrBB() to avoid invalidating it.
848 SplitIndirectBrCriticalEdges(F
, BPI
, BFI
);
850 FuncPGOInstrumentation
<PGOEdge
, BBInfo
> FuncInfo(F
, ComdatMembers
, true, BPI
,
852 std::vector
<BasicBlock
*> InstrumentBBs
;
853 FuncInfo
.getInstrumentBBs(InstrumentBBs
);
854 unsigned NumCounters
=
855 InstrumentBBs
.size() + FuncInfo
.SIVisitor
.getNumOfSelectInsts();
858 Type
*I8PtrTy
= Type::getInt8PtrTy(M
->getContext());
859 for (auto *InstrBB
: InstrumentBBs
) {
860 IRBuilder
<> Builder(InstrBB
, InstrBB
->getFirstInsertionPt());
861 assert(Builder
.GetInsertPoint() != InstrBB
->end() &&
862 "Cannot get the Instrumentation point");
864 Intrinsic::getDeclaration(M
, Intrinsic::instrprof_increment
),
865 {ConstantExpr::getBitCast(FuncInfo
.FuncNameVar
, I8PtrTy
),
866 Builder
.getInt64(FuncInfo
.FunctionHash
), Builder
.getInt32(NumCounters
),
867 Builder
.getInt32(I
++)});
870 // Now instrument select instructions:
871 FuncInfo
.SIVisitor
.instrumentSelects(F
, &I
, NumCounters
, FuncInfo
.FuncNameVar
,
872 FuncInfo
.FunctionHash
);
873 assert(I
== NumCounters
);
875 if (DisableValueProfiling
)
878 unsigned NumIndirectCalls
= 0;
879 for (auto &I
: FuncInfo
.ValueSites
[IPVK_IndirectCallTarget
]) {
881 Value
*Callee
= CS
.getCalledValue();
882 LLVM_DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
883 << NumIndirectCalls
<< "\n");
884 IRBuilder
<> Builder(I
);
885 assert(Builder
.GetInsertPoint() != I
->getParent()->end() &&
886 "Cannot get the Instrumentation point");
888 Intrinsic::getDeclaration(M
, Intrinsic::instrprof_value_profile
),
889 {ConstantExpr::getBitCast(FuncInfo
.FuncNameVar
, I8PtrTy
),
890 Builder
.getInt64(FuncInfo
.FunctionHash
),
891 Builder
.CreatePtrToInt(Callee
, Builder
.getInt64Ty()),
892 Builder
.getInt32(IPVK_IndirectCallTarget
),
893 Builder
.getInt32(NumIndirectCalls
++)});
895 NumOfPGOICall
+= NumIndirectCalls
;
897 // Now instrument memop intrinsic calls.
898 FuncInfo
.MIVisitor
.instrumentMemIntrinsics(
899 F
, NumCounters
, FuncInfo
.FuncNameVar
, FuncInfo
.FunctionHash
);
904 // This class represents a CFG edge in profile use compilation.
905 struct PGOUseEdge
: public PGOEdge
{
906 bool CountValid
= false;
907 uint64_t CountValue
= 0;
909 PGOUseEdge(const BasicBlock
*Src
, const BasicBlock
*Dest
, uint64_t W
= 1)
910 : PGOEdge(Src
, Dest
, W
) {}
912 // Set edge count value
913 void setEdgeCount(uint64_t Value
) {
918 // Return the information string for this object.
919 const std::string
infoString() const {
921 return PGOEdge::infoString();
922 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue
))
927 using DirectEdges
= SmallVector
<PGOUseEdge
*, 2>;
929 // This class stores the auxiliary information for each BB.
930 struct UseBBInfo
: public BBInfo
{
931 uint64_t CountValue
= 0;
933 int32_t UnknownCountInEdge
= 0;
934 int32_t UnknownCountOutEdge
= 0;
936 DirectEdges OutEdges
;
938 UseBBInfo(unsigned IX
) : BBInfo(IX
), CountValid(false) {}
940 UseBBInfo(unsigned IX
, uint64_t C
)
941 : BBInfo(IX
), CountValue(C
), CountValid(true) {}
943 // Set the profile count value for this BB.
944 void setBBInfoCount(uint64_t Value
) {
949 // Return the information string of this object.
950 const std::string
infoString() const {
952 return BBInfo::infoString();
953 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue
)).str();
956 // Add an OutEdge and update the edge count.
957 void addOutEdge(PGOUseEdge
*E
) {
958 OutEdges
.push_back(E
);
959 UnknownCountOutEdge
++;
962 // Add an InEdge and update the edge count.
963 void addInEdge(PGOUseEdge
*E
) {
964 InEdges
.push_back(E
);
965 UnknownCountInEdge
++;
969 } // end anonymous namespace
971 // Sum up the count values for all the edges.
972 static uint64_t sumEdgeCount(const ArrayRef
<PGOUseEdge
*> Edges
) {
974 for (auto &E
: Edges
) {
977 Total
+= E
->CountValue
;
986 PGOUseFunc(Function
&Func
, Module
*Modu
,
987 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
,
988 BranchProbabilityInfo
*BPI
= nullptr,
989 BlockFrequencyInfo
*BFIin
= nullptr, bool IsCS
= false)
990 : F(Func
), M(Modu
), BFI(BFIin
),
991 FuncInfo(Func
, ComdatMembers
, false, BPI
, BFIin
, IsCS
),
992 FreqAttr(FFA_Normal
), IsCS(IsCS
) {}
994 // Read counts for the instrumented BB from profile.
995 bool readCounters(IndexedInstrProfReader
*PGOReader
, bool &AllZeros
);
997 // Populate the counts for all BBs.
998 void populateCounters();
1000 // Set the branch weights based on the count values.
1001 void setBranchWeights();
1003 // Annotate the value profile call sites for all value kind.
1004 void annotateValueSites();
1006 // Annotate the value profile call sites for one value kind.
1007 void annotateValueSites(uint32_t Kind
);
1009 // Annotate the irreducible loop header weights.
1010 void annotateIrrLoopHeaderWeights();
1012 // The hotness of the function from the profile count.
1013 enum FuncFreqAttr
{ FFA_Normal
, FFA_Cold
, FFA_Hot
};
1015 // Return the function hotness from the profile.
1016 FuncFreqAttr
getFuncFreqAttr() const { return FreqAttr
; }
1018 // Return the function hash.
1019 uint64_t getFuncHash() const { return FuncInfo
.FunctionHash
; }
1021 // Return the profile record for this function;
1022 InstrProfRecord
&getProfileRecord() { return ProfileRecord
; }
1024 // Return the auxiliary BB information.
1025 UseBBInfo
&getBBInfo(const BasicBlock
*BB
) const {
1026 return FuncInfo
.getBBInfo(BB
);
1029 // Return the auxiliary BB information if available.
1030 UseBBInfo
*findBBInfo(const BasicBlock
*BB
) const {
1031 return FuncInfo
.findBBInfo(BB
);
1034 Function
&getFunc() const { return F
; }
1036 void dumpInfo(std::string Str
= "") const {
1037 FuncInfo
.dumpInfo(Str
);
1040 uint64_t getProgramMaxCount() const { return ProgramMaxCount
; }
1044 BlockFrequencyInfo
*BFI
;
1046 // This member stores the shared information with class PGOGenFunc.
1047 FuncPGOInstrumentation
<PGOUseEdge
, UseBBInfo
> FuncInfo
;
1049 // The maximum count value in the profile. This is only used in PGO use
1051 uint64_t ProgramMaxCount
;
1053 // Position of counter that remains to be read.
1054 uint32_t CountPosition
= 0;
1056 // Total size of the profile count for this function.
1057 uint32_t ProfileCountSize
= 0;
1059 // ProfileRecord for this function.
1060 InstrProfRecord ProfileRecord
;
1062 // Function hotness info derived from profile.
1063 FuncFreqAttr FreqAttr
;
1065 // Is to use the context sensitive profile.
1068 // Find the Instrumented BB and set the value. Return false on error.
1069 bool setInstrumentedCounts(const std::vector
<uint64_t> &CountFromProfile
);
1071 // Set the edge counter value for the unknown edge -- there should be only
1072 // one unknown edge.
1073 void setEdgeCount(DirectEdges
&Edges
, uint64_t Value
);
1075 // Return FuncName string;
1076 const std::string
getFuncName() const { return FuncInfo
.FuncName
; }
1078 // Set the hot/cold inline hints based on the count values.
1079 // FIXME: This function should be removed once the functionality in
1080 // the inliner is implemented.
1081 void markFunctionAttributes(uint64_t EntryCount
, uint64_t MaxCount
) {
1082 if (ProgramMaxCount
== 0)
1084 // Threshold of the hot functions.
1085 const BranchProbability
HotFunctionThreshold(1, 100);
1086 // Threshold of the cold functions.
1087 const BranchProbability
ColdFunctionThreshold(2, 10000);
1088 if (EntryCount
>= HotFunctionThreshold
.scale(ProgramMaxCount
))
1090 else if (MaxCount
<= ColdFunctionThreshold
.scale(ProgramMaxCount
))
1091 FreqAttr
= FFA_Cold
;
1095 } // end anonymous namespace
1097 // Visit all the edges and assign the count value for the instrumented
1098 // edges and the BB. Return false on error.
1099 bool PGOUseFunc::setInstrumentedCounts(
1100 const std::vector
<uint64_t> &CountFromProfile
) {
1102 std::vector
<BasicBlock
*> InstrumentBBs
;
1103 FuncInfo
.getInstrumentBBs(InstrumentBBs
);
1104 unsigned NumCounters
=
1105 InstrumentBBs
.size() + FuncInfo
.SIVisitor
.getNumOfSelectInsts();
1106 // The number of counters here should match the number of counters
1107 // in profile. Return if they mismatch.
1108 if (NumCounters
!= CountFromProfile
.size()) {
1111 // Set the profile count to the Instrumented BBs.
1113 for (BasicBlock
*InstrBB
: InstrumentBBs
) {
1114 uint64_t CountValue
= CountFromProfile
[I
++];
1115 UseBBInfo
&Info
= getBBInfo(InstrBB
);
1116 Info
.setBBInfoCount(CountValue
);
1118 ProfileCountSize
= CountFromProfile
.size();
1121 // Set the edge count and update the count of unknown edges for BBs.
1122 auto setEdgeCount
= [this](PGOUseEdge
*E
, uint64_t Value
) -> void {
1123 E
->setEdgeCount(Value
);
1124 this->getBBInfo(E
->SrcBB
).UnknownCountOutEdge
--;
1125 this->getBBInfo(E
->DestBB
).UnknownCountInEdge
--;
1128 // Set the profile count the Instrumented edges. There are BBs that not in
1129 // MST but not instrumented. Need to set the edge count value so that we can
1130 // populate the profile counts later.
1131 for (auto &E
: FuncInfo
.MST
.AllEdges
) {
1132 if (E
->Removed
|| E
->InMST
)
1134 const BasicBlock
*SrcBB
= E
->SrcBB
;
1135 UseBBInfo
&SrcInfo
= getBBInfo(SrcBB
);
1137 // If only one out-edge, the edge profile count should be the same as BB
1139 if (SrcInfo
.CountValid
&& SrcInfo
.OutEdges
.size() == 1)
1140 setEdgeCount(E
.get(), SrcInfo
.CountValue
);
1142 const BasicBlock
*DestBB
= E
->DestBB
;
1143 UseBBInfo
&DestInfo
= getBBInfo(DestBB
);
1144 // If only one in-edge, the edge profile count should be the same as BB
1146 if (DestInfo
.CountValid
&& DestInfo
.InEdges
.size() == 1)
1147 setEdgeCount(E
.get(), DestInfo
.CountValue
);
1151 // E's count should have been set from profile. If not, this meenas E skips
1152 // the instrumentation. We set the count to 0.
1153 setEdgeCount(E
.get(), 0);
1158 // Set the count value for the unknown edge. There should be one and only one
1159 // unknown edge in Edges vector.
1160 void PGOUseFunc::setEdgeCount(DirectEdges
&Edges
, uint64_t Value
) {
1161 for (auto &E
: Edges
) {
1164 E
->setEdgeCount(Value
);
1166 getBBInfo(E
->SrcBB
).UnknownCountOutEdge
--;
1167 getBBInfo(E
->DestBB
).UnknownCountInEdge
--;
1170 llvm_unreachable("Cannot find the unknown count edge");
1173 // Read the profile from ProfileFileName and assign the value to the
1174 // instrumented BB and the edges. This function also updates ProgramMaxCount.
1175 // Return true if the profile are successfully read, and false on errors.
1176 bool PGOUseFunc::readCounters(IndexedInstrProfReader
*PGOReader
, bool &AllZeros
) {
1177 auto &Ctx
= M
->getContext();
1178 Expected
<InstrProfRecord
> Result
=
1179 PGOReader
->getInstrProfRecord(FuncInfo
.FuncName
, FuncInfo
.FunctionHash
);
1180 if (Error E
= Result
.takeError()) {
1181 handleAllErrors(std::move(E
), [&](const InstrProfError
&IPE
) {
1182 auto Err
= IPE
.get();
1183 bool SkipWarning
= false;
1184 LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
1185 << FuncInfo
.FuncName
<< ": ");
1186 if (Err
== instrprof_error::unknown_function
) {
1187 IsCS
? NumOfCSPGOMissing
++ : NumOfPGOMissing
++;
1188 SkipWarning
= !PGOWarnMissing
;
1189 LLVM_DEBUG(dbgs() << "unknown function");
1190 } else if (Err
== instrprof_error::hash_mismatch
||
1191 Err
== instrprof_error::malformed
) {
1192 IsCS
? NumOfCSPGOMismatch
++ : NumOfPGOMismatch
++;
1194 NoPGOWarnMismatch
||
1195 (NoPGOWarnMismatchComdat
&&
1197 F
.getLinkage() == GlobalValue::AvailableExternallyLinkage
));
1198 LLVM_DEBUG(dbgs() << "hash mismatch (skip=" << SkipWarning
<< ")");
1201 LLVM_DEBUG(dbgs() << " IsCS=" << IsCS
<< "\n");
1205 std::string Msg
= IPE
.message() + std::string(" ") + F
.getName().str() +
1206 std::string(" Hash = ") +
1207 std::to_string(FuncInfo
.FunctionHash
);
1210 DiagnosticInfoPGOProfile(M
->getName().data(), Msg
, DS_Warning
));
1214 ProfileRecord
= std::move(Result
.get());
1215 std::vector
<uint64_t> &CountFromProfile
= ProfileRecord
.Counts
;
1217 IsCS
? NumOfCSPGOFunc
++ : NumOfPGOFunc
++;
1218 LLVM_DEBUG(dbgs() << CountFromProfile
.size() << " counts\n");
1219 uint64_t ValueSum
= 0;
1220 for (unsigned I
= 0, S
= CountFromProfile
.size(); I
< S
; I
++) {
1221 LLVM_DEBUG(dbgs() << " " << I
<< ": " << CountFromProfile
[I
] << "\n");
1222 ValueSum
+= CountFromProfile
[I
];
1224 AllZeros
= (ValueSum
== 0);
1226 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum
<< "\n");
1228 getBBInfo(nullptr).UnknownCountOutEdge
= 2;
1229 getBBInfo(nullptr).UnknownCountInEdge
= 2;
1231 if (!setInstrumentedCounts(CountFromProfile
)) {
1233 dbgs() << "Inconsistent number of counts, skipping this function");
1234 Ctx
.diagnose(DiagnosticInfoPGOProfile(
1235 M
->getName().data(),
1236 Twine("Inconsistent number of counts in ") + F
.getName().str()
1237 + Twine(": the profile may be stale or there is a function name collision."),
1241 ProgramMaxCount
= PGOReader
->getMaximumFunctionCount(IsCS
);
1245 // Populate the counters from instrumented BBs to all BBs.
1246 // In the end of this operation, all BBs should have a valid count value.
1247 void PGOUseFunc::populateCounters() {
1248 bool Changes
= true;
1249 unsigned NumPasses
= 0;
1254 // For efficient traversal, it's better to start from the end as most
1255 // of the instrumented edges are at the end.
1256 for (auto &BB
: reverse(F
)) {
1257 UseBBInfo
*Count
= findBBInfo(&BB
);
1258 if (Count
== nullptr)
1260 if (!Count
->CountValid
) {
1261 if (Count
->UnknownCountOutEdge
== 0) {
1262 Count
->CountValue
= sumEdgeCount(Count
->OutEdges
);
1263 Count
->CountValid
= true;
1265 } else if (Count
->UnknownCountInEdge
== 0) {
1266 Count
->CountValue
= sumEdgeCount(Count
->InEdges
);
1267 Count
->CountValid
= true;
1271 if (Count
->CountValid
) {
1272 if (Count
->UnknownCountOutEdge
== 1) {
1274 uint64_t OutSum
= sumEdgeCount(Count
->OutEdges
);
1275 // If the one of the successor block can early terminate (no-return),
1276 // we can end up with situation where out edge sum count is larger as
1277 // the source BB's count is collected by a post-dominated block.
1278 if (Count
->CountValue
> OutSum
)
1279 Total
= Count
->CountValue
- OutSum
;
1280 setEdgeCount(Count
->OutEdges
, Total
);
1283 if (Count
->UnknownCountInEdge
== 1) {
1285 uint64_t InSum
= sumEdgeCount(Count
->InEdges
);
1286 if (Count
->CountValue
> InSum
)
1287 Total
= Count
->CountValue
- InSum
;
1288 setEdgeCount(Count
->InEdges
, Total
);
1295 LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses
<< " passes.\n");
1297 // Assert every BB has a valid counter.
1298 for (auto &BB
: F
) {
1299 auto BI
= findBBInfo(&BB
);
1302 assert(BI
->CountValid
&& "BB count is not valid");
1305 uint64_t FuncEntryCount
= getBBInfo(&*F
.begin()).CountValue
;
1306 F
.setEntryCount(ProfileCount(FuncEntryCount
, Function::PCT_Real
));
1307 uint64_t FuncMaxCount
= FuncEntryCount
;
1308 for (auto &BB
: F
) {
1309 auto BI
= findBBInfo(&BB
);
1312 FuncMaxCount
= std::max(FuncMaxCount
, BI
->CountValue
);
1314 markFunctionAttributes(FuncEntryCount
, FuncMaxCount
);
1316 // Now annotate select instructions
1317 FuncInfo
.SIVisitor
.annotateSelects(F
, this, &CountPosition
);
1318 assert(CountPosition
== ProfileCountSize
);
1320 LLVM_DEBUG(FuncInfo
.dumpInfo("after reading profile."));
1323 // Assign the scaled count values to the BB with multiple out edges.
1324 void PGOUseFunc::setBranchWeights() {
1325 // Generate MD_prof metadata for every branch instruction.
1326 LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F
.getName()
1327 << " IsCS=" << IsCS
<< "\n");
1328 for (auto &BB
: F
) {
1329 Instruction
*TI
= BB
.getTerminator();
1330 if (TI
->getNumSuccessors() < 2)
1332 if (!(isa
<BranchInst
>(TI
) || isa
<SwitchInst
>(TI
) ||
1333 isa
<IndirectBrInst
>(TI
)))
1336 if (getBBInfo(&BB
).CountValue
== 0)
1339 // We have a non-zero Branch BB.
1340 const UseBBInfo
&BBCountInfo
= getBBInfo(&BB
);
1341 unsigned Size
= BBCountInfo
.OutEdges
.size();
1342 SmallVector
<uint64_t, 2> EdgeCounts(Size
, 0);
1343 uint64_t MaxCount
= 0;
1344 for (unsigned s
= 0; s
< Size
; s
++) {
1345 const PGOUseEdge
*E
= BBCountInfo
.OutEdges
[s
];
1346 const BasicBlock
*SrcBB
= E
->SrcBB
;
1347 const BasicBlock
*DestBB
= E
->DestBB
;
1348 if (DestBB
== nullptr)
1350 unsigned SuccNum
= GetSuccessorNumber(SrcBB
, DestBB
);
1351 uint64_t EdgeCount
= E
->CountValue
;
1352 if (EdgeCount
> MaxCount
)
1353 MaxCount
= EdgeCount
;
1354 EdgeCounts
[SuccNum
] = EdgeCount
;
1356 setProfMetadata(M
, TI
, EdgeCounts
, MaxCount
);
1360 static bool isIndirectBrTarget(BasicBlock
*BB
) {
1361 for (pred_iterator PI
= pred_begin(BB
), E
= pred_end(BB
); PI
!= E
; ++PI
) {
1362 if (isa
<IndirectBrInst
>((*PI
)->getTerminator()))
1368 void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1369 LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1370 // Find irr loop headers
1371 for (auto &BB
: F
) {
1372 // As a heuristic also annotate indrectbr targets as they have a high chance
1373 // to become an irreducible loop header after the indirectbr tail
1375 if (BFI
->isIrrLoopHeader(&BB
) || isIndirectBrTarget(&BB
)) {
1376 Instruction
*TI
= BB
.getTerminator();
1377 const UseBBInfo
&BBCountInfo
= getBBInfo(&BB
);
1378 setIrrLoopHeaderMetadata(M
, TI
, BBCountInfo
.CountValue
);
1383 void SelectInstVisitor::instrumentOneSelectInst(SelectInst
&SI
) {
1384 Module
*M
= F
.getParent();
1385 IRBuilder
<> Builder(&SI
);
1386 Type
*Int64Ty
= Builder
.getInt64Ty();
1387 Type
*I8PtrTy
= Builder
.getInt8PtrTy();
1388 auto *Step
= Builder
.CreateZExt(SI
.getCondition(), Int64Ty
);
1390 Intrinsic::getDeclaration(M
, Intrinsic::instrprof_increment_step
),
1391 {ConstantExpr::getBitCast(FuncNameVar
, I8PtrTy
),
1392 Builder
.getInt64(FuncHash
), Builder
.getInt32(TotalNumCtrs
),
1393 Builder
.getInt32(*CurCtrIdx
), Step
});
1397 void SelectInstVisitor::annotateOneSelectInst(SelectInst
&SI
) {
1398 std::vector
<uint64_t> &CountFromProfile
= UseFunc
->getProfileRecord().Counts
;
1399 assert(*CurCtrIdx
< CountFromProfile
.size() &&
1400 "Out of bound access of counters");
1401 uint64_t SCounts
[2];
1402 SCounts
[0] = CountFromProfile
[*CurCtrIdx
]; // True count
1404 uint64_t TotalCount
= 0;
1405 auto BI
= UseFunc
->findBBInfo(SI
.getParent());
1407 TotalCount
= BI
->CountValue
;
1409 SCounts
[1] = (TotalCount
> SCounts
[0] ? TotalCount
- SCounts
[0] : 0);
1410 uint64_t MaxCount
= std::max(SCounts
[0], SCounts
[1]);
1412 setProfMetadata(F
.getParent(), &SI
, SCounts
, MaxCount
);
1415 void SelectInstVisitor::visitSelectInst(SelectInst
&SI
) {
1416 if (!PGOInstrSelect
)
1418 // FIXME: do not handle this yet.
1419 if (SI
.getCondition()->getType()->isVectorTy())
1427 instrumentOneSelectInst(SI
);
1430 annotateOneSelectInst(SI
);
1434 llvm_unreachable("Unknown visiting mode");
1437 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic
&MI
) {
1438 Module
*M
= F
.getParent();
1439 IRBuilder
<> Builder(&MI
);
1440 Type
*Int64Ty
= Builder
.getInt64Ty();
1441 Type
*I8PtrTy
= Builder
.getInt8PtrTy();
1442 Value
*Length
= MI
.getLength();
1443 assert(!isa
<ConstantInt
>(Length
));
1445 Intrinsic::getDeclaration(M
, Intrinsic::instrprof_value_profile
),
1446 {ConstantExpr::getBitCast(FuncNameVar
, I8PtrTy
),
1447 Builder
.getInt64(FuncHash
), Builder
.CreateZExtOrTrunc(Length
, Int64Ty
),
1448 Builder
.getInt32(IPVK_MemOPSize
), Builder
.getInt32(CurCtrId
)});
1452 void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic
&MI
) {
1455 Value
*Length
= MI
.getLength();
1456 // Not instrument constant length calls.
1457 if (dyn_cast
<ConstantInt
>(Length
))
1465 instrumentOneMemIntrinsic(MI
);
1468 Candidates
.push_back(&MI
);
1471 llvm_unreachable("Unknown visiting mode");
1474 // Traverse all valuesites and annotate the instructions for all value kind.
1475 void PGOUseFunc::annotateValueSites() {
1476 if (DisableValueProfiling
)
1479 // Create the PGOFuncName meta data.
1480 createPGOFuncNameMetadata(F
, FuncInfo
.FuncName
);
1482 for (uint32_t Kind
= IPVK_First
; Kind
<= IPVK_Last
; ++Kind
)
1483 annotateValueSites(Kind
);
1486 static const char *ValueProfKindDescr
[] = {
1487 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
1488 #include "llvm/ProfileData/InstrProfData.inc"
1491 // Annotate the instructions for a specific value kind.
1492 void PGOUseFunc::annotateValueSites(uint32_t Kind
) {
1493 assert(Kind
<= IPVK_Last
);
1494 unsigned ValueSiteIndex
= 0;
1495 auto &ValueSites
= FuncInfo
.ValueSites
[Kind
];
1496 unsigned NumValueSites
= ProfileRecord
.getNumValueSites(Kind
);
1497 if (NumValueSites
!= ValueSites
.size()) {
1498 auto &Ctx
= M
->getContext();
1499 Ctx
.diagnose(DiagnosticInfoPGOProfile(
1500 M
->getName().data(),
1501 Twine("Inconsistent number of value sites for ") +
1502 Twine(ValueProfKindDescr
[Kind
]) +
1503 Twine(" profiling in \"") + F
.getName().str() +
1504 Twine("\", possibly due to the use of a stale profile."),
1509 for (auto &I
: ValueSites
) {
1510 LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1511 << "): Index = " << ValueSiteIndex
<< " out of "
1512 << NumValueSites
<< "\n");
1513 annotateValueSite(*M
, *I
, ProfileRecord
,
1514 static_cast<InstrProfValueKind
>(Kind
), ValueSiteIndex
,
1515 Kind
== IPVK_MemOPSize
? MaxNumMemOPAnnotations
1516 : MaxNumAnnotations
);
1521 // Collect the set of members for each Comdat in module M and store
1522 // in ComdatMembers.
1523 static void collectComdatMembers(
1525 std::unordered_multimap
<Comdat
*, GlobalValue
*> &ComdatMembers
) {
1526 if (!DoComdatRenaming
)
1528 for (Function
&F
: M
)
1529 if (Comdat
*C
= F
.getComdat())
1530 ComdatMembers
.insert(std::make_pair(C
, &F
));
1531 for (GlobalVariable
&GV
: M
.globals())
1532 if (Comdat
*C
= GV
.getComdat())
1533 ComdatMembers
.insert(std::make_pair(C
, &GV
));
1534 for (GlobalAlias
&GA
: M
.aliases())
1535 if (Comdat
*C
= GA
.getComdat())
1536 ComdatMembers
.insert(std::make_pair(C
, &GA
));
1539 static bool InstrumentAllFunctions(
1540 Module
&M
, function_ref
<BranchProbabilityInfo
*(Function
&)> LookupBPI
,
1541 function_ref
<BlockFrequencyInfo
*(Function
&)> LookupBFI
, bool IsCS
) {
1542 // For the context-sensitve instrumentation, we should have a separated pass
1543 // (before LTO/ThinLTO linking) to create these variables.
1545 createIRLevelProfileFlagVar(M
, /* IsCS */ false);
1546 std::unordered_multimap
<Comdat
*, GlobalValue
*> ComdatMembers
;
1547 collectComdatMembers(M
, ComdatMembers
);
1550 if (F
.isDeclaration())
1552 auto *BPI
= LookupBPI(F
);
1553 auto *BFI
= LookupBFI(F
);
1554 instrumentOneFunc(F
, &M
, BPI
, BFI
, ComdatMembers
, IsCS
);
1560 PGOInstrumentationGenCreateVar::run(Module
&M
, ModuleAnalysisManager
&AM
) {
1561 createProfileFileNameVar(M
, CSInstrName
);
1562 createIRLevelProfileFlagVar(M
, /* IsCS */ true);
1563 return PreservedAnalyses::all();
1566 bool PGOInstrumentationGenLegacyPass::runOnModule(Module
&M
) {
1570 auto LookupBPI
= [this](Function
&F
) {
1571 return &this->getAnalysis
<BranchProbabilityInfoWrapperPass
>(F
).getBPI();
1573 auto LookupBFI
= [this](Function
&F
) {
1574 return &this->getAnalysis
<BlockFrequencyInfoWrapperPass
>(F
).getBFI();
1576 return InstrumentAllFunctions(M
, LookupBPI
, LookupBFI
, IsCS
);
1579 PreservedAnalyses
PGOInstrumentationGen::run(Module
&M
,
1580 ModuleAnalysisManager
&AM
) {
1581 auto &FAM
= AM
.getResult
<FunctionAnalysisManagerModuleProxy
>(M
).getManager();
1582 auto LookupBPI
= [&FAM
](Function
&F
) {
1583 return &FAM
.getResult
<BranchProbabilityAnalysis
>(F
);
1586 auto LookupBFI
= [&FAM
](Function
&F
) {
1587 return &FAM
.getResult
<BlockFrequencyAnalysis
>(F
);
1590 if (!InstrumentAllFunctions(M
, LookupBPI
, LookupBFI
, IsCS
))
1591 return PreservedAnalyses::all();
1593 return PreservedAnalyses::none();
1596 static bool annotateAllFunctions(
1597 Module
&M
, StringRef ProfileFileName
, StringRef ProfileRemappingFileName
,
1598 function_ref
<BranchProbabilityInfo
*(Function
&)> LookupBPI
,
1599 function_ref
<BlockFrequencyInfo
*(Function
&)> LookupBFI
, bool IsCS
) {
1600 LLVM_DEBUG(dbgs() << "Read in profile counters: ");
1601 auto &Ctx
= M
.getContext();
1602 // Read the counter array from file.
1604 IndexedInstrProfReader::create(ProfileFileName
, ProfileRemappingFileName
);
1605 if (Error E
= ReaderOrErr
.takeError()) {
1606 handleAllErrors(std::move(E
), [&](const ErrorInfoBase
&EI
) {
1608 DiagnosticInfoPGOProfile(ProfileFileName
.data(), EI
.message()));
1613 std::unique_ptr
<IndexedInstrProfReader
> PGOReader
=
1614 std::move(ReaderOrErr
.get());
1616 Ctx
.diagnose(DiagnosticInfoPGOProfile(ProfileFileName
.data(),
1617 StringRef("Cannot get PGOReader")));
1620 if (!PGOReader
->hasCSIRLevelProfile() && IsCS
)
1623 // TODO: might need to change the warning once the clang option is finalized.
1624 if (!PGOReader
->isIRLevelProfile()) {
1625 Ctx
.diagnose(DiagnosticInfoPGOProfile(
1626 ProfileFileName
.data(), "Not an IR level instrumentation profile"));
1630 std::unordered_multimap
<Comdat
*, GlobalValue
*> ComdatMembers
;
1631 collectComdatMembers(M
, ComdatMembers
);
1632 std::vector
<Function
*> HotFunctions
;
1633 std::vector
<Function
*> ColdFunctions
;
1635 if (F
.isDeclaration())
1637 auto *BPI
= LookupBPI(F
);
1638 auto *BFI
= LookupBFI(F
);
1639 // Split indirectbr critical edges here before computing the MST rather than
1640 // later in getInstrBB() to avoid invalidating it.
1641 SplitIndirectBrCriticalEdges(F
, BPI
, BFI
);
1642 PGOUseFunc
Func(F
, &M
, ComdatMembers
, BPI
, BFI
, IsCS
);
1643 bool AllZeros
= false;
1644 if (!Func
.readCounters(PGOReader
.get(), AllZeros
))
1647 F
.setEntryCount(ProfileCount(0, Function::PCT_Real
));
1648 if (Func
.getProgramMaxCount() != 0)
1649 ColdFunctions
.push_back(&F
);
1652 Func
.populateCounters();
1653 Func
.setBranchWeights();
1654 Func
.annotateValueSites();
1655 Func
.annotateIrrLoopHeaderWeights();
1656 PGOUseFunc::FuncFreqAttr FreqAttr
= Func
.getFuncFreqAttr();
1657 if (FreqAttr
== PGOUseFunc::FFA_Cold
)
1658 ColdFunctions
.push_back(&F
);
1659 else if (FreqAttr
== PGOUseFunc::FFA_Hot
)
1660 HotFunctions
.push_back(&F
);
1661 if (PGOViewCounts
!= PGOVCT_None
&&
1662 (ViewBlockFreqFuncName
.empty() ||
1663 F
.getName().equals(ViewBlockFreqFuncName
))) {
1664 LoopInfo LI
{DominatorTree(F
)};
1665 std::unique_ptr
<BranchProbabilityInfo
> NewBPI
=
1666 std::make_unique
<BranchProbabilityInfo
>(F
, LI
);
1667 std::unique_ptr
<BlockFrequencyInfo
> NewBFI
=
1668 std::make_unique
<BlockFrequencyInfo
>(F
, *NewBPI
, LI
);
1669 if (PGOViewCounts
== PGOVCT_Graph
)
1671 else if (PGOViewCounts
== PGOVCT_Text
) {
1672 dbgs() << "pgo-view-counts: " << Func
.getFunc().getName() << "\n";
1673 NewBFI
->print(dbgs());
1676 if (PGOViewRawCounts
!= PGOVCT_None
&&
1677 (ViewBlockFreqFuncName
.empty() ||
1678 F
.getName().equals(ViewBlockFreqFuncName
))) {
1679 if (PGOViewRawCounts
== PGOVCT_Graph
)
1680 if (ViewBlockFreqFuncName
.empty())
1681 WriteGraph(&Func
, Twine("PGORawCounts_") + Func
.getFunc().getName());
1683 ViewGraph(&Func
, Twine("PGORawCounts_") + Func
.getFunc().getName());
1684 else if (PGOViewRawCounts
== PGOVCT_Text
) {
1685 dbgs() << "pgo-view-raw-counts: " << Func
.getFunc().getName() << "\n";
1690 M
.setProfileSummary(PGOReader
->getSummary(IsCS
).getMD(M
.getContext()),
1691 IsCS
? ProfileSummary::PSK_CSInstr
1692 : ProfileSummary::PSK_Instr
);
1694 // Set function hotness attribute from the profile.
1695 // We have to apply these attributes at the end because their presence
1696 // can affect the BranchProbabilityInfo of any callers, resulting in an
1697 // inconsistent MST between prof-gen and prof-use.
1698 for (auto &F
: HotFunctions
) {
1699 F
->addFnAttr(Attribute::InlineHint
);
1700 LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F
->getName()
1703 for (auto &F
: ColdFunctions
) {
1704 F
->addFnAttr(Attribute::Cold
);
1705 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F
->getName()
1711 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename
,
1712 std::string RemappingFilename
,
1714 : ProfileFileName(std::move(Filename
)),
1715 ProfileRemappingFileName(std::move(RemappingFilename
)), IsCS(IsCS
) {
1716 if (!PGOTestProfileFile
.empty())
1717 ProfileFileName
= PGOTestProfileFile
;
1718 if (!PGOTestProfileRemappingFile
.empty())
1719 ProfileRemappingFileName
= PGOTestProfileRemappingFile
;
1722 PreservedAnalyses
PGOInstrumentationUse::run(Module
&M
,
1723 ModuleAnalysisManager
&AM
) {
1725 auto &FAM
= AM
.getResult
<FunctionAnalysisManagerModuleProxy
>(M
).getManager();
1726 auto LookupBPI
= [&FAM
](Function
&F
) {
1727 return &FAM
.getResult
<BranchProbabilityAnalysis
>(F
);
1730 auto LookupBFI
= [&FAM
](Function
&F
) {
1731 return &FAM
.getResult
<BlockFrequencyAnalysis
>(F
);
1734 if (!annotateAllFunctions(M
, ProfileFileName
, ProfileRemappingFileName
,
1735 LookupBPI
, LookupBFI
, IsCS
))
1736 return PreservedAnalyses::all();
1738 return PreservedAnalyses::none();
1741 bool PGOInstrumentationUseLegacyPass::runOnModule(Module
&M
) {
1745 auto LookupBPI
= [this](Function
&F
) {
1746 return &this->getAnalysis
<BranchProbabilityInfoWrapperPass
>(F
).getBPI();
1748 auto LookupBFI
= [this](Function
&F
) {
1749 return &this->getAnalysis
<BlockFrequencyInfoWrapperPass
>(F
).getBFI();
1752 return annotateAllFunctions(M
, ProfileFileName
, "", LookupBPI
, LookupBFI
,
1756 static std::string
getSimpleNodeName(const BasicBlock
*Node
) {
1757 if (!Node
->getName().empty())
1758 return Node
->getName();
1760 std::string SimpleNodeName
;
1761 raw_string_ostream
OS(SimpleNodeName
);
1762 Node
->printAsOperand(OS
, false);
1766 void llvm::setProfMetadata(Module
*M
, Instruction
*TI
,
1767 ArrayRef
<uint64_t> EdgeCounts
,
1768 uint64_t MaxCount
) {
1769 MDBuilder
MDB(M
->getContext());
1770 assert(MaxCount
> 0 && "Bad max count");
1771 uint64_t Scale
= calculateCountScale(MaxCount
);
1772 SmallVector
<unsigned, 4> Weights
;
1773 for (const auto &ECI
: EdgeCounts
)
1774 Weights
.push_back(scaleBranchCount(ECI
, Scale
));
1776 LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W
1781 misexpect::verifyMisExpect(TI
, Weights
, TI
->getContext());
1783 TI
->setMetadata(LLVMContext::MD_prof
, MDB
.createBranchWeights(Weights
));
1784 if (EmitBranchProbability
) {
1785 std::string BrCondStr
= getBranchCondString(TI
);
1786 if (BrCondStr
.empty())
1790 std::accumulate(Weights
.begin(), Weights
.end(), (uint64_t)0,
1791 [](uint64_t w1
, uint64_t w2
) { return w1
+ w2
; });
1792 uint64_t TotalCount
=
1793 std::accumulate(EdgeCounts
.begin(), EdgeCounts
.end(), (uint64_t)0,
1794 [](uint64_t c1
, uint64_t c2
) { return c1
+ c2
; });
1795 Scale
= calculateCountScale(WSum
);
1796 BranchProbability
BP(scaleBranchCount(Weights
[0], Scale
),
1797 scaleBranchCount(WSum
, Scale
));
1798 std::string BranchProbStr
;
1799 raw_string_ostream
OS(BranchProbStr
);
1801 OS
<< " (total count : " << TotalCount
<< ")";
1803 Function
*F
= TI
->getParent()->getParent();
1804 OptimizationRemarkEmitter
ORE(F
);
1806 return OptimizationRemark(DEBUG_TYPE
, "pgo-instrumentation", TI
)
1807 << BrCondStr
<< " is true with probability : " << BranchProbStr
;
1814 void setIrrLoopHeaderMetadata(Module
*M
, Instruction
*TI
, uint64_t Count
) {
1815 MDBuilder
MDB(M
->getContext());
1816 TI
->setMetadata(llvm::LLVMContext::MD_irr_loop
,
1817 MDB
.createIrrLoopHeaderWeight(Count
));
1820 template <> struct GraphTraits
<PGOUseFunc
*> {
1821 using NodeRef
= const BasicBlock
*;
1822 using ChildIteratorType
= succ_const_iterator
;
1823 using nodes_iterator
= pointer_iterator
<Function::const_iterator
>;
1825 static NodeRef
getEntryNode(const PGOUseFunc
*G
) {
1826 return &G
->getFunc().front();
1829 static ChildIteratorType
child_begin(const NodeRef N
) {
1830 return succ_begin(N
);
1833 static ChildIteratorType
child_end(const NodeRef N
) { return succ_end(N
); }
1835 static nodes_iterator
nodes_begin(const PGOUseFunc
*G
) {
1836 return nodes_iterator(G
->getFunc().begin());
1839 static nodes_iterator
nodes_end(const PGOUseFunc
*G
) {
1840 return nodes_iterator(G
->getFunc().end());
1844 template <> struct DOTGraphTraits
<PGOUseFunc
*> : DefaultDOTGraphTraits
{
1845 explicit DOTGraphTraits(bool isSimple
= false)
1846 : DefaultDOTGraphTraits(isSimple
) {}
1848 static std::string
getGraphName(const PGOUseFunc
*G
) {
1849 return G
->getFunc().getName();
1852 std::string
getNodeLabel(const BasicBlock
*Node
, const PGOUseFunc
*Graph
) {
1854 raw_string_ostream
OS(Result
);
1856 OS
<< getSimpleNodeName(Node
) << ":\\l";
1857 UseBBInfo
*BI
= Graph
->findBBInfo(Node
);
1859 if (BI
&& BI
->CountValid
)
1860 OS
<< BI
->CountValue
<< "\\l";
1864 if (!PGOInstrSelect
)
1867 for (auto BI
= Node
->begin(); BI
!= Node
->end(); ++BI
) {
1869 if (!isa
<SelectInst
>(I
))
1871 // Display scaled counts for SELECT instruction:
1872 OS
<< "SELECT : { T = ";
1874 bool HasProf
= I
->extractProfMetadata(TC
, FC
);
1876 OS
<< "Unknown, F = Unknown }\\l";
1878 OS
<< TC
<< ", F = " << FC
<< " }\\l";
1884 } // end namespace llvm