blob: ffebd42795d7a409d08a457cda39099f71012de2 [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"
Rong Xued9fec72016-01-21 18:11:44 +000061#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000062#include "llvm/IR/DiagnosticInfo.h"
Rong Xu705f7772016-07-25 18:45:37 +000063#include "llvm/IR/GlobalValue.h"
Rong Xuf430ae42015-12-09 18:08:16 +000064#include "llvm/IR/IRBuilder.h"
65#include "llvm/IR/InstIterator.h"
66#include "llvm/IR/Instructions.h"
67#include "llvm/IR/IntrinsicInst.h"
68#include "llvm/IR/MDBuilder.h"
69#include "llvm/IR/Module.h"
70#include "llvm/Pass.h"
71#include "llvm/ProfileData/InstrProfReader.h"
Easwaran Raman5fe04a12016-05-26 22:57:11 +000072#include "llvm/ProfileData/ProfileCommon.h"
Rong Xuf430ae42015-12-09 18:08:16 +000073#include "llvm/Support/BranchProbability.h"
74#include "llvm/Support/Debug.h"
75#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000076#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000077#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000078#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000079#include <string>
Rong Xu705f7772016-07-25 18:45:37 +000080#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +000081#include <utility>
82#include <vector>
83
84using namespace llvm;
85
86#define DEBUG_TYPE "pgo-instrumentation"
87
88STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +000089STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +000090STATISTIC(NumOfPGOEdge, "Number of edges.");
91STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
92STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
93STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
94STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
95STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000096STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000097
98// Command line option to specify the file to read profile from. This is
99// mainly used for testing.
100static cl::opt<std::string>
101 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
102 cl::value_desc("filename"),
103 cl::desc("Specify the path of profile data file. This is"
104 "mainly for test purpose."));
105
Rong Xuecdc98f2016-03-04 22:08:44 +0000106// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000107// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000108static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
109 cl::Hidden,
110 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000111
Rong Xuecdc98f2016-03-04 22:08:44 +0000112// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000113// the metadata for a single indirect call callsite.
114static cl::opt<unsigned> MaxNumAnnotations(
115 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
116 cl::desc("Max number of annotations for a single indirect "
117 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000118
Rong Xu705f7772016-07-25 18:45:37 +0000119// Command line option to control appending FunctionHash to the name of a COMDAT
120// function. This is to avoid the hash mismatch caused by the preinliner.
121static cl::opt<bool> DoComdatRenaming(
Rong Xuef1adad2017-01-10 19:30:20 +0000122 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000123 cl::desc("Append function hash to the name of COMDAT function to avoid "
124 "function hash mismatch due to the preinliner"));
125
Rong Xu0698de92016-05-13 17:26:06 +0000126// Command line option to enable/disable the warning about missing profile
127// information.
Xinliang David Li76a01082016-08-11 05:09:30 +0000128static cl::opt<bool> PGOWarnMissing("pgo-warn-missing-function",
129 cl::init(false),
130 cl::Hidden);
Rong Xu0698de92016-05-13 17:26:06 +0000131
132// Command line option to enable/disable the warning about a hash mismatch in
133// the profile data.
134static cl::opt<bool> NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false),
135 cl::Hidden);
136
Xinliang David Li4ca17332016-09-18 18:34:07 +0000137// Command line option to enable/disable select instruction instrumentation.
138static cl::opt<bool> PGOInstrSelect("pgo-instr-select", cl::init(true),
139 cl::Hidden);
Rong Xuf430ae42015-12-09 18:08:16 +0000140namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000141
142/// The select instruction visitor plays three roles specified
143/// by the mode. In \c VM_counting mode, it simply counts the number of
144/// select instructions. In \c VM_instrument mode, it inserts code to count
145/// the number times TrueValue of select is taken. In \c VM_annotate mode,
146/// it reads the profile data and annotate the select instruction with metadata.
147enum VisitMode { VM_counting, VM_instrument, VM_annotate };
148class PGOUseFunc;
149
150/// Instruction Visitor class to visit select instructions.
151struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
152 Function &F;
153 unsigned NSIs = 0; // Number of select instructions instrumented.
154 VisitMode Mode = VM_counting; // Visiting mode.
155 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
156 unsigned TotalNumCtrs = 0; // Total number of counters
157 GlobalVariable *FuncNameVar = nullptr;
158 uint64_t FuncHash = 0;
159 PGOUseFunc *UseFunc = nullptr;
160
161 SelectInstVisitor(Function &Func) : F(Func) {}
162
163 void countSelects(Function &Func) {
164 Mode = VM_counting;
165 visit(Func);
166 }
167 // Visit the IR stream and instrument all select instructions. \p
168 // Ind is a pointer to the counter index variable; \p TotalNC
169 // is the total number of counters; \p FNV is the pointer to the
170 // PGO function name var; \p FHash is the function hash.
171 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
172 GlobalVariable *FNV, uint64_t FHash) {
173 Mode = VM_instrument;
174 CurCtrIdx = Ind;
175 TotalNumCtrs = TotalNC;
176 FuncHash = FHash;
177 FuncNameVar = FNV;
178 visit(Func);
179 }
180
181 // Visit the IR stream and annotate all select instructions.
182 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
183 Mode = VM_annotate;
184 UseFunc = UF;
185 CurCtrIdx = Ind;
186 visit(Func);
187 }
188
189 void instrumentOneSelectInst(SelectInst &SI);
190 void annotateOneSelectInst(SelectInst &SI);
191 // Visit \p SI instruction and perform tasks according to visit mode.
192 void visitSelectInst(SelectInst &SI);
193 unsigned getNumOfSelectInsts() const { return NSIs; }
194};
195
Xinliang David Li8aebf442016-05-06 05:49:19 +0000196class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000197public:
198 static char ID;
199
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000200 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000201 initializePGOInstrumentationGenLegacyPassPass(
202 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000203 }
204
Mehdi Amini117296c2016-10-01 02:56:57 +0000205 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000206
207private:
208 bool runOnModule(Module &M) override;
209
210 void getAnalysisUsage(AnalysisUsage &AU) const override {
211 AU.addRequired<BlockFrequencyInfoWrapperPass>();
212 }
213};
214
Xinliang David Lid55827f2016-05-07 05:39:12 +0000215class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000216public:
217 static char ID;
218
219 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000220 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000221 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000222 if (!PGOTestProfileFile.empty())
223 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000224 initializePGOInstrumentationUseLegacyPassPass(
225 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000226 }
227
Mehdi Amini117296c2016-10-01 02:56:57 +0000228 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000229
230private:
231 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000232
Xinliang David Lida195582016-05-10 21:59:52 +0000233 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000234 void getAnalysisUsage(AnalysisUsage &AU) const override {
235 AU.addRequired<BlockFrequencyInfoWrapperPass>();
236 }
237};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000238
Rong Xuf430ae42015-12-09 18:08:16 +0000239} // end anonymous namespace
240
Xinliang David Li8aebf442016-05-06 05:49:19 +0000241char PGOInstrumentationGenLegacyPass::ID = 0;
242INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000243 "PGO instrumentation.", false, false)
244INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
245INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000246INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000247 "PGO instrumentation.", false, false)
248
Xinliang David Li8aebf442016-05-06 05:49:19 +0000249ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
250 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000251}
252
Xinliang David Lid55827f2016-05-07 05:39:12 +0000253char PGOInstrumentationUseLegacyPass::ID = 0;
254INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000255 "Read PGO instrumentation profile.", false, false)
256INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
257INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000258INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000259 "Read PGO instrumentation profile.", false, false)
260
Xinliang David Lid55827f2016-05-07 05:39:12 +0000261ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
262 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000263}
264
265namespace {
266/// \brief An MST based instrumentation for PGO
267///
268/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
269/// in the function level.
270struct PGOEdge {
271 // This class implements the CFG edges. Note the CFG can be a multi-graph.
272 // So there might be multiple edges with same SrcBB and DestBB.
273 const BasicBlock *SrcBB;
274 const BasicBlock *DestBB;
275 uint64_t Weight;
276 bool InMST;
277 bool Removed;
278 bool IsCritical;
279 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
280 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
281 IsCritical(false) {}
282 // Return the information string of an edge.
283 const std::string infoString() const {
284 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
285 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
286 }
287};
288
289// This class stores the auxiliary information for each BB.
290struct BBInfo {
291 BBInfo *Group;
292 uint32_t Index;
293 uint32_t Rank;
294
295 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
296
297 // Return the information string of this object.
298 const std::string infoString() const {
299 return (Twine("Index=") + Twine(Index)).str();
300 }
301};
302
303// This class implements the CFG edges. Note the CFG can be a multi-graph.
304template <class Edge, class BBInfo> class FuncPGOInstrumentation {
305private:
306 Function &F;
307 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000308 void renameComdatFunction();
309 // A map that stores the Comdat group in function F.
310 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000311
312public:
Xinliang David Li9780fc12016-09-20 22:39:47 +0000313 std::vector<Instruction *> IndirectCallSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000314 SelectInstVisitor SIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000315 std::string FuncName;
316 GlobalVariable *FuncNameVar;
317 // CFG hash value for this function.
318 uint64_t FunctionHash;
319
320 // The Minimum Spanning Tree of function CFG.
321 CFGMST<Edge, BBInfo> MST;
322
323 // Give an edge, find the BB that will be instrumented.
324 // Return nullptr if there is no BB to be instrumented.
325 BasicBlock *getInstrBB(Edge *E);
326
327 // Return the auxiliary BB information.
328 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
329
Rong Xua5b57452016-12-02 19:10:29 +0000330 // Return the auxiliary BB information if available.
331 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
332
Rong Xuf430ae42015-12-09 18:08:16 +0000333 // Dump edges and BB information.
334 void dumpInfo(std::string Str = "") const {
335 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000336 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000337 }
338
Rong Xu705f7772016-07-25 18:45:37 +0000339 FuncPGOInstrumentation(
340 Function &Func,
341 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
342 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
343 BlockFrequencyInfo *BFI = nullptr)
Xinliang David Li4ca17332016-09-18 18:34:07 +0000344 : F(Func), ComdatMembers(ComdatMembers), SIVisitor(Func), FunctionHash(0),
Rong Xu705f7772016-07-25 18:45:37 +0000345 MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000346
347 // This should be done before CFG hash computation.
348 SIVisitor.countSelects(Func);
349 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Xinliang David Li9780fc12016-09-20 22:39:47 +0000350 IndirectCallSites = findIndirectCallSites(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000351
Rong Xuf430ae42015-12-09 18:08:16 +0000352 FuncName = getPGOFuncName(F);
353 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000354 if (ComdatMembers.size())
355 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000356 DEBUG(dumpInfo("after CFGMST"));
357
358 NumOfPGOBB += MST.BBInfos.size();
359 for (auto &E : MST.AllEdges) {
360 if (E->Removed)
361 continue;
362 NumOfPGOEdge++;
363 if (!E->InMST)
364 NumOfPGOInstrument++;
365 }
366
367 if (CreateGlobalVar)
368 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000369 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000370
371 // Return the number of profile counters needed for the function.
372 unsigned getNumCounters() {
373 unsigned NumCounters = 0;
374 for (auto &E : this->MST.AllEdges) {
375 if (!E->InMST && !E->Removed)
376 NumCounters++;
377 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000378 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000379 }
Rong Xuf430ae42015-12-09 18:08:16 +0000380};
381
382// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
383// value of each BB in the CFG. The higher 32 bits record the number of edges.
384template <class Edge, class BBInfo>
385void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
386 std::vector<char> Indexes;
387 JamCRC JC;
388 for (auto &BB : F) {
389 const TerminatorInst *TI = BB.getTerminator();
390 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
391 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000392 auto BI = findBBInfo(Succ);
393 if (BI == nullptr)
394 continue;
395 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000396 for (int J = 0; J < 4; J++)
397 Indexes.push_back((char)(Index >> (J * 8)));
398 }
399 }
400 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000401 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Xinliang David Li9780fc12016-09-20 22:39:47 +0000402 (uint64_t)IndirectCallSites.size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000403 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
404}
405
406// Check if we can safely rename this Comdat function.
407static bool canRenameComdat(
408 Function &F,
409 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xuef1adad2017-01-10 19:30:20 +0000410 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000411 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000412
413 // FIXME: Current only handle those Comdat groups that only containing one
414 // function and function aliases.
415 // (1) For a Comdat group containing multiple functions, we need to have a
416 // unique postfix based on the hashes for each function. There is a
417 // non-trivial code refactoring to do this efficiently.
418 // (2) Variables can not be renamed, so we can not rename Comdat function in a
419 // group including global vars.
420 Comdat *C = F.getComdat();
421 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
422 if (dyn_cast<GlobalAlias>(CM.second))
423 continue;
424 Function *FM = dyn_cast<Function>(CM.second);
425 if (FM != &F)
426 return false;
427 }
428 return true;
429}
430
431// Append the CFGHash to the Comdat function name.
432template <class Edge, class BBInfo>
433void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
434 if (!canRenameComdat(F, ComdatMembers))
435 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000436 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000437 std::string NewFuncName =
438 Twine(F.getName() + "." + Twine(FunctionHash)).str();
439 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000440 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000441 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
442 Comdat *NewComdat;
443 Module *M = F.getParent();
444 // For AvailableExternallyLinkage functions, change the linkage to
445 // LinkOnceODR and put them into comdat. This is because after renaming, there
446 // is no backup external copy available for the function.
447 if (!F.hasComdat()) {
448 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
449 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
450 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
451 F.setComdat(NewComdat);
452 return;
453 }
454
455 // This function belongs to a single function Comdat group.
456 Comdat *OrigComdat = F.getComdat();
457 std::string NewComdatName =
458 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
459 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
460 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
461
462 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
463 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
464 // For aliases, change the name directly.
465 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000466 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000467 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000468 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000469 continue;
470 }
471 // Must be a function.
472 Function *CF = dyn_cast<Function>(CM.second);
473 assert(CF);
474 CF->setComdat(NewComdat);
475 }
Rong Xuf430ae42015-12-09 18:08:16 +0000476}
477
478// Given a CFG E to be instrumented, find which BB to place the instrumented
479// code. The function will split the critical edge if necessary.
480template <class Edge, class BBInfo>
481BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
482 if (E->InMST || E->Removed)
483 return nullptr;
484
485 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
486 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
487 // For a fake edge, instrument the real BB.
488 if (SrcBB == nullptr)
489 return DestBB;
490 if (DestBB == nullptr)
491 return SrcBB;
492
493 // Instrument the SrcBB if it has a single successor,
494 // otherwise, the DestBB if this is not a critical edge.
495 TerminatorInst *TI = SrcBB->getTerminator();
496 if (TI->getNumSuccessors() <= 1)
497 return SrcBB;
498 if (!E->IsCritical)
499 return DestBB;
500
501 // For a critical edge, we have to split. Instrument the newly
502 // created BB.
503 NumOfPGOSplit++;
504 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
505 << getBBInfo(DestBB).Index << "\n");
506 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
507 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
508 assert(InstrBB && "Critical edge is not split");
509
510 E->Removed = true;
511 return InstrBB;
512}
513
Rong Xued9fec72016-01-21 18:11:44 +0000514// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000515// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000516static void instrumentOneFunc(
517 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
518 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000519 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
520 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000521 unsigned NumCounters = FuncInfo.getNumCounters();
522
Rong Xuf430ae42015-12-09 18:08:16 +0000523 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000524 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000525 for (auto &E : FuncInfo.MST.AllEdges) {
526 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
527 if (!InstrBB)
528 continue;
529
530 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
531 assert(Builder.GetInsertPoint() != InstrBB->end() &&
532 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000533 Builder.CreateCall(
534 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
535 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
536 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
537 Builder.getInt32(I++)});
538 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000539
540 // Now instrument select instructions:
541 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
542 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000543 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000544
545 if (DisableValueProfiling)
546 return;
547
548 unsigned NumIndirectCallSites = 0;
Xinliang David Li9780fc12016-09-20 22:39:47 +0000549 for (auto &I : FuncInfo.IndirectCallSites) {
Rong Xued9fec72016-01-21 18:11:44 +0000550 CallSite CS(I);
551 Value *Callee = CS.getCalledValue();
552 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
553 << NumIndirectCallSites << "\n");
554 IRBuilder<> Builder(I);
555 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
556 "Cannot get the Instrumentation point");
557 Builder.CreateCall(
558 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
559 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
560 Builder.getInt64(FuncInfo.FunctionHash),
561 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
562 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
563 Builder.getInt32(NumIndirectCallSites++)});
564 }
565 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000566}
567
568// This class represents a CFG edge in profile use compilation.
569struct PGOUseEdge : public PGOEdge {
570 bool CountValid;
571 uint64_t CountValue;
572 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
573 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
574
575 // Set edge count value
576 void setEdgeCount(uint64_t Value) {
577 CountValue = Value;
578 CountValid = true;
579 }
580
581 // Return the information string for this object.
582 const std::string infoString() const {
583 if (!CountValid)
584 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000585 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
586 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000587 }
588};
589
590typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
591
592// This class stores the auxiliary information for each BB.
593struct UseBBInfo : public BBInfo {
594 uint64_t CountValue;
595 bool CountValid;
596 int32_t UnknownCountInEdge;
597 int32_t UnknownCountOutEdge;
598 DirectEdges InEdges;
599 DirectEdges OutEdges;
600 UseBBInfo(unsigned IX)
601 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
602 UnknownCountOutEdge(0) {}
603 UseBBInfo(unsigned IX, uint64_t C)
604 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
605 UnknownCountOutEdge(0) {}
606
607 // Set the profile count value for this BB.
608 void setBBInfoCount(uint64_t Value) {
609 CountValue = Value;
610 CountValid = true;
611 }
612
613 // Return the information string of this object.
614 const std::string infoString() const {
615 if (!CountValid)
616 return BBInfo::infoString();
617 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
618 }
619};
620
621// Sum up the count values for all the edges.
622static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
623 uint64_t Total = 0;
624 for (auto &E : Edges) {
625 if (E->Removed)
626 continue;
627 Total += E->CountValue;
628 }
629 return Total;
630}
631
632class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000633public:
Rong Xu705f7772016-07-25 18:45:37 +0000634 PGOUseFunc(Function &Func, Module *Modu,
635 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
636 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000637 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000638 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Rong Xu33308f92016-10-25 21:47:24 +0000639 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000640
641 // Read counts for the instrumented BB from profile.
642 bool readCounters(IndexedInstrProfReader *PGOReader);
643
644 // Populate the counts for all BBs.
645 void populateCounters();
646
647 // Set the branch weights based on the count values.
648 void setBranchWeights();
649
650 // Annotate the indirect call sites.
651 void annotateIndirectCallSites();
652
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000653 // The hotness of the function from the profile count.
654 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
655
656 // Return the function hotness from the profile.
657 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
658
Rong Xu705f7772016-07-25 18:45:37 +0000659 // Return the function hash.
660 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000661 // Return the profile record for this function;
662 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
663
Xinliang David Li4ca17332016-09-18 18:34:07 +0000664 // Return the auxiliary BB information.
665 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
666 return FuncInfo.getBBInfo(BB);
667 }
668
Rong Xua5b57452016-12-02 19:10:29 +0000669 // Return the auxiliary BB information if available.
670 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
671 return FuncInfo.findBBInfo(BB);
672 }
673
Rong Xuf430ae42015-12-09 18:08:16 +0000674private:
675 Function &F;
676 Module *M;
677 // This member stores the shared information with class PGOGenFunc.
678 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
679
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000680 // The maximum count value in the profile. This is only used in PGO use
681 // compilation.
682 uint64_t ProgramMaxCount;
683
Rong Xu33308f92016-10-25 21:47:24 +0000684 // Position of counter that remains to be read.
685 uint32_t CountPosition;
686
687 // Total size of the profile count for this function.
688 uint32_t ProfileCountSize;
689
Rong Xu13b01dc2016-02-10 18:24:45 +0000690 // ProfileRecord for this function.
691 InstrProfRecord ProfileRecord;
692
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000693 // Function hotness info derived from profile.
694 FuncFreqAttr FreqAttr;
695
Rong Xuf430ae42015-12-09 18:08:16 +0000696 // Find the Instrumented BB and set the value.
697 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
698
699 // Set the edge counter value for the unknown edge -- there should be only
700 // one unknown edge.
701 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
702
703 // Return FuncName string;
704 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000705
706 // Set the hot/cold inline hints based on the count values.
707 // FIXME: This function should be removed once the functionality in
708 // the inliner is implemented.
709 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
710 if (ProgramMaxCount == 0)
711 return;
712 // Threshold of the hot functions.
713 const BranchProbability HotFunctionThreshold(1, 100);
714 // Threshold of the cold functions.
715 const BranchProbability ColdFunctionThreshold(2, 10000);
716 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
717 FreqAttr = FFA_Hot;
718 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
719 FreqAttr = FFA_Cold;
720 }
Rong Xuf430ae42015-12-09 18:08:16 +0000721};
722
723// Visit all the edges and assign the count value for the instrumented
724// edges and the BB.
725void PGOUseFunc::setInstrumentedCounts(
726 const std::vector<uint64_t> &CountFromProfile) {
727
Xinliang David Lid1197612016-08-01 20:25:06 +0000728 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000729 // Use a worklist as we will update the vector during the iteration.
730 std::vector<PGOUseEdge *> WorkList;
731 for (auto &E : FuncInfo.MST.AllEdges)
732 WorkList.push_back(E.get());
733
734 uint32_t I = 0;
735 for (auto &E : WorkList) {
736 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
737 if (!InstrBB)
738 continue;
739 uint64_t CountValue = CountFromProfile[I++];
740 if (!E->Removed) {
741 getBBInfo(InstrBB).setBBInfoCount(CountValue);
742 E->setEdgeCount(CountValue);
743 continue;
744 }
745
746 // Need to add two new edges.
747 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
748 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
749 // Add new edge of SrcBB->InstrBB.
750 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
751 NewEdge.setEdgeCount(CountValue);
752 // Add new edge of InstrBB->DestBB.
753 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
754 NewEdge1.setEdgeCount(CountValue);
755 NewEdge1.InMST = true;
756 getBBInfo(InstrBB).setBBInfoCount(CountValue);
757 }
Rong Xu33308f92016-10-25 21:47:24 +0000758 ProfileCountSize = CountFromProfile.size();
759 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000760}
761
762// Set the count value for the unknown edge. There should be one and only one
763// unknown edge in Edges vector.
764void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
765 for (auto &E : Edges) {
766 if (E->CountValid)
767 continue;
768 E->setEdgeCount(Value);
769
770 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
771 getBBInfo(E->DestBB).UnknownCountInEdge--;
772 return;
773 }
774 llvm_unreachable("Cannot find the unknown count edge");
775}
776
777// Read the profile from ProfileFileName and assign the value to the
778// instrumented BB and the edges. This function also updates ProgramMaxCount.
779// Return true if the profile are successfully read, and false on errors.
780bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
781 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000782 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000783 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000784 if (Error E = Result.takeError()) {
785 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
786 auto Err = IPE.get();
787 bool SkipWarning = false;
788 if (Err == instrprof_error::unknown_function) {
789 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000790 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000791 } else if (Err == instrprof_error::hash_mismatch ||
792 Err == instrprof_error::malformed) {
793 NumOfPGOMismatch++;
794 SkipWarning = NoPGOWarnMismatch;
795 }
Rong Xuf430ae42015-12-09 18:08:16 +0000796
Vedant Kumar9152fd12016-05-19 03:54:45 +0000797 if (SkipWarning)
798 return;
799
800 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
801 Ctx.diagnose(
802 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
803 });
Rong Xuf430ae42015-12-09 18:08:16 +0000804 return false;
805 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000806 ProfileRecord = std::move(Result.get());
807 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000808
809 NumOfPGOFunc++;
810 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
811 uint64_t ValueSum = 0;
812 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
813 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
814 ValueSum += CountFromProfile[I];
815 }
816
817 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
818
819 getBBInfo(nullptr).UnknownCountOutEdge = 2;
820 getBBInfo(nullptr).UnknownCountInEdge = 2;
821
822 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000823 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000824 return true;
825}
826
827// Populate the counters from instrumented BBs to all BBs.
828// In the end of this operation, all BBs should have a valid count value.
829void PGOUseFunc::populateCounters() {
830 // First set up Count variable for all BBs.
831 for (auto &E : FuncInfo.MST.AllEdges) {
832 if (E->Removed)
833 continue;
834
835 const BasicBlock *SrcBB = E->SrcBB;
836 const BasicBlock *DestBB = E->DestBB;
837 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
838 UseBBInfo &DestInfo = getBBInfo(DestBB);
839 SrcInfo.OutEdges.push_back(E.get());
840 DestInfo.InEdges.push_back(E.get());
841 SrcInfo.UnknownCountOutEdge++;
842 DestInfo.UnknownCountInEdge++;
843
844 if (!E->CountValid)
845 continue;
846 DestInfo.UnknownCountInEdge--;
847 SrcInfo.UnknownCountOutEdge--;
848 }
849
850 bool Changes = true;
851 unsigned NumPasses = 0;
852 while (Changes) {
853 NumPasses++;
854 Changes = false;
855
856 // For efficient traversal, it's better to start from the end as most
857 // of the instrumented edges are at the end.
858 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +0000859 UseBBInfo *Count = findBBInfo(&BB);
860 if (Count == nullptr)
861 continue;
862 if (!Count->CountValid) {
863 if (Count->UnknownCountOutEdge == 0) {
864 Count->CountValue = sumEdgeCount(Count->OutEdges);
865 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000866 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +0000867 } else if (Count->UnknownCountInEdge == 0) {
868 Count->CountValue = sumEdgeCount(Count->InEdges);
869 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +0000870 Changes = true;
871 }
872 }
Rong Xua5b57452016-12-02 19:10:29 +0000873 if (Count->CountValid) {
874 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000875 uint64_t Total = 0;
876 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
877 // If the one of the successor block can early terminate (no-return),
878 // we can end up with situation where out edge sum count is larger as
879 // the source BB's count is collected by a post-dominated block.
880 if (Count->CountValue > OutSum)
881 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +0000882 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000883 Changes = true;
884 }
Rong Xua5b57452016-12-02 19:10:29 +0000885 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +0000886 uint64_t Total = 0;
887 uint64_t InSum = sumEdgeCount(Count->InEdges);
888 if (Count->CountValue > InSum)
889 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +0000890 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +0000891 Changes = true;
892 }
893 }
894 }
895 }
896
897 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000898#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000899 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +0000900 for (auto &BB : F) {
901 auto BI = findBBInfo(&BB);
902 if (BI == nullptr)
903 continue;
904 assert(BI->CountValid && "BB count is not valid");
905 }
Sean Silva8c7e1212016-05-28 04:19:45 +0000906#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000907 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +0000908 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000909 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +0000910 for (auto &BB : F) {
911 auto BI = findBBInfo(&BB);
912 if (BI == nullptr)
913 continue;
914 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
915 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000916 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000917
Rong Xu33308f92016-10-25 21:47:24 +0000918 // Now annotate select instructions
919 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
920 assert(CountPosition == ProfileCountSize);
921
Rong Xuf430ae42015-12-09 18:08:16 +0000922 DEBUG(FuncInfo.dumpInfo("after reading profile."));
923}
924
Xinliang David Li4ca17332016-09-18 18:34:07 +0000925static void setProfMetadata(Module *M, Instruction *TI,
Xinliang David Li63248ab2016-08-19 06:31:45 +0000926 ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) {
Xinliang David Li2c933682016-08-19 05:31:33 +0000927 MDBuilder MDB(M->getContext());
928 assert(MaxCount > 0 && "Bad max count");
929 uint64_t Scale = calculateCountScale(MaxCount);
930 SmallVector<unsigned, 4> Weights;
931 for (const auto &ECI : EdgeCounts)
932 Weights.push_back(scaleBranchCount(ECI, Scale));
933
934 DEBUG(dbgs() << "Weight is: ";
935 for (const auto &W : Weights) { dbgs() << W << " "; }
936 dbgs() << "\n";);
937 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
938}
939
Rong Xuf430ae42015-12-09 18:08:16 +0000940// Assign the scaled count values to the BB with multiple out edges.
941void PGOUseFunc::setBranchWeights() {
942 // Generate MD_prof metadata for every branch instruction.
943 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000944 for (auto &BB : F) {
945 TerminatorInst *TI = BB.getTerminator();
946 if (TI->getNumSuccessors() < 2)
947 continue;
948 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
949 continue;
950 if (getBBInfo(&BB).CountValue == 0)
951 continue;
952
953 // We have a non-zero Branch BB.
954 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
955 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +0000956 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +0000957 uint64_t MaxCount = 0;
958 for (unsigned s = 0; s < Size; s++) {
959 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
960 const BasicBlock *SrcBB = E->SrcBB;
961 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000962 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000963 continue;
964 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
965 uint64_t EdgeCount = E->CountValue;
966 if (EdgeCount > MaxCount)
967 MaxCount = EdgeCount;
968 EdgeCounts[SuccNum] = EdgeCount;
969 }
Xinliang David Li2c933682016-08-19 05:31:33 +0000970 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000971 }
972}
Rong Xu13b01dc2016-02-10 18:24:45 +0000973
Xinliang David Li4ca17332016-09-18 18:34:07 +0000974void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
975 Module *M = F.getParent();
976 IRBuilder<> Builder(&SI);
977 Type *Int64Ty = Builder.getInt64Ty();
978 Type *I8PtrTy = Builder.getInt8PtrTy();
979 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
980 Builder.CreateCall(
981 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
982 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
983 Builder.getInt64(FuncHash),
984 Builder.getInt32(TotalNumCtrs), Builder.getInt32(*CurCtrIdx), Step});
985 ++(*CurCtrIdx);
986}
987
988void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
989 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
990 assert(*CurCtrIdx < CountFromProfile.size() &&
991 "Out of bound access of counters");
992 uint64_t SCounts[2];
993 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
994 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +0000995 uint64_t TotalCount = 0;
996 auto BI = UseFunc->findBBInfo(SI.getParent());
997 if (BI != nullptr)
998 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000999 // False Count
1000 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1001 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001002 if (MaxCount)
1003 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001004}
1005
1006void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1007 if (!PGOInstrSelect)
1008 return;
1009 // FIXME: do not handle this yet.
1010 if (SI.getCondition()->getType()->isVectorTy())
1011 return;
1012
1013 NSIs++;
1014 switch (Mode) {
1015 case VM_counting:
1016 return;
1017 case VM_instrument:
1018 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001019 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001020 case VM_annotate:
1021 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001022 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001023 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001024
1025 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001026}
1027
Rong Xu13b01dc2016-02-10 18:24:45 +00001028// Traverse all the indirect callsites and annotate the instructions.
1029void PGOUseFunc::annotateIndirectCallSites() {
1030 if (DisableValueProfiling)
1031 return;
1032
Rong Xu8e8fe852016-04-01 16:43:30 +00001033 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001034 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001035
Rong Xu13b01dc2016-02-10 18:24:45 +00001036 unsigned IndirectCallSiteIndex = 0;
Xinliang David Li9780fc12016-09-20 22:39:47 +00001037 auto &IndirectCallSites = FuncInfo.IndirectCallSites;
Rong Xu9e926e82016-02-29 19:16:04 +00001038 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +00001039 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +00001040 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001041 std::string Msg =
1042 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +00001043 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +00001044 auto &Ctx = M->getContext();
1045 Ctx.diagnose(
1046 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1047 return;
1048 }
1049
Rong Xu0eb36032016-04-01 23:16:44 +00001050 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001051 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +00001052 << IndirectCallSiteIndex << " out of " << NumValueSites
1053 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +00001054 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +00001055 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +00001056 IndirectCallSiteIndex++;
1057 }
1058}
Rong Xuf430ae42015-12-09 18:08:16 +00001059} // end anonymous namespace
1060
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001061// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001062// aware this is an ir_level profile so it can set the version flag.
1063static void createIRLevelProfileFlagVariable(Module &M) {
1064 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1065 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001066 auto IRLevelVersionVariable = new GlobalVariable(
1067 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1068 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001069 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001070 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1071 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001072 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001073 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001074 else
Rong Xu9e926e82016-02-29 19:16:04 +00001075 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001076 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001077}
1078
Rong Xu705f7772016-07-25 18:45:37 +00001079// Collect the set of members for each Comdat in module M and store
1080// in ComdatMembers.
1081static void collectComdatMembers(
1082 Module &M,
1083 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1084 if (!DoComdatRenaming)
1085 return;
1086 for (Function &F : M)
1087 if (Comdat *C = F.getComdat())
1088 ComdatMembers.insert(std::make_pair(C, &F));
1089 for (GlobalVariable &GV : M.globals())
1090 if (Comdat *C = GV.getComdat())
1091 ComdatMembers.insert(std::make_pair(C, &GV));
1092 for (GlobalAlias &GA : M.aliases())
1093 if (Comdat *C = GA.getComdat())
1094 ComdatMembers.insert(std::make_pair(C, &GA));
1095}
1096
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001097static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001098 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1099 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001100 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001101 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1102 collectComdatMembers(M, ComdatMembers);
1103
Rong Xuf430ae42015-12-09 18:08:16 +00001104 for (auto &F : M) {
1105 if (F.isDeclaration())
1106 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001107 auto *BPI = LookupBPI(F);
1108 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001109 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001110 }
1111 return true;
1112}
1113
Xinliang David Li8aebf442016-05-06 05:49:19 +00001114bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001115 if (skipModule(M))
1116 return false;
1117
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001118 auto LookupBPI = [this](Function &F) {
1119 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001120 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001121 auto LookupBFI = [this](Function &F) {
1122 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001123 };
1124 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1125}
1126
Xinliang David Li8aebf442016-05-06 05:49:19 +00001127PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001128 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001129
1130 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001131 auto LookupBPI = [&FAM](Function &F) {
1132 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001133 };
1134
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001135 auto LookupBFI = [&FAM](Function &F) {
1136 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001137 };
1138
1139 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1140 return PreservedAnalyses::all();
1141
1142 return PreservedAnalyses::none();
1143}
1144
Xinliang David Lida195582016-05-10 21:59:52 +00001145static bool annotateAllFunctions(
1146 Module &M, StringRef ProfileFileName,
1147 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001148 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001149 DEBUG(dbgs() << "Read in profile counters: ");
1150 auto &Ctx = M.getContext();
1151 // Read the counter array from file.
1152 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001153 if (Error E = ReaderOrErr.takeError()) {
1154 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1155 Ctx.diagnose(
1156 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1157 });
Rong Xuf430ae42015-12-09 18:08:16 +00001158 return false;
1159 }
1160
Xinliang David Lida195582016-05-10 21:59:52 +00001161 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1162 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001163 if (!PGOReader) {
1164 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001165 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001166 return false;
1167 }
Rong Xu33c76c02016-02-10 17:18:30 +00001168 // TODO: might need to change the warning once the clang option is finalized.
1169 if (!PGOReader->isIRLevelProfile()) {
1170 Ctx.diagnose(DiagnosticInfoPGOProfile(
1171 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1172 return false;
1173 }
1174
Rong Xu705f7772016-07-25 18:45:37 +00001175 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1176 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001177 std::vector<Function *> HotFunctions;
1178 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001179 for (auto &F : M) {
1180 if (F.isDeclaration())
1181 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001182 auto *BPI = LookupBPI(F);
1183 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001184 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001185 if (!Func.readCounters(PGOReader.get()))
1186 continue;
1187 Func.populateCounters();
1188 Func.setBranchWeights();
1189 Func.annotateIndirectCallSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001190 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1191 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001192 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001193 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1194 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +00001195 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001196 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001197 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001198 // We have to apply these attributes at the end because their presence
1199 // can affect the BranchProbabilityInfo of any callers, resulting in an
1200 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001201 for (auto &F : HotFunctions) {
1202 F->addFnAttr(llvm::Attribute::InlineHint);
1203 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1204 << "\n");
1205 }
1206 for (auto &F : ColdFunctions) {
1207 F->addFnAttr(llvm::Attribute::Cold);
1208 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1209 }
Rong Xuf430ae42015-12-09 18:08:16 +00001210 return true;
1211}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001212
Xinliang David Lida195582016-05-10 21:59:52 +00001213PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001214 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001215 if (!PGOTestProfileFile.empty())
1216 ProfileFileName = PGOTestProfileFile;
1217}
1218
1219PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001220 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001221
1222 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1223 auto LookupBPI = [&FAM](Function &F) {
1224 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1225 };
1226
1227 auto LookupBFI = [&FAM](Function &F) {
1228 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1229 };
1230
1231 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1232 return PreservedAnalyses::all();
1233
1234 return PreservedAnalyses::none();
1235}
1236
Xinliang David Lid55827f2016-05-07 05:39:12 +00001237bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1238 if (skipModule(M))
1239 return false;
1240
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001241 auto LookupBPI = [this](Function &F) {
1242 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001243 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001244 auto LookupBFI = [this](Function &F) {
1245 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001246 };
1247
Xinliang David Lida195582016-05-10 21:59:52 +00001248 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001249}