blob: 6b3c4b92e760391204e9413b9ed922ce04621ef7 [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 Li58fcc9b2017-02-02 21:29:17 +0000132static cl::opt<bool>
133 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
134 cl::desc("Use this option to turn on/off "
135 "warnings about missing profile data for "
136 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000137
138// Command line option to enable/disable the warning about a hash mismatch in
139// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000140static cl::opt<bool>
141 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
142 cl::desc("Use this option to turn off/on "
143 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000144
Rong Xu20f5df12017-01-11 20:19:41 +0000145// Command line option to enable/disable the warning about a hash mismatch in
146// the profile data for Comdat functions, which often turns out to be false
147// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000148static cl::opt<bool>
149 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
150 cl::Hidden,
151 cl::desc("The option is used to turn on/off "
152 "warnings about hash mismatch for comdat "
153 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000154
Xinliang David Li4ca17332016-09-18 18:34:07 +0000155// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000156static cl::opt<bool>
157 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
158 cl::desc("Use this option to turn on/off SELECT "
159 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000160
Xinliang David Lid289e452017-01-27 19:06:25 +0000161// Command line option to turn on CFG dot dump of raw profile counts
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000162static cl::opt<bool>
163 PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden,
164 cl::desc("A boolean option to show CFG dag "
165 "with raw profile counts from "
166 "profile data. See also option "
167 "-pgo-view-counts. To limit graph "
168 "display to only one function, use "
169 "filtering option -view-bfi-func-name."));
Xinliang David Lid289e452017-01-27 19:06:25 +0000170
Xinliang David Licb253ce2017-01-23 18:58:24 +0000171// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000172// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Xinliang David Licb253ce2017-01-23 18:58:24 +0000173extern cl::opt<bool> PGOViewCounts;
174
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000175// Command line option to specify the name of the function for CFG dump
176// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
177extern cl::opt<std::string> ViewBlockFreqFuncName;
178
Rong Xuf430ae42015-12-09 18:08:16 +0000179namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000180
181/// The select instruction visitor plays three roles specified
182/// by the mode. In \c VM_counting mode, it simply counts the number of
183/// select instructions. In \c VM_instrument mode, it inserts code to count
184/// the number times TrueValue of select is taken. In \c VM_annotate mode,
185/// it reads the profile data and annotate the select instruction with metadata.
186enum VisitMode { VM_counting, VM_instrument, VM_annotate };
187class PGOUseFunc;
188
189/// Instruction Visitor class to visit select instructions.
190struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
191 Function &F;
192 unsigned NSIs = 0; // Number of select instructions instrumented.
193 VisitMode Mode = VM_counting; // Visiting mode.
194 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
195 unsigned TotalNumCtrs = 0; // Total number of counters
196 GlobalVariable *FuncNameVar = nullptr;
197 uint64_t FuncHash = 0;
198 PGOUseFunc *UseFunc = nullptr;
199
200 SelectInstVisitor(Function &Func) : F(Func) {}
201
202 void countSelects(Function &Func) {
203 Mode = VM_counting;
204 visit(Func);
205 }
206 // Visit the IR stream and instrument all select instructions. \p
207 // Ind is a pointer to the counter index variable; \p TotalNC
208 // is the total number of counters; \p FNV is the pointer to the
209 // PGO function name var; \p FHash is the function hash.
210 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
211 GlobalVariable *FNV, uint64_t FHash) {
212 Mode = VM_instrument;
213 CurCtrIdx = Ind;
214 TotalNumCtrs = TotalNC;
215 FuncHash = FHash;
216 FuncNameVar = FNV;
217 visit(Func);
218 }
219
220 // Visit the IR stream and annotate all select instructions.
221 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
222 Mode = VM_annotate;
223 UseFunc = UF;
224 CurCtrIdx = Ind;
225 visit(Func);
226 }
227
228 void instrumentOneSelectInst(SelectInst &SI);
229 void annotateOneSelectInst(SelectInst &SI);
230 // Visit \p SI instruction and perform tasks according to visit mode.
231 void visitSelectInst(SelectInst &SI);
232 unsigned getNumOfSelectInsts() const { return NSIs; }
233};
234
Xinliang David Li8aebf442016-05-06 05:49:19 +0000235class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000236public:
237 static char ID;
238
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000239 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000240 initializePGOInstrumentationGenLegacyPassPass(
241 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000242 }
243
Mehdi Amini117296c2016-10-01 02:56:57 +0000244 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000245
246private:
247 bool runOnModule(Module &M) override;
248
249 void getAnalysisUsage(AnalysisUsage &AU) const override {
250 AU.addRequired<BlockFrequencyInfoWrapperPass>();
251 }
252};
253
Xinliang David Lid55827f2016-05-07 05:39:12 +0000254class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000255public:
256 static char ID;
257
258 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000259 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000260 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000261 if (!PGOTestProfileFile.empty())
262 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000263 initializePGOInstrumentationUseLegacyPassPass(
264 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000265 }
266
Mehdi Amini117296c2016-10-01 02:56:57 +0000267 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000268
269private:
270 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000271
Xinliang David Lida195582016-05-10 21:59:52 +0000272 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000273 void getAnalysisUsage(AnalysisUsage &AU) const override {
274 AU.addRequired<BlockFrequencyInfoWrapperPass>();
275 }
276};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000277
Rong Xuf430ae42015-12-09 18:08:16 +0000278} // end anonymous namespace
279
Xinliang David Li8aebf442016-05-06 05:49:19 +0000280char PGOInstrumentationGenLegacyPass::ID = 0;
281INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000282 "PGO instrumentation.", false, false)
283INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
284INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000285INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000286 "PGO instrumentation.", false, false)
287
Xinliang David Li8aebf442016-05-06 05:49:19 +0000288ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
289 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000290}
291
Xinliang David Lid55827f2016-05-07 05:39:12 +0000292char PGOInstrumentationUseLegacyPass::ID = 0;
293INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000294 "Read PGO instrumentation profile.", false, false)
295INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
296INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000297INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000298 "Read PGO instrumentation profile.", false, false)
299
Xinliang David Lid55827f2016-05-07 05:39:12 +0000300ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
301 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000302}
303
304namespace {
305/// \brief An MST based instrumentation for PGO
306///
307/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
308/// in the function level.
309struct PGOEdge {
310 // This class implements the CFG edges. Note the CFG can be a multi-graph.
311 // So there might be multiple edges with same SrcBB and DestBB.
312 const BasicBlock *SrcBB;
313 const BasicBlock *DestBB;
314 uint64_t Weight;
315 bool InMST;
316 bool Removed;
317 bool IsCritical;
318 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
319 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
320 IsCritical(false) {}
321 // Return the information string of an edge.
322 const std::string infoString() const {
323 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
324 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
325 }
326};
327
328// This class stores the auxiliary information for each BB.
329struct BBInfo {
330 BBInfo *Group;
331 uint32_t Index;
332 uint32_t Rank;
333
334 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
335
336 // Return the information string of this object.
337 const std::string infoString() const {
338 return (Twine("Index=") + Twine(Index)).str();
339 }
340};
341
342// This class implements the CFG edges. Note the CFG can be a multi-graph.
343template <class Edge, class BBInfo> class FuncPGOInstrumentation {
344private:
345 Function &F;
346 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000347 void renameComdatFunction();
348 // A map that stores the Comdat group in function F.
349 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000350
351public:
Rong Xua3bbf962017-03-15 18:23:39 +0000352 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000353 SelectInstVisitor SIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000354 std::string FuncName;
355 GlobalVariable *FuncNameVar;
356 // CFG hash value for this function.
357 uint64_t FunctionHash;
358
359 // The Minimum Spanning Tree of function CFG.
360 CFGMST<Edge, BBInfo> MST;
361
362 // Give an edge, find the BB that will be instrumented.
363 // Return nullptr if there is no BB to be instrumented.
364 BasicBlock *getInstrBB(Edge *E);
365
366 // Return the auxiliary BB information.
367 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
368
Rong Xua5b57452016-12-02 19:10:29 +0000369 // Return the auxiliary BB information if available.
370 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
371
Rong Xuf430ae42015-12-09 18:08:16 +0000372 // Dump edges and BB information.
373 void dumpInfo(std::string Str = "") const {
374 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000375 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000376 }
377
Rong Xu705f7772016-07-25 18:45:37 +0000378 FuncPGOInstrumentation(
379 Function &Func,
380 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
381 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
382 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000383 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
384 SIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000385
386 // This should be done before CFG hash computation.
387 SIVisitor.countSelects(Func);
388 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xua3bbf962017-03-15 18:23:39 +0000389 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000390
Rong Xuf430ae42015-12-09 18:08:16 +0000391 FuncName = getPGOFuncName(F);
392 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000393 if (ComdatMembers.size())
394 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000395 DEBUG(dumpInfo("after CFGMST"));
396
397 NumOfPGOBB += MST.BBInfos.size();
398 for (auto &E : MST.AllEdges) {
399 if (E->Removed)
400 continue;
401 NumOfPGOEdge++;
402 if (!E->InMST)
403 NumOfPGOInstrument++;
404 }
405
406 if (CreateGlobalVar)
407 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000408 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000409
410 // Return the number of profile counters needed for the function.
411 unsigned getNumCounters() {
412 unsigned NumCounters = 0;
413 for (auto &E : this->MST.AllEdges) {
414 if (!E->InMST && !E->Removed)
415 NumCounters++;
416 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000417 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000418 }
Rong Xuf430ae42015-12-09 18:08:16 +0000419};
420
421// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
422// value of each BB in the CFG. The higher 32 bits record the number of edges.
423template <class Edge, class BBInfo>
424void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
425 std::vector<char> Indexes;
426 JamCRC JC;
427 for (auto &BB : F) {
428 const TerminatorInst *TI = BB.getTerminator();
429 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
430 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000431 auto BI = findBBInfo(Succ);
432 if (BI == nullptr)
433 continue;
434 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000435 for (int J = 0; J < 4; J++)
436 Indexes.push_back((char)(Index >> (J * 8)));
437 }
438 }
439 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000440 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000441 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000442 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
443}
444
445// Check if we can safely rename this Comdat function.
446static bool canRenameComdat(
447 Function &F,
448 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000449 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000450 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000451
452 // FIXME: Current only handle those Comdat groups that only containing one
453 // function and function aliases.
454 // (1) For a Comdat group containing multiple functions, we need to have a
455 // unique postfix based on the hashes for each function. There is a
456 // non-trivial code refactoring to do this efficiently.
457 // (2) Variables can not be renamed, so we can not rename Comdat function in a
458 // group including global vars.
459 Comdat *C = F.getComdat();
460 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
461 if (dyn_cast<GlobalAlias>(CM.second))
462 continue;
463 Function *FM = dyn_cast<Function>(CM.second);
464 if (FM != &F)
465 return false;
466 }
467 return true;
468}
469
470// Append the CFGHash to the Comdat function name.
471template <class Edge, class BBInfo>
472void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
473 if (!canRenameComdat(F, ComdatMembers))
474 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000475 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000476 std::string NewFuncName =
477 Twine(F.getName() + "." + Twine(FunctionHash)).str();
478 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000479 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000480 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
481 Comdat *NewComdat;
482 Module *M = F.getParent();
483 // For AvailableExternallyLinkage functions, change the linkage to
484 // LinkOnceODR and put them into comdat. This is because after renaming, there
485 // is no backup external copy available for the function.
486 if (!F.hasComdat()) {
487 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
488 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
489 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
490 F.setComdat(NewComdat);
491 return;
492 }
493
494 // This function belongs to a single function Comdat group.
495 Comdat *OrigComdat = F.getComdat();
496 std::string NewComdatName =
497 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
498 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
499 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
500
501 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
502 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
503 // For aliases, change the name directly.
504 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000505 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000506 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000507 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000508 continue;
509 }
510 // Must be a function.
511 Function *CF = dyn_cast<Function>(CM.second);
512 assert(CF);
513 CF->setComdat(NewComdat);
514 }
Rong Xuf430ae42015-12-09 18:08:16 +0000515}
516
517// Given a CFG E to be instrumented, find which BB to place the instrumented
518// code. The function will split the critical edge if necessary.
519template <class Edge, class BBInfo>
520BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
521 if (E->InMST || E->Removed)
522 return nullptr;
523
524 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
525 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
526 // For a fake edge, instrument the real BB.
527 if (SrcBB == nullptr)
528 return DestBB;
529 if (DestBB == nullptr)
530 return SrcBB;
531
532 // Instrument the SrcBB if it has a single successor,
533 // otherwise, the DestBB if this is not a critical edge.
534 TerminatorInst *TI = SrcBB->getTerminator();
535 if (TI->getNumSuccessors() <= 1)
536 return SrcBB;
537 if (!E->IsCritical)
538 return DestBB;
539
540 // For a critical edge, we have to split. Instrument the newly
541 // created BB.
542 NumOfPGOSplit++;
543 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
544 << getBBInfo(DestBB).Index << "\n");
545 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
546 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
547 assert(InstrBB && "Critical edge is not split");
548
549 E->Removed = true;
550 return InstrBB;
551}
552
Rong Xued9fec72016-01-21 18:11:44 +0000553// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000554// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000555static void instrumentOneFunc(
556 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
557 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000558 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
559 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000560 unsigned NumCounters = FuncInfo.getNumCounters();
561
Rong Xuf430ae42015-12-09 18:08:16 +0000562 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000563 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000564 for (auto &E : FuncInfo.MST.AllEdges) {
565 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
566 if (!InstrBB)
567 continue;
568
569 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
570 assert(Builder.GetInsertPoint() != InstrBB->end() &&
571 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000572 Builder.CreateCall(
573 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
574 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
575 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
576 Builder.getInt32(I++)});
577 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000578
579 // Now instrument select instructions:
580 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
581 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000582 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000583
584 if (DisableValueProfiling)
585 return;
586
587 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000588 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000589 CallSite CS(I);
590 Value *Callee = CS.getCalledValue();
591 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
592 << NumIndirectCallSites << "\n");
593 IRBuilder<> Builder(I);
594 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
595 "Cannot get the Instrumentation point");
596 Builder.CreateCall(
597 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
598 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
599 Builder.getInt64(FuncInfo.FunctionHash),
600 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000601 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000602 Builder.getInt32(NumIndirectCallSites++)});
603 }
604 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000605}
606
607// This class represents a CFG edge in profile use compilation.
608struct PGOUseEdge : public PGOEdge {
609 bool CountValid;
610 uint64_t CountValue;
611 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
612 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
613
614 // Set edge count value
615 void setEdgeCount(uint64_t Value) {
616 CountValue = Value;
617 CountValid = true;
618 }
619
620 // Return the information string for this object.
621 const std::string infoString() const {
622 if (!CountValid)
623 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000624 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
625 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000626 }
627};
628
629typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
630
631// This class stores the auxiliary information for each BB.
632struct UseBBInfo : public BBInfo {
633 uint64_t CountValue;
634 bool CountValid;
635 int32_t UnknownCountInEdge;
636 int32_t UnknownCountOutEdge;
637 DirectEdges InEdges;
638 DirectEdges OutEdges;
639 UseBBInfo(unsigned IX)
640 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
641 UnknownCountOutEdge(0) {}
642 UseBBInfo(unsigned IX, uint64_t C)
643 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
644 UnknownCountOutEdge(0) {}
645
646 // Set the profile count value for this BB.
647 void setBBInfoCount(uint64_t Value) {
648 CountValue = Value;
649 CountValid = true;
650 }
651
652 // Return the information string of this object.
653 const std::string infoString() const {
654 if (!CountValid)
655 return BBInfo::infoString();
656 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
657 }
658};
659
660// Sum up the count values for all the edges.
661static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
662 uint64_t Total = 0;
663 for (auto &E : Edges) {
664 if (E->Removed)
665 continue;
666 Total += E->CountValue;
667 }
668 return Total;
669}
670
671class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000672public:
Rong Xu705f7772016-07-25 18:45:37 +0000673 PGOUseFunc(Function &Func, Module *Modu,
674 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
675 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000676 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000677 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Rong Xu33308f92016-10-25 21:47:24 +0000678 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000679
680 // Read counts for the instrumented BB from profile.
681 bool readCounters(IndexedInstrProfReader *PGOReader);
682
683 // Populate the counts for all BBs.
684 void populateCounters();
685
686 // Set the branch weights based on the count values.
687 void setBranchWeights();
688
Rong Xua3bbf962017-03-15 18:23:39 +0000689 // Annotate the value profile call sites all all value kind.
690 void annotateValueSites();
691
692 // Annotate the value profile call sites for one value kind.
693 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000694
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000695 // The hotness of the function from the profile count.
696 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
697
698 // Return the function hotness from the profile.
699 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
700
Rong Xu705f7772016-07-25 18:45:37 +0000701 // Return the function hash.
702 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000703 // Return the profile record for this function;
704 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
705
Xinliang David Li4ca17332016-09-18 18:34:07 +0000706 // Return the auxiliary BB information.
707 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
708 return FuncInfo.getBBInfo(BB);
709 }
710
Rong Xua5b57452016-12-02 19:10:29 +0000711 // Return the auxiliary BB information if available.
712 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
713 return FuncInfo.findBBInfo(BB);
714 }
715
Xinliang David Lid289e452017-01-27 19:06:25 +0000716 Function &getFunc() const { return F; }
717
Rong Xuf430ae42015-12-09 18:08:16 +0000718private:
719 Function &F;
720 Module *M;
721 // This member stores the shared information with class PGOGenFunc.
722 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
723
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000724 // The maximum count value in the profile. This is only used in PGO use
725 // compilation.
726 uint64_t ProgramMaxCount;
727
Rong Xu33308f92016-10-25 21:47:24 +0000728 // Position of counter that remains to be read.
729 uint32_t CountPosition;
730
731 // Total size of the profile count for this function.
732 uint32_t ProfileCountSize;
733
Rong Xu13b01dc2016-02-10 18:24:45 +0000734 // ProfileRecord for this function.
735 InstrProfRecord ProfileRecord;
736
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000737 // Function hotness info derived from profile.
738 FuncFreqAttr FreqAttr;
739
Rong Xuf430ae42015-12-09 18:08:16 +0000740 // Find the Instrumented BB and set the value.
741 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
742
743 // Set the edge counter value for the unknown edge -- there should be only
744 // one unknown edge.
745 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
746
747 // Return FuncName string;
748 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000749
750 // Set the hot/cold inline hints based on the count values.
751 // FIXME: This function should be removed once the functionality in
752 // the inliner is implemented.
753 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
754 if (ProgramMaxCount == 0)
755 return;
756 // Threshold of the hot functions.
757 const BranchProbability HotFunctionThreshold(1, 100);
758 // Threshold of the cold functions.
759 const BranchProbability ColdFunctionThreshold(2, 10000);
760 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
761 FreqAttr = FFA_Hot;
762 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
763 FreqAttr = FFA_Cold;
764 }
Rong Xuf430ae42015-12-09 18:08:16 +0000765};
766
767// Visit all the edges and assign the count value for the instrumented
768// edges and the BB.
769void PGOUseFunc::setInstrumentedCounts(
770 const std::vector<uint64_t> &CountFromProfile) {
771
Xinliang David Lid1197612016-08-01 20:25:06 +0000772 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000773 // Use a worklist as we will update the vector during the iteration.
774 std::vector<PGOUseEdge *> WorkList;
775 for (auto &E : FuncInfo.MST.AllEdges)
776 WorkList.push_back(E.get());
777
778 uint32_t I = 0;
779 for (auto &E : WorkList) {
780 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
781 if (!InstrBB)
782 continue;
783 uint64_t CountValue = CountFromProfile[I++];
784 if (!E->Removed) {
785 getBBInfo(InstrBB).setBBInfoCount(CountValue);
786 E->setEdgeCount(CountValue);
787 continue;
788 }
789
790 // Need to add two new edges.
791 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
792 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
793 // Add new edge of SrcBB->InstrBB.
794 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
795 NewEdge.setEdgeCount(CountValue);
796 // Add new edge of InstrBB->DestBB.
797 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
798 NewEdge1.setEdgeCount(CountValue);
799 NewEdge1.InMST = true;
800 getBBInfo(InstrBB).setBBInfoCount(CountValue);
801 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000802 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000803 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000804}
805
806// Set the count value for the unknown edge. There should be one and only one
807// unknown edge in Edges vector.
808void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
809 for (auto &E : Edges) {
810 if (E->CountValid)
811 continue;
812 E->setEdgeCount(Value);
813
814 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
815 getBBInfo(E->DestBB).UnknownCountInEdge--;
816 return;
817 }
818 llvm_unreachable("Cannot find the unknown count edge");
819}
820
821// Read the profile from ProfileFileName and assign the value to the
822// instrumented BB and the edges. This function also updates ProgramMaxCount.
823// Return true if the profile are successfully read, and false on errors.
824bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
825 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000826 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000827 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000828 if (Error E = Result.takeError()) {
829 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
830 auto Err = IPE.get();
831 bool SkipWarning = false;
832 if (Err == instrprof_error::unknown_function) {
833 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000834 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000835 } else if (Err == instrprof_error::hash_mismatch ||
836 Err == instrprof_error::malformed) {
837 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +0000838 SkipWarning =
839 NoPGOWarnMismatch ||
840 (NoPGOWarnMismatchComdat &&
841 (F.hasComdat() ||
842 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000843 }
Rong Xuf430ae42015-12-09 18:08:16 +0000844
Vedant Kumar9152fd12016-05-19 03:54:45 +0000845 if (SkipWarning)
846 return;
847
848 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
849 Ctx.diagnose(
850 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
851 });
Rong Xuf430ae42015-12-09 18:08:16 +0000852 return false;
853 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000854 ProfileRecord = std::move(Result.get());
855 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000856
857 NumOfPGOFunc++;
858 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
859 uint64_t ValueSum = 0;
860 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
861 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
862 ValueSum += CountFromProfile[I];
863 }
864
865 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
866
867 getBBInfo(nullptr).UnknownCountOutEdge = 2;
868 getBBInfo(nullptr).UnknownCountInEdge = 2;
869
870 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000871 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000872 return true;
873}
874
875// Populate the counters from instrumented BBs to all BBs.
876// In the end of this operation, all BBs should have a valid count value.
877void PGOUseFunc::populateCounters() {
878 // First set up Count variable for all BBs.
879 for (auto &E : FuncInfo.MST.AllEdges) {
880 if (E->Removed)
881 continue;
882
883 const BasicBlock *SrcBB = E->SrcBB;
884 const BasicBlock *DestBB = E->DestBB;
885 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
886 UseBBInfo &DestInfo = getBBInfo(DestBB);
887 SrcInfo.OutEdges.push_back(E.get());
888 DestInfo.InEdges.push_back(E.get());
889 SrcInfo.UnknownCountOutEdge++;
890 DestInfo.UnknownCountInEdge++;
891
892 if (!E->CountValid)
893 continue;
894 DestInfo.UnknownCountInEdge--;
895 SrcInfo.UnknownCountOutEdge--;
896 }
897
898 bool Changes = true;
899 unsigned NumPasses = 0;
900 while (Changes) {
901 NumPasses++;
902 Changes = false;
903
904 // For efficient traversal, it's better to start from the end as most
905 // of the instrumented edges are at the end.
906 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +0000907 UseBBInfo *Count = findBBInfo(&BB);
908 if (Count == nullptr)
909 continue;
910 if (!Count->CountValid) {
911 if (Count->UnknownCountOutEdge == 0) {
912 Count->CountValue = sumEdgeCount(Count->OutEdges);
913 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000914 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +0000915 } else if (Count->UnknownCountInEdge == 0) {
916 Count->CountValue = sumEdgeCount(Count->InEdges);
917 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000918 Changes = true;
919 }
920 }
Rong Xua5b57452016-12-02 19:10:29 +0000921 if (Count->CountValid) {
922 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000923 uint64_t Total = 0;
924 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
925 // If the one of the successor block can early terminate (no-return),
926 // we can end up with situation where out edge sum count is larger as
927 // the source BB's count is collected by a post-dominated block.
928 if (Count->CountValue > OutSum)
929 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +0000930 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000931 Changes = true;
932 }
Rong Xua5b57452016-12-02 19:10:29 +0000933 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000934 uint64_t Total = 0;
935 uint64_t InSum = sumEdgeCount(Count->InEdges);
936 if (Count->CountValue > InSum)
937 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +0000938 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000939 Changes = true;
940 }
941 }
942 }
943 }
944
945 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000946#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000947 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +0000948 for (auto &BB : F) {
949 auto BI = findBBInfo(&BB);
950 if (BI == nullptr)
951 continue;
952 assert(BI->CountValid && "BB count is not valid");
953 }
Sean Silva8c7e1212016-05-28 04:19:45 +0000954#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000955 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +0000956 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000957 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +0000958 for (auto &BB : F) {
959 auto BI = findBBInfo(&BB);
960 if (BI == nullptr)
961 continue;
962 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
963 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000964 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000965
Rong Xu33308f92016-10-25 21:47:24 +0000966 // Now annotate select instructions
967 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
968 assert(CountPosition == ProfileCountSize);
969
Rong Xuf430ae42015-12-09 18:08:16 +0000970 DEBUG(FuncInfo.dumpInfo("after reading profile."));
971}
972
Xinliang David Li4ca17332016-09-18 18:34:07 +0000973static void setProfMetadata(Module *M, Instruction *TI,
Xinliang David Li63248ab2016-08-19 06:31:45 +0000974 ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) {
Xinliang David Li2c933682016-08-19 05:31:33 +0000975 MDBuilder MDB(M->getContext());
976 assert(MaxCount > 0 && "Bad max count");
977 uint64_t Scale = calculateCountScale(MaxCount);
978 SmallVector<unsigned, 4> Weights;
979 for (const auto &ECI : EdgeCounts)
980 Weights.push_back(scaleBranchCount(ECI, Scale));
981
982 DEBUG(dbgs() << "Weight is: ";
Rong Xu0a2a1312017-03-09 19:08:55 +0000983 for (const auto &W : Weights) { dbgs() << W << " "; }
Xinliang David Li2c933682016-08-19 05:31:33 +0000984 dbgs() << "\n";);
985 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
986}
987
Rong Xuf430ae42015-12-09 18:08:16 +0000988// Assign the scaled count values to the BB with multiple out edges.
989void PGOUseFunc::setBranchWeights() {
990 // Generate MD_prof metadata for every branch instruction.
991 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000992 for (auto &BB : F) {
993 TerminatorInst *TI = BB.getTerminator();
994 if (TI->getNumSuccessors() < 2)
995 continue;
996 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
997 continue;
998 if (getBBInfo(&BB).CountValue == 0)
999 continue;
1000
1001 // We have a non-zero Branch BB.
1002 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1003 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001004 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001005 uint64_t MaxCount = 0;
1006 for (unsigned s = 0; s < Size; s++) {
1007 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1008 const BasicBlock *SrcBB = E->SrcBB;
1009 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001010 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001011 continue;
1012 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1013 uint64_t EdgeCount = E->CountValue;
1014 if (EdgeCount > MaxCount)
1015 MaxCount = EdgeCount;
1016 EdgeCounts[SuccNum] = EdgeCount;
1017 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001018 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001019 }
1020}
Rong Xu13b01dc2016-02-10 18:24:45 +00001021
Xinliang David Li4ca17332016-09-18 18:34:07 +00001022void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1023 Module *M = F.getParent();
1024 IRBuilder<> Builder(&SI);
1025 Type *Int64Ty = Builder.getInt64Ty();
1026 Type *I8PtrTy = Builder.getInt8PtrTy();
1027 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1028 Builder.CreateCall(
1029 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1030 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001031 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1032 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001033 ++(*CurCtrIdx);
1034}
1035
1036void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1037 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1038 assert(*CurCtrIdx < CountFromProfile.size() &&
1039 "Out of bound access of counters");
1040 uint64_t SCounts[2];
1041 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1042 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001043 uint64_t TotalCount = 0;
1044 auto BI = UseFunc->findBBInfo(SI.getParent());
1045 if (BI != nullptr)
1046 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001047 // False Count
1048 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1049 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001050 if (MaxCount)
1051 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001052}
1053
1054void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1055 if (!PGOInstrSelect)
1056 return;
1057 // FIXME: do not handle this yet.
1058 if (SI.getCondition()->getType()->isVectorTy())
1059 return;
1060
1061 NSIs++;
1062 switch (Mode) {
1063 case VM_counting:
1064 return;
1065 case VM_instrument:
1066 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001067 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001068 case VM_annotate:
1069 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001070 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001071 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001072
1073 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001074}
1075
Rong Xua3bbf962017-03-15 18:23:39 +00001076// Traverse all valuesites and annotate the instructions for all value kind.
1077void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001078 if (DisableValueProfiling)
1079 return;
1080
Rong Xu8e8fe852016-04-01 16:43:30 +00001081 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001082 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001083
Rong Xua3bbf962017-03-15 18:23:39 +00001084 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1085 annotateValueSites(Kind);
1086}
1087
1088// Annotate the instructions for a specific value kind.
1089void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1090 unsigned ValueSiteIndex = 0;
1091 auto &ValueSites = FuncInfo.ValueSites[Kind];
1092 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1093 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001094 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001095 Ctx.diagnose(DiagnosticInfoPGOProfile(
1096 M->getName().data(),
1097 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1098 " in " + F.getName().str(),
1099 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001100 return;
1101 }
1102
Rong Xua3bbf962017-03-15 18:23:39 +00001103 for (auto &I : ValueSites) {
1104 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1105 << "): Index = " << ValueSiteIndex << " out of "
1106 << NumValueSites << "\n");
1107 annotateValueSite(*M, *I, ProfileRecord,
1108 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1109 MaxNumAnnotations);
1110 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001111 }
1112}
Rong Xuf430ae42015-12-09 18:08:16 +00001113} // end anonymous namespace
1114
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001115// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001116// aware this is an ir_level profile so it can set the version flag.
1117static void createIRLevelProfileFlagVariable(Module &M) {
1118 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1119 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001120 auto IRLevelVersionVariable = new GlobalVariable(
1121 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1122 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001123 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001124 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1125 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001126 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001127 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001128 else
Rong Xu9e926e82016-02-29 19:16:04 +00001129 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001130 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001131}
1132
Rong Xu705f7772016-07-25 18:45:37 +00001133// Collect the set of members for each Comdat in module M and store
1134// in ComdatMembers.
1135static void collectComdatMembers(
1136 Module &M,
1137 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1138 if (!DoComdatRenaming)
1139 return;
1140 for (Function &F : M)
1141 if (Comdat *C = F.getComdat())
1142 ComdatMembers.insert(std::make_pair(C, &F));
1143 for (GlobalVariable &GV : M.globals())
1144 if (Comdat *C = GV.getComdat())
1145 ComdatMembers.insert(std::make_pair(C, &GV));
1146 for (GlobalAlias &GA : M.aliases())
1147 if (Comdat *C = GA.getComdat())
1148 ComdatMembers.insert(std::make_pair(C, &GA));
1149}
1150
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001151static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001152 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1153 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001154 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001155 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1156 collectComdatMembers(M, ComdatMembers);
1157
Rong Xuf430ae42015-12-09 18:08:16 +00001158 for (auto &F : M) {
1159 if (F.isDeclaration())
1160 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001161 auto *BPI = LookupBPI(F);
1162 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001163 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001164 }
1165 return true;
1166}
1167
Xinliang David Li8aebf442016-05-06 05:49:19 +00001168bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001169 if (skipModule(M))
1170 return false;
1171
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001172 auto LookupBPI = [this](Function &F) {
1173 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001174 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001175 auto LookupBFI = [this](Function &F) {
1176 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001177 };
1178 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1179}
1180
Xinliang David Li8aebf442016-05-06 05:49:19 +00001181PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001182 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001183
1184 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001185 auto LookupBPI = [&FAM](Function &F) {
1186 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001187 };
1188
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001189 auto LookupBFI = [&FAM](Function &F) {
1190 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001191 };
1192
1193 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1194 return PreservedAnalyses::all();
1195
1196 return PreservedAnalyses::none();
1197}
1198
Xinliang David Lida195582016-05-10 21:59:52 +00001199static bool annotateAllFunctions(
1200 Module &M, StringRef ProfileFileName,
1201 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001202 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001203 DEBUG(dbgs() << "Read in profile counters: ");
1204 auto &Ctx = M.getContext();
1205 // Read the counter array from file.
1206 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001207 if (Error E = ReaderOrErr.takeError()) {
1208 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1209 Ctx.diagnose(
1210 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1211 });
Rong Xuf430ae42015-12-09 18:08:16 +00001212 return false;
1213 }
1214
Xinliang David Lida195582016-05-10 21:59:52 +00001215 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1216 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001217 if (!PGOReader) {
1218 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001219 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001220 return false;
1221 }
Rong Xu33c76c02016-02-10 17:18:30 +00001222 // TODO: might need to change the warning once the clang option is finalized.
1223 if (!PGOReader->isIRLevelProfile()) {
1224 Ctx.diagnose(DiagnosticInfoPGOProfile(
1225 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1226 return false;
1227 }
1228
Rong Xu705f7772016-07-25 18:45:37 +00001229 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1230 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001231 std::vector<Function *> HotFunctions;
1232 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001233 for (auto &F : M) {
1234 if (F.isDeclaration())
1235 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001236 auto *BPI = LookupBPI(F);
1237 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001238 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001239 if (!Func.readCounters(PGOReader.get()))
1240 continue;
1241 Func.populateCounters();
1242 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001243 Func.annotateValueSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001244 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1245 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001246 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001247 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1248 HotFunctions.push_back(&F);
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001249 if (PGOViewCounts && (ViewBlockFreqFuncName.empty() ||
1250 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001251 LoopInfo LI{DominatorTree(F)};
1252 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1253 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1254 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1255 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1256
1257 NewBFI->view();
1258 }
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001259 if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() ||
1260 F.getName().equals(ViewBlockFreqFuncName))) {
1261 if (ViewBlockFreqFuncName.empty())
Xinliang David Lid289e452017-01-27 19:06:25 +00001262 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1263 else
1264 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1265 }
Rong Xuf430ae42015-12-09 18:08:16 +00001266 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001267 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001268 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001269 // We have to apply these attributes at the end because their presence
1270 // can affect the BranchProbabilityInfo of any callers, resulting in an
1271 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001272 for (auto &F : HotFunctions) {
1273 F->addFnAttr(llvm::Attribute::InlineHint);
1274 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1275 << "\n");
1276 }
1277 for (auto &F : ColdFunctions) {
1278 F->addFnAttr(llvm::Attribute::Cold);
1279 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1280 }
Rong Xuf430ae42015-12-09 18:08:16 +00001281 return true;
1282}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001283
Xinliang David Lida195582016-05-10 21:59:52 +00001284PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001285 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001286 if (!PGOTestProfileFile.empty())
1287 ProfileFileName = PGOTestProfileFile;
1288}
1289
1290PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001291 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001292
1293 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1294 auto LookupBPI = [&FAM](Function &F) {
1295 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1296 };
1297
1298 auto LookupBFI = [&FAM](Function &F) {
1299 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1300 };
1301
1302 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1303 return PreservedAnalyses::all();
1304
1305 return PreservedAnalyses::none();
1306}
1307
Xinliang David Lid55827f2016-05-07 05:39:12 +00001308bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1309 if (skipModule(M))
1310 return false;
1311
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001312 auto LookupBPI = [this](Function &F) {
1313 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001314 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001315 auto LookupBFI = [this](Function &F) {
1316 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001317 };
1318
Xinliang David Lida195582016-05-10 21:59:52 +00001319 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001320}
Xinliang David Lid289e452017-01-27 19:06:25 +00001321
1322namespace llvm {
1323template <> struct GraphTraits<PGOUseFunc *> {
1324 typedef const BasicBlock *NodeRef;
1325 typedef succ_const_iterator ChildIteratorType;
1326 typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1327
1328 static NodeRef getEntryNode(const PGOUseFunc *G) {
1329 return &G->getFunc().front();
1330 }
1331 static ChildIteratorType child_begin(const NodeRef N) {
1332 return succ_begin(N);
1333 }
1334 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1335 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1336 return nodes_iterator(G->getFunc().begin());
1337 }
1338 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1339 return nodes_iterator(G->getFunc().end());
1340 }
1341};
1342
Xinliang David Li6144a592017-02-03 21:57:51 +00001343static std::string getSimpleNodeName(const BasicBlock *Node) {
1344 if (!Node->getName().empty())
1345 return Node->getName();
1346
1347 std::string SimpleNodeName;
1348 raw_string_ostream OS(SimpleNodeName);
1349 Node->printAsOperand(OS, false);
1350 return OS.str();
1351}
1352
Xinliang David Lid289e452017-01-27 19:06:25 +00001353template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1354 explicit DOTGraphTraits(bool isSimple = false)
1355 : DefaultDOTGraphTraits(isSimple) {}
1356
1357 static std::string getGraphName(const PGOUseFunc *G) {
1358 return G->getFunc().getName();
1359 }
1360
1361 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1362 std::string Result;
1363 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001364
1365 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001366 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001367 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001368 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001369 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001370 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001371 OS << "Unknown\\l";
1372
1373 if (!PGOInstrSelect)
1374 return Result;
1375
1376 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1377 auto *I = &*BI;
1378 if (!isa<SelectInst>(I))
1379 continue;
1380 // Display scaled counts for SELECT instruction:
1381 OS << "SELECT : { T = ";
1382 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001383 bool HasProf = I->extractProfMetadata(TC, FC);
1384 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001385 OS << "Unknown, F = Unknown }\\l";
1386 else
1387 OS << TC << ", F = " << FC << " }\\l";
1388 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001389 return Result;
1390 }
1391};
Rong Xu0a2a1312017-03-09 19:08:55 +00001392} // namespace llvm