blob: 97fe6c89d579b257b5f653dc5ca5f33cb55b21c4 [file] [log] [blame]
Rong Xuf430ae42015-12-09 18:08:16 +00001//===-- PGOInstrumentation.cpp - MST-based PGO Instrumentation ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements PGO instrumentation using a minimum spanning tree based
11// on the following paper:
12// [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
13// for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
14// Issue 3, pp 313-322
15// The idea of the algorithm based on the fact that for each node (except for
16// the entry and exit), the sum of incoming edge counts equals the sum of
17// outgoing edge counts. The count of edge on spanning tree can be derived from
18// those edges not on the spanning tree. Knuth proves this method instruments
19// the minimum number of edges.
20//
21// The minimal spanning tree here is actually a maximum weight tree -- on-tree
22// edges have higher frequencies (more likely to execute). The idea is to
23// instrument those less frequently executed edges to reduce the runtime
24// overhead of instrumented binaries.
25//
26// This file contains two passes:
27// (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
Rong Xu13b01dc2016-02-10 18:24:45 +000028// count profile, and generates the instrumentation for indirect call
29// profiling.
Rong Xuf430ae42015-12-09 18:08:16 +000030// (2) Pass PGOInstrumentationUse which reads the edge count profile and
Rong Xu13b01dc2016-02-10 18:24:45 +000031// annotates the branch weights. It also reads the indirect call value
32// profiling records and annotate the indirect call instructions.
33//
Rong Xuf430ae42015-12-09 18:08:16 +000034// To get the precise counter information, These two passes need to invoke at
35// the same compilation point (so they see the same IR). For pass
36// PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
37// pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
38// the profile is opened in module level and passed to each PGOUseFunc instance.
39// The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
40// in class FuncPGOInstrumentation.
41//
42// Class PGOEdge represents a CFG edge and some auxiliary information. Class
43// BBInfo contains auxiliary information for each BB. These two classes are used
44// in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
45// class of PGOEdge and BBInfo, respectively. They contains extra data structure
46// used in populating profile counters.
47// The MST implementation is in Class CFGMST (CFGMST.h).
48//
49//===----------------------------------------------------------------------===//
50
Xinliang David Li8aebf442016-05-06 05:49:19 +000051#include "llvm/Transforms/PGOInstrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000052#include "CFGMST.h"
Rong Xuf430ae42015-12-09 18:08:16 +000053#include "llvm/ADT/STLExtras.h"
Rong Xu705f7772016-07-25 18:45:37 +000054#include "llvm/ADT/SmallVector.h"
Rong Xuf430ae42015-12-09 18:08:16 +000055#include "llvm/ADT/Statistic.h"
Rong Xu33c76c02016-02-10 17:18:30 +000056#include "llvm/ADT/Triple.h"
Rong Xuf430ae42015-12-09 18:08:16 +000057#include "llvm/Analysis/BlockFrequencyInfo.h"
58#include "llvm/Analysis/BranchProbabilityInfo.h"
59#include "llvm/Analysis/CFG.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000060#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Xinliang David Licb253ce2017-01-23 18:58:24 +000061#include "llvm/Analysis/LoopInfo.h"
Rong Xued9fec72016-01-21 18:11:44 +000062#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000063#include "llvm/IR/DiagnosticInfo.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000064#include "llvm/IR/Dominators.h"
Rong Xu705f7772016-07-25 18:45:37 +000065#include "llvm/IR/GlobalValue.h"
Rong Xuf430ae42015-12-09 18:08:16 +000066#include "llvm/IR/IRBuilder.h"
67#include "llvm/IR/InstIterator.h"
68#include "llvm/IR/Instructions.h"
69#include "llvm/IR/IntrinsicInst.h"
70#include "llvm/IR/MDBuilder.h"
71#include "llvm/IR/Module.h"
72#include "llvm/Pass.h"
73#include "llvm/ProfileData/InstrProfReader.h"
Easwaran Raman5fe04a12016-05-26 22:57:11 +000074#include "llvm/ProfileData/ProfileCommon.h"
Rong Xuf430ae42015-12-09 18:08:16 +000075#include "llvm/Support/BranchProbability.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000076#include "llvm/Support/DOTGraphTraits.h"
Rong Xuf430ae42015-12-09 18:08:16 +000077#include "llvm/Support/Debug.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000078#include "llvm/Support/GraphWriter.h"
Rong Xuf430ae42015-12-09 18:08:16 +000079#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000080#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000081#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000082#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000083#include <string>
Rong Xu705f7772016-07-25 18:45:37 +000084#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +000085#include <utility>
86#include <vector>
87
88using namespace llvm;
89
90#define DEBUG_TYPE "pgo-instrumentation"
91
92STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +000093STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +000094STATISTIC(NumOfPGOEdge, "Number of edges.");
95STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
96STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
97STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
98STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
99STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000100STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +0000101
102// Command line option to specify the file to read profile from. This is
103// mainly used for testing.
104static cl::opt<std::string>
105 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
106 cl::value_desc("filename"),
107 cl::desc("Specify the path of profile data file. This is"
108 "mainly for test purpose."));
109
Rong Xuecdc98f2016-03-04 22:08:44 +0000110// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000111// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000112static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
113 cl::Hidden,
114 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000115
Rong Xuecdc98f2016-03-04 22:08:44 +0000116// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000117// the metadata for a single indirect call callsite.
118static cl::opt<unsigned> MaxNumAnnotations(
119 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
120 cl::desc("Max number of annotations for a single indirect "
121 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000122
Rong Xu705f7772016-07-25 18:45:37 +0000123// Command line option to control appending FunctionHash to the name of a COMDAT
124// function. This is to avoid the hash mismatch caused by the preinliner.
125static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000126 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000127 cl::desc("Append function hash to the name of COMDAT function to avoid "
128 "function hash mismatch due to the preinliner"));
129
Rong Xu0698de92016-05-13 17:26:06 +0000130// Command line option to enable/disable the warning about missing profile
131// information.
Xinliang David Li76a01082016-08-11 05:09:30 +0000132static cl::opt<bool> PGOWarnMissing("pgo-warn-missing-function",
133 cl::init(false),
134 cl::Hidden);
Rong Xu0698de92016-05-13 17:26:06 +0000135
136// Command line option to enable/disable the warning about a hash mismatch in
137// the profile data.
138static cl::opt<bool> NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false),
139 cl::Hidden);
140
Rong Xu20f5df12017-01-11 20:19:41 +0000141// Command line option to enable/disable the warning about a hash mismatch in
142// the profile data for Comdat functions, which often turns out to be false
143// positive due to the pre-instrumentation inline.
144static cl::opt<bool> NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat",
145 cl::init(true), cl::Hidden);
146
Xinliang David Li4ca17332016-09-18 18:34:07 +0000147// Command line option to enable/disable select instruction instrumentation.
148static cl::opt<bool> PGOInstrSelect("pgo-instr-select", cl::init(true),
149 cl::Hidden);
Xinliang David Licb253ce2017-01-23 18:58:24 +0000150
151// Command line option to specify the name of the function for CFG dump
152static cl::opt<std::string>
153 PGOViewFunction("pgo-view-function", cl::Hidden,
154 cl::desc("The option to specify "
155 "the name of the function "
156 "whose CFG will be displayed."));
157
Xinliang David Lid289e452017-01-27 19:06:25 +0000158// Command line option to turn on CFG dot dump of raw profile counts
159static cl::opt<bool> PGOViewRawCounts("pgo-view-raw-counts", cl::init(false),
160 cl::Hidden);
161
Xinliang David Licb253ce2017-01-23 18:58:24 +0000162// Command line option to turn on CFG dot dump after profile annotation.
163extern cl::opt<bool> PGOViewCounts;
164
Rong Xuf430ae42015-12-09 18:08:16 +0000165namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000166
167/// The select instruction visitor plays three roles specified
168/// by the mode. In \c VM_counting mode, it simply counts the number of
169/// select instructions. In \c VM_instrument mode, it inserts code to count
170/// the number times TrueValue of select is taken. In \c VM_annotate mode,
171/// it reads the profile data and annotate the select instruction with metadata.
172enum VisitMode { VM_counting, VM_instrument, VM_annotate };
173class PGOUseFunc;
174
175/// Instruction Visitor class to visit select instructions.
176struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
177 Function &F;
178 unsigned NSIs = 0; // Number of select instructions instrumented.
179 VisitMode Mode = VM_counting; // Visiting mode.
180 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
181 unsigned TotalNumCtrs = 0; // Total number of counters
182 GlobalVariable *FuncNameVar = nullptr;
183 uint64_t FuncHash = 0;
184 PGOUseFunc *UseFunc = nullptr;
185
186 SelectInstVisitor(Function &Func) : F(Func) {}
187
188 void countSelects(Function &Func) {
189 Mode = VM_counting;
190 visit(Func);
191 }
192 // Visit the IR stream and instrument all select instructions. \p
193 // Ind is a pointer to the counter index variable; \p TotalNC
194 // is the total number of counters; \p FNV is the pointer to the
195 // PGO function name var; \p FHash is the function hash.
196 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
197 GlobalVariable *FNV, uint64_t FHash) {
198 Mode = VM_instrument;
199 CurCtrIdx = Ind;
200 TotalNumCtrs = TotalNC;
201 FuncHash = FHash;
202 FuncNameVar = FNV;
203 visit(Func);
204 }
205
206 // Visit the IR stream and annotate all select instructions.
207 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
208 Mode = VM_annotate;
209 UseFunc = UF;
210 CurCtrIdx = Ind;
211 visit(Func);
212 }
213
214 void instrumentOneSelectInst(SelectInst &SI);
215 void annotateOneSelectInst(SelectInst &SI);
216 // Visit \p SI instruction and perform tasks according to visit mode.
217 void visitSelectInst(SelectInst &SI);
218 unsigned getNumOfSelectInsts() const { return NSIs; }
219};
220
Xinliang David Li8aebf442016-05-06 05:49:19 +0000221class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000222public:
223 static char ID;
224
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000225 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000226 initializePGOInstrumentationGenLegacyPassPass(
227 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000228 }
229
Mehdi Amini117296c2016-10-01 02:56:57 +0000230 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000231
232private:
233 bool runOnModule(Module &M) override;
234
235 void getAnalysisUsage(AnalysisUsage &AU) const override {
236 AU.addRequired<BlockFrequencyInfoWrapperPass>();
237 }
238};
239
Xinliang David Lid55827f2016-05-07 05:39:12 +0000240class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000241public:
242 static char ID;
243
244 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000245 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000246 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000247 if (!PGOTestProfileFile.empty())
248 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000249 initializePGOInstrumentationUseLegacyPassPass(
250 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000251 }
252
Mehdi Amini117296c2016-10-01 02:56:57 +0000253 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000254
255private:
256 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000257
Xinliang David Lida195582016-05-10 21:59:52 +0000258 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000259 void getAnalysisUsage(AnalysisUsage &AU) const override {
260 AU.addRequired<BlockFrequencyInfoWrapperPass>();
261 }
262};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000263
Rong Xuf430ae42015-12-09 18:08:16 +0000264} // end anonymous namespace
265
Xinliang David Li8aebf442016-05-06 05:49:19 +0000266char PGOInstrumentationGenLegacyPass::ID = 0;
267INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000268 "PGO instrumentation.", false, false)
269INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
270INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000271INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000272 "PGO instrumentation.", false, false)
273
Xinliang David Li8aebf442016-05-06 05:49:19 +0000274ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
275 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000276}
277
Xinliang David Lid55827f2016-05-07 05:39:12 +0000278char PGOInstrumentationUseLegacyPass::ID = 0;
279INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000280 "Read PGO instrumentation profile.", false, false)
281INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
282INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000283INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000284 "Read PGO instrumentation profile.", false, false)
285
Xinliang David Lid55827f2016-05-07 05:39:12 +0000286ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
287 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000288}
289
290namespace {
291/// \brief An MST based instrumentation for PGO
292///
293/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
294/// in the function level.
295struct PGOEdge {
296 // This class implements the CFG edges. Note the CFG can be a multi-graph.
297 // So there might be multiple edges with same SrcBB and DestBB.
298 const BasicBlock *SrcBB;
299 const BasicBlock *DestBB;
300 uint64_t Weight;
301 bool InMST;
302 bool Removed;
303 bool IsCritical;
304 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
305 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
306 IsCritical(false) {}
307 // Return the information string of an edge.
308 const std::string infoString() const {
309 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
310 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
311 }
312};
313
314// This class stores the auxiliary information for each BB.
315struct BBInfo {
316 BBInfo *Group;
317 uint32_t Index;
318 uint32_t Rank;
319
320 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
321
322 // Return the information string of this object.
323 const std::string infoString() const {
324 return (Twine("Index=") + Twine(Index)).str();
325 }
326};
327
328// This class implements the CFG edges. Note the CFG can be a multi-graph.
329template <class Edge, class BBInfo> class FuncPGOInstrumentation {
330private:
331 Function &F;
332 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000333 void renameComdatFunction();
334 // A map that stores the Comdat group in function F.
335 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000336
337public:
Xinliang David Li9780fc12016-09-20 22:39:47 +0000338 std::vector<Instruction *> IndirectCallSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000339 SelectInstVisitor SIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000340 std::string FuncName;
341 GlobalVariable *FuncNameVar;
342 // CFG hash value for this function.
343 uint64_t FunctionHash;
344
345 // The Minimum Spanning Tree of function CFG.
346 CFGMST<Edge, BBInfo> MST;
347
348 // Give an edge, find the BB that will be instrumented.
349 // Return nullptr if there is no BB to be instrumented.
350 BasicBlock *getInstrBB(Edge *E);
351
352 // Return the auxiliary BB information.
353 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
354
Rong Xua5b57452016-12-02 19:10:29 +0000355 // Return the auxiliary BB information if available.
356 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
357
Rong Xuf430ae42015-12-09 18:08:16 +0000358 // Dump edges and BB information.
359 void dumpInfo(std::string Str = "") const {
360 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000361 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000362 }
363
Rong Xu705f7772016-07-25 18:45:37 +0000364 FuncPGOInstrumentation(
365 Function &Func,
366 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
367 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
368 BlockFrequencyInfo *BFI = nullptr)
Xinliang David Li4ca17332016-09-18 18:34:07 +0000369 : F(Func), ComdatMembers(ComdatMembers), SIVisitor(Func), FunctionHash(0),
Rong Xu705f7772016-07-25 18:45:37 +0000370 MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000371
372 // This should be done before CFG hash computation.
373 SIVisitor.countSelects(Func);
374 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Xinliang David Li9780fc12016-09-20 22:39:47 +0000375 IndirectCallSites = findIndirectCallSites(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000376
Rong Xuf430ae42015-12-09 18:08:16 +0000377 FuncName = getPGOFuncName(F);
378 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000379 if (ComdatMembers.size())
380 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000381 DEBUG(dumpInfo("after CFGMST"));
382
383 NumOfPGOBB += MST.BBInfos.size();
384 for (auto &E : MST.AllEdges) {
385 if (E->Removed)
386 continue;
387 NumOfPGOEdge++;
388 if (!E->InMST)
389 NumOfPGOInstrument++;
390 }
391
392 if (CreateGlobalVar)
393 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000394 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000395
396 // Return the number of profile counters needed for the function.
397 unsigned getNumCounters() {
398 unsigned NumCounters = 0;
399 for (auto &E : this->MST.AllEdges) {
400 if (!E->InMST && !E->Removed)
401 NumCounters++;
402 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000403 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000404 }
Rong Xuf430ae42015-12-09 18:08:16 +0000405};
406
407// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
408// value of each BB in the CFG. The higher 32 bits record the number of edges.
409template <class Edge, class BBInfo>
410void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
411 std::vector<char> Indexes;
412 JamCRC JC;
413 for (auto &BB : F) {
414 const TerminatorInst *TI = BB.getTerminator();
415 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
416 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000417 auto BI = findBBInfo(Succ);
418 if (BI == nullptr)
419 continue;
420 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000421 for (int J = 0; J < 4; J++)
422 Indexes.push_back((char)(Index >> (J * 8)));
423 }
424 }
425 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000426 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Xinliang David Li9780fc12016-09-20 22:39:47 +0000427 (uint64_t)IndirectCallSites.size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000428 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
429}
430
431// Check if we can safely rename this Comdat function.
432static bool canRenameComdat(
433 Function &F,
434 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000435 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000436 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000437
438 // FIXME: Current only handle those Comdat groups that only containing one
439 // function and function aliases.
440 // (1) For a Comdat group containing multiple functions, we need to have a
441 // unique postfix based on the hashes for each function. There is a
442 // non-trivial code refactoring to do this efficiently.
443 // (2) Variables can not be renamed, so we can not rename Comdat function in a
444 // group including global vars.
445 Comdat *C = F.getComdat();
446 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
447 if (dyn_cast<GlobalAlias>(CM.second))
448 continue;
449 Function *FM = dyn_cast<Function>(CM.second);
450 if (FM != &F)
451 return false;
452 }
453 return true;
454}
455
456// Append the CFGHash to the Comdat function name.
457template <class Edge, class BBInfo>
458void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
459 if (!canRenameComdat(F, ComdatMembers))
460 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000461 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000462 std::string NewFuncName =
463 Twine(F.getName() + "." + Twine(FunctionHash)).str();
464 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000465 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000466 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
467 Comdat *NewComdat;
468 Module *M = F.getParent();
469 // For AvailableExternallyLinkage functions, change the linkage to
470 // LinkOnceODR and put them into comdat. This is because after renaming, there
471 // is no backup external copy available for the function.
472 if (!F.hasComdat()) {
473 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
474 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
475 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
476 F.setComdat(NewComdat);
477 return;
478 }
479
480 // This function belongs to a single function Comdat group.
481 Comdat *OrigComdat = F.getComdat();
482 std::string NewComdatName =
483 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
484 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
485 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
486
487 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
488 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
489 // For aliases, change the name directly.
490 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000491 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000492 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000493 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000494 continue;
495 }
496 // Must be a function.
497 Function *CF = dyn_cast<Function>(CM.second);
498 assert(CF);
499 CF->setComdat(NewComdat);
500 }
Rong Xuf430ae42015-12-09 18:08:16 +0000501}
502
503// Given a CFG E to be instrumented, find which BB to place the instrumented
504// code. The function will split the critical edge if necessary.
505template <class Edge, class BBInfo>
506BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
507 if (E->InMST || E->Removed)
508 return nullptr;
509
510 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
511 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
512 // For a fake edge, instrument the real BB.
513 if (SrcBB == nullptr)
514 return DestBB;
515 if (DestBB == nullptr)
516 return SrcBB;
517
518 // Instrument the SrcBB if it has a single successor,
519 // otherwise, the DestBB if this is not a critical edge.
520 TerminatorInst *TI = SrcBB->getTerminator();
521 if (TI->getNumSuccessors() <= 1)
522 return SrcBB;
523 if (!E->IsCritical)
524 return DestBB;
525
526 // For a critical edge, we have to split. Instrument the newly
527 // created BB.
528 NumOfPGOSplit++;
529 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
530 << getBBInfo(DestBB).Index << "\n");
531 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
532 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
533 assert(InstrBB && "Critical edge is not split");
534
535 E->Removed = true;
536 return InstrBB;
537}
538
Rong Xued9fec72016-01-21 18:11:44 +0000539// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000540// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000541static void instrumentOneFunc(
542 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
543 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000544 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
545 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000546 unsigned NumCounters = FuncInfo.getNumCounters();
547
Rong Xuf430ae42015-12-09 18:08:16 +0000548 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000549 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000550 for (auto &E : FuncInfo.MST.AllEdges) {
551 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
552 if (!InstrBB)
553 continue;
554
555 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
556 assert(Builder.GetInsertPoint() != InstrBB->end() &&
557 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000558 Builder.CreateCall(
559 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
560 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
561 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
562 Builder.getInt32(I++)});
563 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000564
565 // Now instrument select instructions:
566 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
567 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000568 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000569
570 if (DisableValueProfiling)
571 return;
572
573 unsigned NumIndirectCallSites = 0;
Xinliang David Li9780fc12016-09-20 22:39:47 +0000574 for (auto &I : FuncInfo.IndirectCallSites) {
Rong Xued9fec72016-01-21 18:11:44 +0000575 CallSite CS(I);
576 Value *Callee = CS.getCalledValue();
577 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
578 << NumIndirectCallSites << "\n");
579 IRBuilder<> Builder(I);
580 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
581 "Cannot get the Instrumentation point");
582 Builder.CreateCall(
583 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
584 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
585 Builder.getInt64(FuncInfo.FunctionHash),
586 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
587 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
588 Builder.getInt32(NumIndirectCallSites++)});
589 }
590 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000591}
592
593// This class represents a CFG edge in profile use compilation.
594struct PGOUseEdge : public PGOEdge {
595 bool CountValid;
596 uint64_t CountValue;
597 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
598 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
599
600 // Set edge count value
601 void setEdgeCount(uint64_t Value) {
602 CountValue = Value;
603 CountValid = true;
604 }
605
606 // Return the information string for this object.
607 const std::string infoString() const {
608 if (!CountValid)
609 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000610 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
611 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000612 }
613};
614
615typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
616
617// This class stores the auxiliary information for each BB.
618struct UseBBInfo : public BBInfo {
619 uint64_t CountValue;
620 bool CountValid;
621 int32_t UnknownCountInEdge;
622 int32_t UnknownCountOutEdge;
623 DirectEdges InEdges;
624 DirectEdges OutEdges;
625 UseBBInfo(unsigned IX)
626 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
627 UnknownCountOutEdge(0) {}
628 UseBBInfo(unsigned IX, uint64_t C)
629 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
630 UnknownCountOutEdge(0) {}
631
632 // Set the profile count value for this BB.
633 void setBBInfoCount(uint64_t Value) {
634 CountValue = Value;
635 CountValid = true;
636 }
637
638 // Return the information string of this object.
639 const std::string infoString() const {
640 if (!CountValid)
641 return BBInfo::infoString();
642 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
643 }
644};
645
646// Sum up the count values for all the edges.
647static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
648 uint64_t Total = 0;
649 for (auto &E : Edges) {
650 if (E->Removed)
651 continue;
652 Total += E->CountValue;
653 }
654 return Total;
655}
656
657class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000658public:
Rong Xu705f7772016-07-25 18:45:37 +0000659 PGOUseFunc(Function &Func, Module *Modu,
660 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
661 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000662 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000663 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Rong Xu33308f92016-10-25 21:47:24 +0000664 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000665
666 // Read counts for the instrumented BB from profile.
667 bool readCounters(IndexedInstrProfReader *PGOReader);
668
669 // Populate the counts for all BBs.
670 void populateCounters();
671
672 // Set the branch weights based on the count values.
673 void setBranchWeights();
674
675 // Annotate the indirect call sites.
676 void annotateIndirectCallSites();
677
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000678 // The hotness of the function from the profile count.
679 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
680
681 // Return the function hotness from the profile.
682 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
683
Rong Xu705f7772016-07-25 18:45:37 +0000684 // Return the function hash.
685 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000686 // Return the profile record for this function;
687 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
688
Xinliang David Li4ca17332016-09-18 18:34:07 +0000689 // Return the auxiliary BB information.
690 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
691 return FuncInfo.getBBInfo(BB);
692 }
693
Rong Xua5b57452016-12-02 19:10:29 +0000694 // Return the auxiliary BB information if available.
695 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
696 return FuncInfo.findBBInfo(BB);
697 }
698
Xinliang David Lid289e452017-01-27 19:06:25 +0000699 Function &getFunc() const { return F; }
700
Rong Xuf430ae42015-12-09 18:08:16 +0000701private:
702 Function &F;
703 Module *M;
704 // This member stores the shared information with class PGOGenFunc.
705 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
706
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000707 // The maximum count value in the profile. This is only used in PGO use
708 // compilation.
709 uint64_t ProgramMaxCount;
710
Rong Xu33308f92016-10-25 21:47:24 +0000711 // Position of counter that remains to be read.
712 uint32_t CountPosition;
713
714 // Total size of the profile count for this function.
715 uint32_t ProfileCountSize;
716
Rong Xu13b01dc2016-02-10 18:24:45 +0000717 // ProfileRecord for this function.
718 InstrProfRecord ProfileRecord;
719
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000720 // Function hotness info derived from profile.
721 FuncFreqAttr FreqAttr;
722
Rong Xuf430ae42015-12-09 18:08:16 +0000723 // Find the Instrumented BB and set the value.
724 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
725
726 // Set the edge counter value for the unknown edge -- there should be only
727 // one unknown edge.
728 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
729
730 // Return FuncName string;
731 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000732
733 // Set the hot/cold inline hints based on the count values.
734 // FIXME: This function should be removed once the functionality in
735 // the inliner is implemented.
736 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
737 if (ProgramMaxCount == 0)
738 return;
739 // Threshold of the hot functions.
740 const BranchProbability HotFunctionThreshold(1, 100);
741 // Threshold of the cold functions.
742 const BranchProbability ColdFunctionThreshold(2, 10000);
743 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
744 FreqAttr = FFA_Hot;
745 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
746 FreqAttr = FFA_Cold;
747 }
Rong Xuf430ae42015-12-09 18:08:16 +0000748};
749
750// Visit all the edges and assign the count value for the instrumented
751// edges and the BB.
752void PGOUseFunc::setInstrumentedCounts(
753 const std::vector<uint64_t> &CountFromProfile) {
754
Xinliang David Lid1197612016-08-01 20:25:06 +0000755 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000756 // Use a worklist as we will update the vector during the iteration.
757 std::vector<PGOUseEdge *> WorkList;
758 for (auto &E : FuncInfo.MST.AllEdges)
759 WorkList.push_back(E.get());
760
761 uint32_t I = 0;
762 for (auto &E : WorkList) {
763 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
764 if (!InstrBB)
765 continue;
766 uint64_t CountValue = CountFromProfile[I++];
767 if (!E->Removed) {
768 getBBInfo(InstrBB).setBBInfoCount(CountValue);
769 E->setEdgeCount(CountValue);
770 continue;
771 }
772
773 // Need to add two new edges.
774 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
775 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
776 // Add new edge of SrcBB->InstrBB.
777 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
778 NewEdge.setEdgeCount(CountValue);
779 // Add new edge of InstrBB->DestBB.
780 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
781 NewEdge1.setEdgeCount(CountValue);
782 NewEdge1.InMST = true;
783 getBBInfo(InstrBB).setBBInfoCount(CountValue);
784 }
Rong Xu33308f92016-10-25 21:47:24 +0000785 ProfileCountSize = CountFromProfile.size();
786 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000787}
788
789// Set the count value for the unknown edge. There should be one and only one
790// unknown edge in Edges vector.
791void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
792 for (auto &E : Edges) {
793 if (E->CountValid)
794 continue;
795 E->setEdgeCount(Value);
796
797 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
798 getBBInfo(E->DestBB).UnknownCountInEdge--;
799 return;
800 }
801 llvm_unreachable("Cannot find the unknown count edge");
802}
803
804// Read the profile from ProfileFileName and assign the value to the
805// instrumented BB and the edges. This function also updates ProgramMaxCount.
806// Return true if the profile are successfully read, and false on errors.
807bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
808 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000809 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000810 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000811 if (Error E = Result.takeError()) {
812 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
813 auto Err = IPE.get();
814 bool SkipWarning = false;
815 if (Err == instrprof_error::unknown_function) {
816 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000817 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000818 } else if (Err == instrprof_error::hash_mismatch ||
819 Err == instrprof_error::malformed) {
820 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +0000821 SkipWarning =
822 NoPGOWarnMismatch ||
823 (NoPGOWarnMismatchComdat &&
824 (F.hasComdat() ||
825 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000826 }
Rong Xuf430ae42015-12-09 18:08:16 +0000827
Vedant Kumar9152fd12016-05-19 03:54:45 +0000828 if (SkipWarning)
829 return;
830
831 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
832 Ctx.diagnose(
833 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
834 });
Rong Xuf430ae42015-12-09 18:08:16 +0000835 return false;
836 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000837 ProfileRecord = std::move(Result.get());
838 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000839
840 NumOfPGOFunc++;
841 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
842 uint64_t ValueSum = 0;
843 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
844 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
845 ValueSum += CountFromProfile[I];
846 }
847
848 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
849
850 getBBInfo(nullptr).UnknownCountOutEdge = 2;
851 getBBInfo(nullptr).UnknownCountInEdge = 2;
852
853 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000854 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000855 return true;
856}
857
858// Populate the counters from instrumented BBs to all BBs.
859// In the end of this operation, all BBs should have a valid count value.
860void PGOUseFunc::populateCounters() {
861 // First set up Count variable for all BBs.
862 for (auto &E : FuncInfo.MST.AllEdges) {
863 if (E->Removed)
864 continue;
865
866 const BasicBlock *SrcBB = E->SrcBB;
867 const BasicBlock *DestBB = E->DestBB;
868 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
869 UseBBInfo &DestInfo = getBBInfo(DestBB);
870 SrcInfo.OutEdges.push_back(E.get());
871 DestInfo.InEdges.push_back(E.get());
872 SrcInfo.UnknownCountOutEdge++;
873 DestInfo.UnknownCountInEdge++;
874
875 if (!E->CountValid)
876 continue;
877 DestInfo.UnknownCountInEdge--;
878 SrcInfo.UnknownCountOutEdge--;
879 }
880
881 bool Changes = true;
882 unsigned NumPasses = 0;
883 while (Changes) {
884 NumPasses++;
885 Changes = false;
886
887 // For efficient traversal, it's better to start from the end as most
888 // of the instrumented edges are at the end.
889 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +0000890 UseBBInfo *Count = findBBInfo(&BB);
891 if (Count == nullptr)
892 continue;
893 if (!Count->CountValid) {
894 if (Count->UnknownCountOutEdge == 0) {
895 Count->CountValue = sumEdgeCount(Count->OutEdges);
896 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000897 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +0000898 } else if (Count->UnknownCountInEdge == 0) {
899 Count->CountValue = sumEdgeCount(Count->InEdges);
900 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000901 Changes = true;
902 }
903 }
Rong Xua5b57452016-12-02 19:10:29 +0000904 if (Count->CountValid) {
905 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000906 uint64_t Total = 0;
907 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
908 // If the one of the successor block can early terminate (no-return),
909 // we can end up with situation where out edge sum count is larger as
910 // the source BB's count is collected by a post-dominated block.
911 if (Count->CountValue > OutSum)
912 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +0000913 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000914 Changes = true;
915 }
Rong Xua5b57452016-12-02 19:10:29 +0000916 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000917 uint64_t Total = 0;
918 uint64_t InSum = sumEdgeCount(Count->InEdges);
919 if (Count->CountValue > InSum)
920 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +0000921 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000922 Changes = true;
923 }
924 }
925 }
926 }
927
928 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000929#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000930 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +0000931 for (auto &BB : F) {
932 auto BI = findBBInfo(&BB);
933 if (BI == nullptr)
934 continue;
935 assert(BI->CountValid && "BB count is not valid");
936 }
Sean Silva8c7e1212016-05-28 04:19:45 +0000937#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000938 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +0000939 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000940 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +0000941 for (auto &BB : F) {
942 auto BI = findBBInfo(&BB);
943 if (BI == nullptr)
944 continue;
945 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
946 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000947 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000948
Rong Xu33308f92016-10-25 21:47:24 +0000949 // Now annotate select instructions
950 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
951 assert(CountPosition == ProfileCountSize);
952
Rong Xuf430ae42015-12-09 18:08:16 +0000953 DEBUG(FuncInfo.dumpInfo("after reading profile."));
954}
955
Xinliang David Li4ca17332016-09-18 18:34:07 +0000956static void setProfMetadata(Module *M, Instruction *TI,
Xinliang David Li63248ab2016-08-19 06:31:45 +0000957 ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) {
Xinliang David Li2c933682016-08-19 05:31:33 +0000958 MDBuilder MDB(M->getContext());
959 assert(MaxCount > 0 && "Bad max count");
960 uint64_t Scale = calculateCountScale(MaxCount);
961 SmallVector<unsigned, 4> Weights;
962 for (const auto &ECI : EdgeCounts)
963 Weights.push_back(scaleBranchCount(ECI, Scale));
964
965 DEBUG(dbgs() << "Weight is: ";
966 for (const auto &W : Weights) { dbgs() << W << " "; }
967 dbgs() << "\n";);
968 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
969}
970
Rong Xuf430ae42015-12-09 18:08:16 +0000971// Assign the scaled count values to the BB with multiple out edges.
972void PGOUseFunc::setBranchWeights() {
973 // Generate MD_prof metadata for every branch instruction.
974 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000975 for (auto &BB : F) {
976 TerminatorInst *TI = BB.getTerminator();
977 if (TI->getNumSuccessors() < 2)
978 continue;
979 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
980 continue;
981 if (getBBInfo(&BB).CountValue == 0)
982 continue;
983
984 // We have a non-zero Branch BB.
985 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
986 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +0000987 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +0000988 uint64_t MaxCount = 0;
989 for (unsigned s = 0; s < Size; s++) {
990 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
991 const BasicBlock *SrcBB = E->SrcBB;
992 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000993 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000994 continue;
995 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
996 uint64_t EdgeCount = E->CountValue;
997 if (EdgeCount > MaxCount)
998 MaxCount = EdgeCount;
999 EdgeCounts[SuccNum] = EdgeCount;
1000 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001001 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001002 }
1003}
Rong Xu13b01dc2016-02-10 18:24:45 +00001004
Xinliang David Li4ca17332016-09-18 18:34:07 +00001005void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1006 Module *M = F.getParent();
1007 IRBuilder<> Builder(&SI);
1008 Type *Int64Ty = Builder.getInt64Ty();
1009 Type *I8PtrTy = Builder.getInt8PtrTy();
1010 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1011 Builder.CreateCall(
1012 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1013 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1014 Builder.getInt64(FuncHash),
1015 Builder.getInt32(TotalNumCtrs), Builder.getInt32(*CurCtrIdx), Step});
1016 ++(*CurCtrIdx);
1017}
1018
1019void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1020 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1021 assert(*CurCtrIdx < CountFromProfile.size() &&
1022 "Out of bound access of counters");
1023 uint64_t SCounts[2];
1024 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1025 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001026 uint64_t TotalCount = 0;
1027 auto BI = UseFunc->findBBInfo(SI.getParent());
1028 if (BI != nullptr)
1029 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001030 // False Count
1031 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1032 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001033 if (MaxCount)
1034 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001035}
1036
1037void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1038 if (!PGOInstrSelect)
1039 return;
1040 // FIXME: do not handle this yet.
1041 if (SI.getCondition()->getType()->isVectorTy())
1042 return;
1043
1044 NSIs++;
1045 switch (Mode) {
1046 case VM_counting:
1047 return;
1048 case VM_instrument:
1049 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001050 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001051 case VM_annotate:
1052 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001053 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001054 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001055
1056 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001057}
1058
Rong Xu13b01dc2016-02-10 18:24:45 +00001059// Traverse all the indirect callsites and annotate the instructions.
1060void PGOUseFunc::annotateIndirectCallSites() {
1061 if (DisableValueProfiling)
1062 return;
1063
Rong Xu8e8fe852016-04-01 16:43:30 +00001064 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001065 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001066
Rong Xu13b01dc2016-02-10 18:24:45 +00001067 unsigned IndirectCallSiteIndex = 0;
Xinliang David Li9780fc12016-09-20 22:39:47 +00001068 auto &IndirectCallSites = FuncInfo.IndirectCallSites;
Rong Xu9e926e82016-02-29 19:16:04 +00001069 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +00001070 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +00001071 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001072 std::string Msg =
1073 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +00001074 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +00001075 auto &Ctx = M->getContext();
1076 Ctx.diagnose(
1077 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1078 return;
1079 }
1080
Rong Xu0eb36032016-04-01 23:16:44 +00001081 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001082 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +00001083 << IndirectCallSiteIndex << " out of " << NumValueSites
1084 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +00001085 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +00001086 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +00001087 IndirectCallSiteIndex++;
1088 }
1089}
Rong Xuf430ae42015-12-09 18:08:16 +00001090} // end anonymous namespace
1091
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001092// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001093// aware this is an ir_level profile so it can set the version flag.
1094static void createIRLevelProfileFlagVariable(Module &M) {
1095 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1096 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001097 auto IRLevelVersionVariable = new GlobalVariable(
1098 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1099 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001100 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001101 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1102 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001103 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001104 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001105 else
Rong Xu9e926e82016-02-29 19:16:04 +00001106 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001107 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001108}
1109
Rong Xu705f7772016-07-25 18:45:37 +00001110// Collect the set of members for each Comdat in module M and store
1111// in ComdatMembers.
1112static void collectComdatMembers(
1113 Module &M,
1114 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1115 if (!DoComdatRenaming)
1116 return;
1117 for (Function &F : M)
1118 if (Comdat *C = F.getComdat())
1119 ComdatMembers.insert(std::make_pair(C, &F));
1120 for (GlobalVariable &GV : M.globals())
1121 if (Comdat *C = GV.getComdat())
1122 ComdatMembers.insert(std::make_pair(C, &GV));
1123 for (GlobalAlias &GA : M.aliases())
1124 if (Comdat *C = GA.getComdat())
1125 ComdatMembers.insert(std::make_pair(C, &GA));
1126}
1127
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001128static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001129 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1130 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001131 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001132 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1133 collectComdatMembers(M, ComdatMembers);
1134
Rong Xuf430ae42015-12-09 18:08:16 +00001135 for (auto &F : M) {
1136 if (F.isDeclaration())
1137 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001138 auto *BPI = LookupBPI(F);
1139 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001140 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001141 }
1142 return true;
1143}
1144
Xinliang David Li8aebf442016-05-06 05:49:19 +00001145bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001146 if (skipModule(M))
1147 return false;
1148
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001149 auto LookupBPI = [this](Function &F) {
1150 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001151 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001152 auto LookupBFI = [this](Function &F) {
1153 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001154 };
1155 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1156}
1157
Xinliang David Li8aebf442016-05-06 05:49:19 +00001158PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001159 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001160
1161 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001162 auto LookupBPI = [&FAM](Function &F) {
1163 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001164 };
1165
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001166 auto LookupBFI = [&FAM](Function &F) {
1167 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001168 };
1169
1170 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1171 return PreservedAnalyses::all();
1172
1173 return PreservedAnalyses::none();
1174}
1175
Xinliang David Lida195582016-05-10 21:59:52 +00001176static bool annotateAllFunctions(
1177 Module &M, StringRef ProfileFileName,
1178 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001179 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001180 DEBUG(dbgs() << "Read in profile counters: ");
1181 auto &Ctx = M.getContext();
1182 // Read the counter array from file.
1183 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001184 if (Error E = ReaderOrErr.takeError()) {
1185 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1186 Ctx.diagnose(
1187 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1188 });
Rong Xuf430ae42015-12-09 18:08:16 +00001189 return false;
1190 }
1191
Xinliang David Lida195582016-05-10 21:59:52 +00001192 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1193 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001194 if (!PGOReader) {
1195 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001196 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001197 return false;
1198 }
Rong Xu33c76c02016-02-10 17:18:30 +00001199 // TODO: might need to change the warning once the clang option is finalized.
1200 if (!PGOReader->isIRLevelProfile()) {
1201 Ctx.diagnose(DiagnosticInfoPGOProfile(
1202 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1203 return false;
1204 }
1205
Rong Xu705f7772016-07-25 18:45:37 +00001206 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1207 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001208 std::vector<Function *> HotFunctions;
1209 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001210 for (auto &F : M) {
1211 if (F.isDeclaration())
1212 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001213 auto *BPI = LookupBPI(F);
1214 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001215 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001216 if (!Func.readCounters(PGOReader.get()))
1217 continue;
1218 Func.populateCounters();
1219 Func.setBranchWeights();
1220 Func.annotateIndirectCallSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001221 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1222 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001223 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001224 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1225 HotFunctions.push_back(&F);
Xinliang David Licb253ce2017-01-23 18:58:24 +00001226 if (PGOViewCounts &&
1227 (PGOViewFunction.empty() || F.getName().equals(PGOViewFunction))) {
1228 LoopInfo LI{DominatorTree(F)};
1229 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1230 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1231 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1232 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1233
1234 NewBFI->view();
1235 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001236 if (PGOViewRawCounts &&
1237 (PGOViewFunction.empty() || F.getName().equals(PGOViewFunction))) {
1238 if (PGOViewFunction.empty())
1239 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1240 else
1241 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1242 }
Rong Xuf430ae42015-12-09 18:08:16 +00001243 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001244 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001245 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001246 // We have to apply these attributes at the end because their presence
1247 // can affect the BranchProbabilityInfo of any callers, resulting in an
1248 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001249 for (auto &F : HotFunctions) {
1250 F->addFnAttr(llvm::Attribute::InlineHint);
1251 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1252 << "\n");
1253 }
1254 for (auto &F : ColdFunctions) {
1255 F->addFnAttr(llvm::Attribute::Cold);
1256 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1257 }
Rong Xuf430ae42015-12-09 18:08:16 +00001258 return true;
1259}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001260
Xinliang David Lida195582016-05-10 21:59:52 +00001261PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001262 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001263 if (!PGOTestProfileFile.empty())
1264 ProfileFileName = PGOTestProfileFile;
1265}
1266
1267PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001268 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001269
1270 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1271 auto LookupBPI = [&FAM](Function &F) {
1272 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1273 };
1274
1275 auto LookupBFI = [&FAM](Function &F) {
1276 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1277 };
1278
1279 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1280 return PreservedAnalyses::all();
1281
1282 return PreservedAnalyses::none();
1283}
1284
Xinliang David Lid55827f2016-05-07 05:39:12 +00001285bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1286 if (skipModule(M))
1287 return false;
1288
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001289 auto LookupBPI = [this](Function &F) {
1290 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001291 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001292 auto LookupBFI = [this](Function &F) {
1293 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001294 };
1295
Xinliang David Lida195582016-05-10 21:59:52 +00001296 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001297}
Xinliang David Lid289e452017-01-27 19:06:25 +00001298
1299namespace llvm {
1300template <> struct GraphTraits<PGOUseFunc *> {
1301 typedef const BasicBlock *NodeRef;
1302 typedef succ_const_iterator ChildIteratorType;
1303 typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1304
1305 static NodeRef getEntryNode(const PGOUseFunc *G) {
1306 return &G->getFunc().front();
1307 }
1308 static ChildIteratorType child_begin(const NodeRef N) {
1309 return succ_begin(N);
1310 }
1311 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1312 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1313 return nodes_iterator(G->getFunc().begin());
1314 }
1315 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1316 return nodes_iterator(G->getFunc().end());
1317 }
1318};
1319
1320template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1321 explicit DOTGraphTraits(bool isSimple = false)
1322 : DefaultDOTGraphTraits(isSimple) {}
1323
1324 static std::string getGraphName(const PGOUseFunc *G) {
1325 return G->getFunc().getName();
1326 }
1327
1328 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1329 std::string Result;
1330 raw_string_ostream OS(Result);
1331 OS << Node->getName().str() << " : ";
1332 UseBBInfo *BI = Graph->findBBInfo(Node);
1333 if (BI && BI->CountValid)
1334 OS << BI->CountValue;
1335 else
1336 OS << "Unknown";
1337 return Result;
1338 }
1339};
1340}