blob: b81bb1b495557dbe4498694215eb2f1fd7dbfdc6 [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:
Xinliang David Li9780fc12016-09-20 22:39:47 +0000352 std::vector<Instruction *> IndirectCallSites;
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)
Xinliang David Li4ca17332016-09-18 18:34:07 +0000383 : F(Func), ComdatMembers(ComdatMembers), SIVisitor(Func), FunctionHash(0),
Rong Xu705f7772016-07-25 18:45:37 +0000384 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();
Xinliang David Li9780fc12016-09-20 22:39:47 +0000389 IndirectCallSites = 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 |
Xinliang David Li9780fc12016-09-20 22:39:47 +0000441 (uint64_t)IndirectCallSites.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;
Xinliang David Li9780fc12016-09-20 22:39:47 +0000588 for (auto &I : FuncInfo.IndirectCallSites) {
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()),
601 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
602 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
689 // Annotate the indirect call sites.
690 void annotateIndirectCallSites();
691
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000692 // The hotness of the function from the profile count.
693 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
694
695 // Return the function hotness from the profile.
696 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
697
Rong Xu705f7772016-07-25 18:45:37 +0000698 // Return the function hash.
699 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000700 // Return the profile record for this function;
701 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
702
Xinliang David Li4ca17332016-09-18 18:34:07 +0000703 // Return the auxiliary BB information.
704 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
705 return FuncInfo.getBBInfo(BB);
706 }
707
Rong Xua5b57452016-12-02 19:10:29 +0000708 // Return the auxiliary BB information if available.
709 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
710 return FuncInfo.findBBInfo(BB);
711 }
712
Xinliang David Lid289e452017-01-27 19:06:25 +0000713 Function &getFunc() const { return F; }
714
Rong Xuf430ae42015-12-09 18:08:16 +0000715private:
716 Function &F;
717 Module *M;
718 // This member stores the shared information with class PGOGenFunc.
719 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
720
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000721 // The maximum count value in the profile. This is only used in PGO use
722 // compilation.
723 uint64_t ProgramMaxCount;
724
Rong Xu33308f92016-10-25 21:47:24 +0000725 // Position of counter that remains to be read.
726 uint32_t CountPosition;
727
728 // Total size of the profile count for this function.
729 uint32_t ProfileCountSize;
730
Rong Xu13b01dc2016-02-10 18:24:45 +0000731 // ProfileRecord for this function.
732 InstrProfRecord ProfileRecord;
733
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000734 // Function hotness info derived from profile.
735 FuncFreqAttr FreqAttr;
736
Rong Xuf430ae42015-12-09 18:08:16 +0000737 // Find the Instrumented BB and set the value.
738 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
739
740 // Set the edge counter value for the unknown edge -- there should be only
741 // one unknown edge.
742 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
743
744 // Return FuncName string;
745 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000746
747 // Set the hot/cold inline hints based on the count values.
748 // FIXME: This function should be removed once the functionality in
749 // the inliner is implemented.
750 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
751 if (ProgramMaxCount == 0)
752 return;
753 // Threshold of the hot functions.
754 const BranchProbability HotFunctionThreshold(1, 100);
755 // Threshold of the cold functions.
756 const BranchProbability ColdFunctionThreshold(2, 10000);
757 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
758 FreqAttr = FFA_Hot;
759 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
760 FreqAttr = FFA_Cold;
761 }
Rong Xuf430ae42015-12-09 18:08:16 +0000762};
763
764// Visit all the edges and assign the count value for the instrumented
765// edges and the BB.
766void PGOUseFunc::setInstrumentedCounts(
767 const std::vector<uint64_t> &CountFromProfile) {
768
Xinliang David Lid1197612016-08-01 20:25:06 +0000769 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000770 // Use a worklist as we will update the vector during the iteration.
771 std::vector<PGOUseEdge *> WorkList;
772 for (auto &E : FuncInfo.MST.AllEdges)
773 WorkList.push_back(E.get());
774
775 uint32_t I = 0;
776 for (auto &E : WorkList) {
777 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
778 if (!InstrBB)
779 continue;
780 uint64_t CountValue = CountFromProfile[I++];
781 if (!E->Removed) {
782 getBBInfo(InstrBB).setBBInfoCount(CountValue);
783 E->setEdgeCount(CountValue);
784 continue;
785 }
786
787 // Need to add two new edges.
788 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
789 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
790 // Add new edge of SrcBB->InstrBB.
791 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
792 NewEdge.setEdgeCount(CountValue);
793 // Add new edge of InstrBB->DestBB.
794 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
795 NewEdge1.setEdgeCount(CountValue);
796 NewEdge1.InMST = true;
797 getBBInfo(InstrBB).setBBInfoCount(CountValue);
798 }
Rong Xu33308f92016-10-25 21:47:24 +0000799 ProfileCountSize = CountFromProfile.size();
800 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000801}
802
803// Set the count value for the unknown edge. There should be one and only one
804// unknown edge in Edges vector.
805void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
806 for (auto &E : Edges) {
807 if (E->CountValid)
808 continue;
809 E->setEdgeCount(Value);
810
811 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
812 getBBInfo(E->DestBB).UnknownCountInEdge--;
813 return;
814 }
815 llvm_unreachable("Cannot find the unknown count edge");
816}
817
818// Read the profile from ProfileFileName and assign the value to the
819// instrumented BB and the edges. This function also updates ProgramMaxCount.
820// Return true if the profile are successfully read, and false on errors.
821bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
822 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000823 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000824 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000825 if (Error E = Result.takeError()) {
826 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
827 auto Err = IPE.get();
828 bool SkipWarning = false;
829 if (Err == instrprof_error::unknown_function) {
830 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000831 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000832 } else if (Err == instrprof_error::hash_mismatch ||
833 Err == instrprof_error::malformed) {
834 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +0000835 SkipWarning =
836 NoPGOWarnMismatch ||
837 (NoPGOWarnMismatchComdat &&
838 (F.hasComdat() ||
839 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000840 }
Rong Xuf430ae42015-12-09 18:08:16 +0000841
Vedant Kumar9152fd12016-05-19 03:54:45 +0000842 if (SkipWarning)
843 return;
844
845 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
846 Ctx.diagnose(
847 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
848 });
Rong Xuf430ae42015-12-09 18:08:16 +0000849 return false;
850 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000851 ProfileRecord = std::move(Result.get());
852 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000853
854 NumOfPGOFunc++;
855 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
856 uint64_t ValueSum = 0;
857 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
858 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
859 ValueSum += CountFromProfile[I];
860 }
861
862 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
863
864 getBBInfo(nullptr).UnknownCountOutEdge = 2;
865 getBBInfo(nullptr).UnknownCountInEdge = 2;
866
867 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000868 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000869 return true;
870}
871
872// Populate the counters from instrumented BBs to all BBs.
873// In the end of this operation, all BBs should have a valid count value.
874void PGOUseFunc::populateCounters() {
875 // First set up Count variable for all BBs.
876 for (auto &E : FuncInfo.MST.AllEdges) {
877 if (E->Removed)
878 continue;
879
880 const BasicBlock *SrcBB = E->SrcBB;
881 const BasicBlock *DestBB = E->DestBB;
882 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
883 UseBBInfo &DestInfo = getBBInfo(DestBB);
884 SrcInfo.OutEdges.push_back(E.get());
885 DestInfo.InEdges.push_back(E.get());
886 SrcInfo.UnknownCountOutEdge++;
887 DestInfo.UnknownCountInEdge++;
888
889 if (!E->CountValid)
890 continue;
891 DestInfo.UnknownCountInEdge--;
892 SrcInfo.UnknownCountOutEdge--;
893 }
894
895 bool Changes = true;
896 unsigned NumPasses = 0;
897 while (Changes) {
898 NumPasses++;
899 Changes = false;
900
901 // For efficient traversal, it's better to start from the end as most
902 // of the instrumented edges are at the end.
903 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +0000904 UseBBInfo *Count = findBBInfo(&BB);
905 if (Count == nullptr)
906 continue;
907 if (!Count->CountValid) {
908 if (Count->UnknownCountOutEdge == 0) {
909 Count->CountValue = sumEdgeCount(Count->OutEdges);
910 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000911 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +0000912 } else if (Count->UnknownCountInEdge == 0) {
913 Count->CountValue = sumEdgeCount(Count->InEdges);
914 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000915 Changes = true;
916 }
917 }
Rong Xua5b57452016-12-02 19:10:29 +0000918 if (Count->CountValid) {
919 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000920 uint64_t Total = 0;
921 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
922 // If the one of the successor block can early terminate (no-return),
923 // we can end up with situation where out edge sum count is larger as
924 // the source BB's count is collected by a post-dominated block.
925 if (Count->CountValue > OutSum)
926 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +0000927 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000928 Changes = true;
929 }
Rong Xua5b57452016-12-02 19:10:29 +0000930 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000931 uint64_t Total = 0;
932 uint64_t InSum = sumEdgeCount(Count->InEdges);
933 if (Count->CountValue > InSum)
934 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +0000935 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000936 Changes = true;
937 }
938 }
939 }
940 }
941
942 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000943#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000944 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +0000945 for (auto &BB : F) {
946 auto BI = findBBInfo(&BB);
947 if (BI == nullptr)
948 continue;
949 assert(BI->CountValid && "BB count is not valid");
950 }
Sean Silva8c7e1212016-05-28 04:19:45 +0000951#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000952 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +0000953 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000954 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +0000955 for (auto &BB : F) {
956 auto BI = findBBInfo(&BB);
957 if (BI == nullptr)
958 continue;
959 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
960 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000961 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000962
Rong Xu33308f92016-10-25 21:47:24 +0000963 // Now annotate select instructions
964 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
965 assert(CountPosition == ProfileCountSize);
966
Rong Xuf430ae42015-12-09 18:08:16 +0000967 DEBUG(FuncInfo.dumpInfo("after reading profile."));
968}
969
Xinliang David Li4ca17332016-09-18 18:34:07 +0000970static void setProfMetadata(Module *M, Instruction *TI,
Xinliang David Li63248ab2016-08-19 06:31:45 +0000971 ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) {
Xinliang David Li2c933682016-08-19 05:31:33 +0000972 MDBuilder MDB(M->getContext());
973 assert(MaxCount > 0 && "Bad max count");
974 uint64_t Scale = calculateCountScale(MaxCount);
975 SmallVector<unsigned, 4> Weights;
976 for (const auto &ECI : EdgeCounts)
977 Weights.push_back(scaleBranchCount(ECI, Scale));
978
979 DEBUG(dbgs() << "Weight is: ";
980 for (const auto &W : Weights) { dbgs() << W << " "; }
981 dbgs() << "\n";);
982 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
983}
984
Rong Xuf430ae42015-12-09 18:08:16 +0000985// Assign the scaled count values to the BB with multiple out edges.
986void PGOUseFunc::setBranchWeights() {
987 // Generate MD_prof metadata for every branch instruction.
988 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000989 for (auto &BB : F) {
990 TerminatorInst *TI = BB.getTerminator();
991 if (TI->getNumSuccessors() < 2)
992 continue;
993 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
994 continue;
995 if (getBBInfo(&BB).CountValue == 0)
996 continue;
997
998 // We have a non-zero Branch BB.
999 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1000 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001001 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001002 uint64_t MaxCount = 0;
1003 for (unsigned s = 0; s < Size; s++) {
1004 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1005 const BasicBlock *SrcBB = E->SrcBB;
1006 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001007 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001008 continue;
1009 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1010 uint64_t EdgeCount = E->CountValue;
1011 if (EdgeCount > MaxCount)
1012 MaxCount = EdgeCount;
1013 EdgeCounts[SuccNum] = EdgeCount;
1014 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001015 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001016 }
1017}
Rong Xu13b01dc2016-02-10 18:24:45 +00001018
Xinliang David Li4ca17332016-09-18 18:34:07 +00001019void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1020 Module *M = F.getParent();
1021 IRBuilder<> Builder(&SI);
1022 Type *Int64Ty = Builder.getInt64Ty();
1023 Type *I8PtrTy = Builder.getInt8PtrTy();
1024 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1025 Builder.CreateCall(
1026 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1027 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1028 Builder.getInt64(FuncHash),
1029 Builder.getInt32(TotalNumCtrs), Builder.getInt32(*CurCtrIdx), Step});
1030 ++(*CurCtrIdx);
1031}
1032
1033void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1034 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1035 assert(*CurCtrIdx < CountFromProfile.size() &&
1036 "Out of bound access of counters");
1037 uint64_t SCounts[2];
1038 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1039 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001040 uint64_t TotalCount = 0;
1041 auto BI = UseFunc->findBBInfo(SI.getParent());
1042 if (BI != nullptr)
1043 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001044 // False Count
1045 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1046 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001047 if (MaxCount)
1048 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001049}
1050
1051void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1052 if (!PGOInstrSelect)
1053 return;
1054 // FIXME: do not handle this yet.
1055 if (SI.getCondition()->getType()->isVectorTy())
1056 return;
1057
1058 NSIs++;
1059 switch (Mode) {
1060 case VM_counting:
1061 return;
1062 case VM_instrument:
1063 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001064 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001065 case VM_annotate:
1066 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001067 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001068 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001069
1070 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001071}
1072
Rong Xu13b01dc2016-02-10 18:24:45 +00001073// Traverse all the indirect callsites and annotate the instructions.
1074void PGOUseFunc::annotateIndirectCallSites() {
1075 if (DisableValueProfiling)
1076 return;
1077
Rong Xu8e8fe852016-04-01 16:43:30 +00001078 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001079 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001080
Rong Xu13b01dc2016-02-10 18:24:45 +00001081 unsigned IndirectCallSiteIndex = 0;
Xinliang David Li9780fc12016-09-20 22:39:47 +00001082 auto &IndirectCallSites = FuncInfo.IndirectCallSites;
Rong Xu9e926e82016-02-29 19:16:04 +00001083 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +00001084 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +00001085 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001086 std::string Msg =
1087 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +00001088 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +00001089 auto &Ctx = M->getContext();
1090 Ctx.diagnose(
1091 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1092 return;
1093 }
1094
Rong Xu0eb36032016-04-01 23:16:44 +00001095 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001096 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +00001097 << IndirectCallSiteIndex << " out of " << NumValueSites
1098 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +00001099 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +00001100 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +00001101 IndirectCallSiteIndex++;
1102 }
1103}
Rong Xuf430ae42015-12-09 18:08:16 +00001104} // end anonymous namespace
1105
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001106// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001107// aware this is an ir_level profile so it can set the version flag.
1108static void createIRLevelProfileFlagVariable(Module &M) {
1109 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1110 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001111 auto IRLevelVersionVariable = new GlobalVariable(
1112 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1113 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001114 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001115 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1116 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001117 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001118 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001119 else
Rong Xu9e926e82016-02-29 19:16:04 +00001120 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001121 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001122}
1123
Rong Xu705f7772016-07-25 18:45:37 +00001124// Collect the set of members for each Comdat in module M and store
1125// in ComdatMembers.
1126static void collectComdatMembers(
1127 Module &M,
1128 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1129 if (!DoComdatRenaming)
1130 return;
1131 for (Function &F : M)
1132 if (Comdat *C = F.getComdat())
1133 ComdatMembers.insert(std::make_pair(C, &F));
1134 for (GlobalVariable &GV : M.globals())
1135 if (Comdat *C = GV.getComdat())
1136 ComdatMembers.insert(std::make_pair(C, &GV));
1137 for (GlobalAlias &GA : M.aliases())
1138 if (Comdat *C = GA.getComdat())
1139 ComdatMembers.insert(std::make_pair(C, &GA));
1140}
1141
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001142static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001143 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1144 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001145 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001146 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1147 collectComdatMembers(M, ComdatMembers);
1148
Rong Xuf430ae42015-12-09 18:08:16 +00001149 for (auto &F : M) {
1150 if (F.isDeclaration())
1151 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001152 auto *BPI = LookupBPI(F);
1153 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001154 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001155 }
1156 return true;
1157}
1158
Xinliang David Li8aebf442016-05-06 05:49:19 +00001159bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001160 if (skipModule(M))
1161 return false;
1162
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001163 auto LookupBPI = [this](Function &F) {
1164 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001165 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001166 auto LookupBFI = [this](Function &F) {
1167 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001168 };
1169 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1170}
1171
Xinliang David Li8aebf442016-05-06 05:49:19 +00001172PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001173 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001174
1175 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001176 auto LookupBPI = [&FAM](Function &F) {
1177 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001178 };
1179
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001180 auto LookupBFI = [&FAM](Function &F) {
1181 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001182 };
1183
1184 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1185 return PreservedAnalyses::all();
1186
1187 return PreservedAnalyses::none();
1188}
1189
Xinliang David Lida195582016-05-10 21:59:52 +00001190static bool annotateAllFunctions(
1191 Module &M, StringRef ProfileFileName,
1192 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001193 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001194 DEBUG(dbgs() << "Read in profile counters: ");
1195 auto &Ctx = M.getContext();
1196 // Read the counter array from file.
1197 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001198 if (Error E = ReaderOrErr.takeError()) {
1199 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1200 Ctx.diagnose(
1201 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1202 });
Rong Xuf430ae42015-12-09 18:08:16 +00001203 return false;
1204 }
1205
Xinliang David Lida195582016-05-10 21:59:52 +00001206 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1207 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001208 if (!PGOReader) {
1209 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001210 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001211 return false;
1212 }
Rong Xu33c76c02016-02-10 17:18:30 +00001213 // TODO: might need to change the warning once the clang option is finalized.
1214 if (!PGOReader->isIRLevelProfile()) {
1215 Ctx.diagnose(DiagnosticInfoPGOProfile(
1216 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1217 return false;
1218 }
1219
Rong Xu705f7772016-07-25 18:45:37 +00001220 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1221 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001222 std::vector<Function *> HotFunctions;
1223 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001224 for (auto &F : M) {
1225 if (F.isDeclaration())
1226 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001227 auto *BPI = LookupBPI(F);
1228 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001229 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001230 if (!Func.readCounters(PGOReader.get()))
1231 continue;
1232 Func.populateCounters();
1233 Func.setBranchWeights();
1234 Func.annotateIndirectCallSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001235 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1236 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001237 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001238 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1239 HotFunctions.push_back(&F);
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001240 if (PGOViewCounts && (ViewBlockFreqFuncName.empty() ||
1241 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001242 LoopInfo LI{DominatorTree(F)};
1243 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1244 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1245 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1246 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1247
1248 NewBFI->view();
1249 }
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001250 if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() ||
1251 F.getName().equals(ViewBlockFreqFuncName))) {
1252 if (ViewBlockFreqFuncName.empty())
Xinliang David Lid289e452017-01-27 19:06:25 +00001253 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1254 else
1255 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1256 }
Rong Xuf430ae42015-12-09 18:08:16 +00001257 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001258 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001259 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001260 // We have to apply these attributes at the end because their presence
1261 // can affect the BranchProbabilityInfo of any callers, resulting in an
1262 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001263 for (auto &F : HotFunctions) {
1264 F->addFnAttr(llvm::Attribute::InlineHint);
1265 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1266 << "\n");
1267 }
1268 for (auto &F : ColdFunctions) {
1269 F->addFnAttr(llvm::Attribute::Cold);
1270 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1271 }
Rong Xuf430ae42015-12-09 18:08:16 +00001272 return true;
1273}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001274
Xinliang David Lida195582016-05-10 21:59:52 +00001275PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001276 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001277 if (!PGOTestProfileFile.empty())
1278 ProfileFileName = PGOTestProfileFile;
1279}
1280
1281PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001282 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001283
1284 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1285 auto LookupBPI = [&FAM](Function &F) {
1286 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1287 };
1288
1289 auto LookupBFI = [&FAM](Function &F) {
1290 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1291 };
1292
1293 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1294 return PreservedAnalyses::all();
1295
1296 return PreservedAnalyses::none();
1297}
1298
Xinliang David Lid55827f2016-05-07 05:39:12 +00001299bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1300 if (skipModule(M))
1301 return false;
1302
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001303 auto LookupBPI = [this](Function &F) {
1304 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001305 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001306 auto LookupBFI = [this](Function &F) {
1307 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001308 };
1309
Xinliang David Lida195582016-05-10 21:59:52 +00001310 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001311}
Xinliang David Lid289e452017-01-27 19:06:25 +00001312
1313namespace llvm {
1314template <> struct GraphTraits<PGOUseFunc *> {
1315 typedef const BasicBlock *NodeRef;
1316 typedef succ_const_iterator ChildIteratorType;
1317 typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1318
1319 static NodeRef getEntryNode(const PGOUseFunc *G) {
1320 return &G->getFunc().front();
1321 }
1322 static ChildIteratorType child_begin(const NodeRef N) {
1323 return succ_begin(N);
1324 }
1325 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1326 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1327 return nodes_iterator(G->getFunc().begin());
1328 }
1329 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1330 return nodes_iterator(G->getFunc().end());
1331 }
1332};
1333
Xinliang David Li6144a592017-02-03 21:57:51 +00001334static std::string getSimpleNodeName(const BasicBlock *Node) {
1335 if (!Node->getName().empty())
1336 return Node->getName();
1337
1338 std::string SimpleNodeName;
1339 raw_string_ostream OS(SimpleNodeName);
1340 Node->printAsOperand(OS, false);
1341 return OS.str();
1342}
1343
Xinliang David Lid289e452017-01-27 19:06:25 +00001344template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1345 explicit DOTGraphTraits(bool isSimple = false)
1346 : DefaultDOTGraphTraits(isSimple) {}
1347
1348 static std::string getGraphName(const PGOUseFunc *G) {
1349 return G->getFunc().getName();
1350 }
1351
1352 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1353 std::string Result;
1354 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001355
1356 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001357 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001358 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001359 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001360 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001361 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001362 OS << "Unknown\\l";
1363
1364 if (!PGOInstrSelect)
1365 return Result;
1366
1367 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1368 auto *I = &*BI;
1369 if (!isa<SelectInst>(I))
1370 continue;
1371 // Display scaled counts for SELECT instruction:
1372 OS << "SELECT : { T = ";
1373 uint64_t TC, FC;
1374 bool hasProf = I->extractProfMetadata(TC, FC);
1375 if (!hasProf)
1376 OS << "Unknown, F = Unknown }\\l";
1377 else
1378 OS << TC << ", F = " << FC << " }\\l";
1379 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001380 return Result;
1381 }
1382};
1383}