blob: f4ffe23420e7f6db0ebbca864cbb2cbe61da0f1c [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(
122 "do-comdat-renaming", cl::init(true), cl::Hidden,
123 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
205 const char *getPassName() const override {
206 return "PGOInstrumentationGenPass";
207 }
208
209private:
210 bool runOnModule(Module &M) override;
211
212 void getAnalysisUsage(AnalysisUsage &AU) const override {
213 AU.addRequired<BlockFrequencyInfoWrapperPass>();
214 }
215};
216
Xinliang David Lid55827f2016-05-07 05:39:12 +0000217class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000218public:
219 static char ID;
220
221 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000222 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000223 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000224 if (!PGOTestProfileFile.empty())
225 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000226 initializePGOInstrumentationUseLegacyPassPass(
227 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000228 }
229
230 const char *getPassName() const override {
231 return "PGOInstrumentationUsePass";
232 }
233
234private:
235 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000236
Xinliang David Lida195582016-05-10 21:59:52 +0000237 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000238 void getAnalysisUsage(AnalysisUsage &AU) const override {
239 AU.addRequired<BlockFrequencyInfoWrapperPass>();
240 }
241};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000242
Rong Xuf430ae42015-12-09 18:08:16 +0000243} // end anonymous namespace
244
Xinliang David Li8aebf442016-05-06 05:49:19 +0000245char PGOInstrumentationGenLegacyPass::ID = 0;
246INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000247 "PGO instrumentation.", false, false)
248INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
249INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000250INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000251 "PGO instrumentation.", false, false)
252
Xinliang David Li8aebf442016-05-06 05:49:19 +0000253ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
254 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000255}
256
Xinliang David Lid55827f2016-05-07 05:39:12 +0000257char PGOInstrumentationUseLegacyPass::ID = 0;
258INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000259 "Read PGO instrumentation profile.", false, false)
260INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
261INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000262INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000263 "Read PGO instrumentation profile.", false, false)
264
Xinliang David Lid55827f2016-05-07 05:39:12 +0000265ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
266 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000267}
268
269namespace {
270/// \brief An MST based instrumentation for PGO
271///
272/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
273/// in the function level.
274struct PGOEdge {
275 // This class implements the CFG edges. Note the CFG can be a multi-graph.
276 // So there might be multiple edges with same SrcBB and DestBB.
277 const BasicBlock *SrcBB;
278 const BasicBlock *DestBB;
279 uint64_t Weight;
280 bool InMST;
281 bool Removed;
282 bool IsCritical;
283 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
284 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
285 IsCritical(false) {}
286 // Return the information string of an edge.
287 const std::string infoString() const {
288 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
289 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
290 }
291};
292
293// This class stores the auxiliary information for each BB.
294struct BBInfo {
295 BBInfo *Group;
296 uint32_t Index;
297 uint32_t Rank;
298
299 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
300
301 // Return the information string of this object.
302 const std::string infoString() const {
303 return (Twine("Index=") + Twine(Index)).str();
304 }
305};
306
307// This class implements the CFG edges. Note the CFG can be a multi-graph.
308template <class Edge, class BBInfo> class FuncPGOInstrumentation {
309private:
310 Function &F;
311 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000312 void renameComdatFunction();
313 // A map that stores the Comdat group in function F.
314 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000315
316public:
Xinliang David Li4ca17332016-09-18 18:34:07 +0000317 SelectInstVisitor SIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000318 std::string FuncName;
319 GlobalVariable *FuncNameVar;
320 // CFG hash value for this function.
321 uint64_t FunctionHash;
322
323 // The Minimum Spanning Tree of function CFG.
324 CFGMST<Edge, BBInfo> MST;
325
326 // Give an edge, find the BB that will be instrumented.
327 // Return nullptr if there is no BB to be instrumented.
328 BasicBlock *getInstrBB(Edge *E);
329
330 // Return the auxiliary BB information.
331 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
332
333 // 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();
350
Rong Xuf430ae42015-12-09 18:08:16 +0000351 FuncName = getPGOFuncName(F);
352 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000353 if (ComdatMembers.size())
354 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000355 DEBUG(dumpInfo("after CFGMST"));
356
357 NumOfPGOBB += MST.BBInfos.size();
358 for (auto &E : MST.AllEdges) {
359 if (E->Removed)
360 continue;
361 NumOfPGOEdge++;
362 if (!E->InMST)
363 NumOfPGOInstrument++;
364 }
365
366 if (CreateGlobalVar)
367 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000368 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000369
370 // Return the number of profile counters needed for the function.
371 unsigned getNumCounters() {
372 unsigned NumCounters = 0;
373 for (auto &E : this->MST.AllEdges) {
374 if (!E->InMST && !E->Removed)
375 NumCounters++;
376 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000377 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000378 }
Rong Xuf430ae42015-12-09 18:08:16 +0000379};
380
381// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
382// value of each BB in the CFG. The higher 32 bits record the number of edges.
383template <class Edge, class BBInfo>
384void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
385 std::vector<char> Indexes;
386 JamCRC JC;
387 for (auto &BB : F) {
388 const TerminatorInst *TI = BB.getTerminator();
389 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
390 BasicBlock *Succ = TI->getSuccessor(I);
391 uint32_t Index = getBBInfo(Succ).Index;
392 for (int J = 0; J < 4; J++)
393 Indexes.push_back((char)(Index >> (J * 8)));
394 }
395 }
396 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000397 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
398 (uint64_t)findIndirectCallSites(F).size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000399 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
400}
401
402// Check if we can safely rename this Comdat function.
403static bool canRenameComdat(
404 Function &F,
405 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
406 if (F.getName().empty())
407 return false;
408 if (!needsComdatForCounter(F, *(F.getParent())))
409 return false;
410 // Only safe to do if this function may be discarded if it is not used
411 // in the compilation unit.
412 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
413 return false;
414
415 // For AvailableExternallyLinkage functions.
416 if (!F.hasComdat()) {
417 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
418 return true;
419 }
420
421 // FIXME: Current only handle those Comdat groups that only containing one
422 // function and function aliases.
423 // (1) For a Comdat group containing multiple functions, we need to have a
424 // unique postfix based on the hashes for each function. There is a
425 // non-trivial code refactoring to do this efficiently.
426 // (2) Variables can not be renamed, so we can not rename Comdat function in a
427 // group including global vars.
428 Comdat *C = F.getComdat();
429 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
430 if (dyn_cast<GlobalAlias>(CM.second))
431 continue;
432 Function *FM = dyn_cast<Function>(CM.second);
433 if (FM != &F)
434 return false;
435 }
436 return true;
437}
438
439// Append the CFGHash to the Comdat function name.
440template <class Edge, class BBInfo>
441void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
442 if (!canRenameComdat(F, ComdatMembers))
443 return;
444 std::string NewFuncName =
445 Twine(F.getName() + "." + Twine(FunctionHash)).str();
446 F.setName(Twine(NewFuncName));
447 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
448 Comdat *NewComdat;
449 Module *M = F.getParent();
450 // For AvailableExternallyLinkage functions, change the linkage to
451 // LinkOnceODR and put them into comdat. This is because after renaming, there
452 // is no backup external copy available for the function.
453 if (!F.hasComdat()) {
454 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
455 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
456 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
457 F.setComdat(NewComdat);
458 return;
459 }
460
461 // This function belongs to a single function Comdat group.
462 Comdat *OrigComdat = F.getComdat();
463 std::string NewComdatName =
464 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
465 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
466 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
467
468 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
469 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
470 // For aliases, change the name directly.
471 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
472 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
473 continue;
474 }
475 // Must be a function.
476 Function *CF = dyn_cast<Function>(CM.second);
477 assert(CF);
478 CF->setComdat(NewComdat);
479 }
Rong Xuf430ae42015-12-09 18:08:16 +0000480}
481
482// Given a CFG E to be instrumented, find which BB to place the instrumented
483// code. The function will split the critical edge if necessary.
484template <class Edge, class BBInfo>
485BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
486 if (E->InMST || E->Removed)
487 return nullptr;
488
489 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
490 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
491 // For a fake edge, instrument the real BB.
492 if (SrcBB == nullptr)
493 return DestBB;
494 if (DestBB == nullptr)
495 return SrcBB;
496
497 // Instrument the SrcBB if it has a single successor,
498 // otherwise, the DestBB if this is not a critical edge.
499 TerminatorInst *TI = SrcBB->getTerminator();
500 if (TI->getNumSuccessors() <= 1)
501 return SrcBB;
502 if (!E->IsCritical)
503 return DestBB;
504
505 // For a critical edge, we have to split. Instrument the newly
506 // created BB.
507 NumOfPGOSplit++;
508 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
509 << getBBInfo(DestBB).Index << "\n");
510 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
511 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
512 assert(InstrBB && "Critical edge is not split");
513
514 E->Removed = true;
515 return InstrBB;
516}
517
Rong Xued9fec72016-01-21 18:11:44 +0000518// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000519// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000520static void instrumentOneFunc(
521 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
522 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000523 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
524 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000525 unsigned NumCounters = FuncInfo.getNumCounters();
526
Rong Xuf430ae42015-12-09 18:08:16 +0000527 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000528 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000529 for (auto &E : FuncInfo.MST.AllEdges) {
530 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
531 if (!InstrBB)
532 continue;
533
534 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
535 assert(Builder.GetInsertPoint() != InstrBB->end() &&
536 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000537 Builder.CreateCall(
538 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
539 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
540 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
541 Builder.getInt32(I++)});
542 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000543
544 // Now instrument select instructions:
545 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
546 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000547 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000548
549 if (DisableValueProfiling)
550 return;
551
552 unsigned NumIndirectCallSites = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000553 for (auto &I : findIndirectCallSites(F)) {
Rong Xued9fec72016-01-21 18:11:44 +0000554 CallSite CS(I);
555 Value *Callee = CS.getCalledValue();
556 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
557 << NumIndirectCallSites << "\n");
558 IRBuilder<> Builder(I);
559 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
560 "Cannot get the Instrumentation point");
561 Builder.CreateCall(
562 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
563 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
564 Builder.getInt64(FuncInfo.FunctionHash),
565 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
566 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
567 Builder.getInt32(NumIndirectCallSites++)});
568 }
569 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000570}
571
572// This class represents a CFG edge in profile use compilation.
573struct PGOUseEdge : public PGOEdge {
574 bool CountValid;
575 uint64_t CountValue;
576 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
577 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
578
579 // Set edge count value
580 void setEdgeCount(uint64_t Value) {
581 CountValue = Value;
582 CountValid = true;
583 }
584
585 // Return the information string for this object.
586 const std::string infoString() const {
587 if (!CountValid)
588 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000589 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
590 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000591 }
592};
593
594typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
595
596// This class stores the auxiliary information for each BB.
597struct UseBBInfo : public BBInfo {
598 uint64_t CountValue;
599 bool CountValid;
600 int32_t UnknownCountInEdge;
601 int32_t UnknownCountOutEdge;
602 DirectEdges InEdges;
603 DirectEdges OutEdges;
604 UseBBInfo(unsigned IX)
605 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
606 UnknownCountOutEdge(0) {}
607 UseBBInfo(unsigned IX, uint64_t C)
608 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
609 UnknownCountOutEdge(0) {}
610
611 // Set the profile count value for this BB.
612 void setBBInfoCount(uint64_t Value) {
613 CountValue = Value;
614 CountValid = true;
615 }
616
617 // Return the information string of this object.
618 const std::string infoString() const {
619 if (!CountValid)
620 return BBInfo::infoString();
621 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
622 }
623};
624
625// Sum up the count values for all the edges.
626static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
627 uint64_t Total = 0;
628 for (auto &E : Edges) {
629 if (E->Removed)
630 continue;
631 Total += E->CountValue;
632 }
633 return Total;
634}
635
636class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000637public:
Rong Xu705f7772016-07-25 18:45:37 +0000638 PGOUseFunc(Function &Func, Module *Modu,
639 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
640 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000641 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000642 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000643 FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000644
645 // Read counts for the instrumented BB from profile.
646 bool readCounters(IndexedInstrProfReader *PGOReader);
647
648 // Populate the counts for all BBs.
649 void populateCounters();
650
651 // Set the branch weights based on the count values.
652 void setBranchWeights();
653
654 // Annotate the indirect call sites.
655 void annotateIndirectCallSites();
656
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000657 // The hotness of the function from the profile count.
658 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
659
660 // Return the function hotness from the profile.
661 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
662
Rong Xu705f7772016-07-25 18:45:37 +0000663 // Return the function hash.
664 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000665 // Return the profile record for this function;
666 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
667
Xinliang David Li4ca17332016-09-18 18:34:07 +0000668 // Return the auxiliary BB information.
669 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
670 return FuncInfo.getBBInfo(BB);
671 }
672
Rong Xuf430ae42015-12-09 18:08:16 +0000673private:
674 Function &F;
675 Module *M;
676 // This member stores the shared information with class PGOGenFunc.
677 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
678
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000679 // The maximum count value in the profile. This is only used in PGO use
680 // compilation.
681 uint64_t ProgramMaxCount;
682
Rong Xu13b01dc2016-02-10 18:24:45 +0000683 // ProfileRecord for this function.
684 InstrProfRecord ProfileRecord;
685
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000686 // Function hotness info derived from profile.
687 FuncFreqAttr FreqAttr;
688
Rong Xuf430ae42015-12-09 18:08:16 +0000689 // Find the Instrumented BB and set the value.
690 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
691
692 // Set the edge counter value for the unknown edge -- there should be only
693 // one unknown edge.
694 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
695
696 // Return FuncName string;
697 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000698
699 // Set the hot/cold inline hints based on the count values.
700 // FIXME: This function should be removed once the functionality in
701 // the inliner is implemented.
702 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
703 if (ProgramMaxCount == 0)
704 return;
705 // Threshold of the hot functions.
706 const BranchProbability HotFunctionThreshold(1, 100);
707 // Threshold of the cold functions.
708 const BranchProbability ColdFunctionThreshold(2, 10000);
709 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
710 FreqAttr = FFA_Hot;
711 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
712 FreqAttr = FFA_Cold;
713 }
Rong Xuf430ae42015-12-09 18:08:16 +0000714};
715
716// Visit all the edges and assign the count value for the instrumented
717// edges and the BB.
718void PGOUseFunc::setInstrumentedCounts(
719 const std::vector<uint64_t> &CountFromProfile) {
720
Xinliang David Lid1197612016-08-01 20:25:06 +0000721 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000722 // Use a worklist as we will update the vector during the iteration.
723 std::vector<PGOUseEdge *> WorkList;
724 for (auto &E : FuncInfo.MST.AllEdges)
725 WorkList.push_back(E.get());
726
727 uint32_t I = 0;
728 for (auto &E : WorkList) {
729 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
730 if (!InstrBB)
731 continue;
732 uint64_t CountValue = CountFromProfile[I++];
733 if (!E->Removed) {
734 getBBInfo(InstrBB).setBBInfoCount(CountValue);
735 E->setEdgeCount(CountValue);
736 continue;
737 }
738
739 // Need to add two new edges.
740 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
741 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
742 // Add new edge of SrcBB->InstrBB.
743 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
744 NewEdge.setEdgeCount(CountValue);
745 // Add new edge of InstrBB->DestBB.
746 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
747 NewEdge1.setEdgeCount(CountValue);
748 NewEdge1.InMST = true;
749 getBBInfo(InstrBB).setBBInfoCount(CountValue);
750 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000751 // Now annotate select instructions
752 FuncInfo.SIVisitor.annotateSelects(F, this, &I);
Xinliang David Lid1197612016-08-01 20:25:06 +0000753 assert(I == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000754}
755
756// Set the count value for the unknown edge. There should be one and only one
757// unknown edge in Edges vector.
758void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
759 for (auto &E : Edges) {
760 if (E->CountValid)
761 continue;
762 E->setEdgeCount(Value);
763
764 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
765 getBBInfo(E->DestBB).UnknownCountInEdge--;
766 return;
767 }
768 llvm_unreachable("Cannot find the unknown count edge");
769}
770
771// Read the profile from ProfileFileName and assign the value to the
772// instrumented BB and the edges. This function also updates ProgramMaxCount.
773// Return true if the profile are successfully read, and false on errors.
774bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
775 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000776 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000777 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000778 if (Error E = Result.takeError()) {
779 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
780 auto Err = IPE.get();
781 bool SkipWarning = false;
782 if (Err == instrprof_error::unknown_function) {
783 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000784 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000785 } else if (Err == instrprof_error::hash_mismatch ||
786 Err == instrprof_error::malformed) {
787 NumOfPGOMismatch++;
788 SkipWarning = NoPGOWarnMismatch;
789 }
Rong Xuf430ae42015-12-09 18:08:16 +0000790
Vedant Kumar9152fd12016-05-19 03:54:45 +0000791 if (SkipWarning)
792 return;
793
794 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
795 Ctx.diagnose(
796 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
797 });
Rong Xuf430ae42015-12-09 18:08:16 +0000798 return false;
799 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000800 ProfileRecord = std::move(Result.get());
801 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000802
803 NumOfPGOFunc++;
804 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
805 uint64_t ValueSum = 0;
806 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
807 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
808 ValueSum += CountFromProfile[I];
809 }
810
811 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
812
813 getBBInfo(nullptr).UnknownCountOutEdge = 2;
814 getBBInfo(nullptr).UnknownCountInEdge = 2;
815
816 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000817 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000818 return true;
819}
820
821// Populate the counters from instrumented BBs to all BBs.
822// In the end of this operation, all BBs should have a valid count value.
823void PGOUseFunc::populateCounters() {
824 // First set up Count variable for all BBs.
825 for (auto &E : FuncInfo.MST.AllEdges) {
826 if (E->Removed)
827 continue;
828
829 const BasicBlock *SrcBB = E->SrcBB;
830 const BasicBlock *DestBB = E->DestBB;
831 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
832 UseBBInfo &DestInfo = getBBInfo(DestBB);
833 SrcInfo.OutEdges.push_back(E.get());
834 DestInfo.InEdges.push_back(E.get());
835 SrcInfo.UnknownCountOutEdge++;
836 DestInfo.UnknownCountInEdge++;
837
838 if (!E->CountValid)
839 continue;
840 DestInfo.UnknownCountInEdge--;
841 SrcInfo.UnknownCountOutEdge--;
842 }
843
844 bool Changes = true;
845 unsigned NumPasses = 0;
846 while (Changes) {
847 NumPasses++;
848 Changes = false;
849
850 // For efficient traversal, it's better to start from the end as most
851 // of the instrumented edges are at the end.
852 for (auto &BB : reverse(F)) {
853 UseBBInfo &Count = getBBInfo(&BB);
854 if (!Count.CountValid) {
855 if (Count.UnknownCountOutEdge == 0) {
856 Count.CountValue = sumEdgeCount(Count.OutEdges);
857 Count.CountValid = true;
858 Changes = true;
859 } else if (Count.UnknownCountInEdge == 0) {
860 Count.CountValue = sumEdgeCount(Count.InEdges);
861 Count.CountValid = true;
862 Changes = true;
863 }
864 }
865 if (Count.CountValid) {
866 if (Count.UnknownCountOutEdge == 1) {
867 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
868 setEdgeCount(Count.OutEdges, Total);
869 Changes = true;
870 }
871 if (Count.UnknownCountInEdge == 1) {
872 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
873 setEdgeCount(Count.InEdges, Total);
874 Changes = true;
875 }
876 }
877 }
878 }
879
880 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000881#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000882 // Assert every BB has a valid counter.
Sean Silva8c7e1212016-05-28 04:19:45 +0000883 for (auto &BB : F)
884 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
885#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000886 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +0000887 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000888 uint64_t FuncMaxCount = FuncEntryCount;
Sean Silva8c7e1212016-05-28 04:19:45 +0000889 for (auto &BB : F)
890 FuncMaxCount = std::max(FuncMaxCount, getBBInfo(&BB).CountValue);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000891 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000892
893 DEBUG(FuncInfo.dumpInfo("after reading profile."));
894}
895
Xinliang David Li4ca17332016-09-18 18:34:07 +0000896static void setProfMetadata(Module *M, Instruction *TI,
Xinliang David Li63248ab2016-08-19 06:31:45 +0000897 ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) {
Xinliang David Li2c933682016-08-19 05:31:33 +0000898 MDBuilder MDB(M->getContext());
899 assert(MaxCount > 0 && "Bad max count");
900 uint64_t Scale = calculateCountScale(MaxCount);
901 SmallVector<unsigned, 4> Weights;
902 for (const auto &ECI : EdgeCounts)
903 Weights.push_back(scaleBranchCount(ECI, Scale));
904
905 DEBUG(dbgs() << "Weight is: ";
906 for (const auto &W : Weights) { dbgs() << W << " "; }
907 dbgs() << "\n";);
908 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
909}
910
Rong Xuf430ae42015-12-09 18:08:16 +0000911// Assign the scaled count values to the BB with multiple out edges.
912void PGOUseFunc::setBranchWeights() {
913 // Generate MD_prof metadata for every branch instruction.
914 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000915 for (auto &BB : F) {
916 TerminatorInst *TI = BB.getTerminator();
917 if (TI->getNumSuccessors() < 2)
918 continue;
919 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
920 continue;
921 if (getBBInfo(&BB).CountValue == 0)
922 continue;
923
924 // We have a non-zero Branch BB.
925 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
926 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +0000927 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +0000928 uint64_t MaxCount = 0;
929 for (unsigned s = 0; s < Size; s++) {
930 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
931 const BasicBlock *SrcBB = E->SrcBB;
932 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000933 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000934 continue;
935 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
936 uint64_t EdgeCount = E->CountValue;
937 if (EdgeCount > MaxCount)
938 MaxCount = EdgeCount;
939 EdgeCounts[SuccNum] = EdgeCount;
940 }
Xinliang David Li2c933682016-08-19 05:31:33 +0000941 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000942 }
943}
Rong Xu13b01dc2016-02-10 18:24:45 +0000944
Xinliang David Li4ca17332016-09-18 18:34:07 +0000945void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
946 Module *M = F.getParent();
947 IRBuilder<> Builder(&SI);
948 Type *Int64Ty = Builder.getInt64Ty();
949 Type *I8PtrTy = Builder.getInt8PtrTy();
950 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
951 Builder.CreateCall(
952 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
953 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
954 Builder.getInt64(FuncHash),
955 Builder.getInt32(TotalNumCtrs), Builder.getInt32(*CurCtrIdx), Step});
956 ++(*CurCtrIdx);
957}
958
959void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
960 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
961 assert(*CurCtrIdx < CountFromProfile.size() &&
962 "Out of bound access of counters");
963 uint64_t SCounts[2];
964 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
965 ++(*CurCtrIdx);
966 uint64_t TotalCount = UseFunc->getBBInfo(SI.getParent()).CountValue;
967 // False Count
968 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
969 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
970 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
971}
972
973void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
974 if (!PGOInstrSelect)
975 return;
976 // FIXME: do not handle this yet.
977 if (SI.getCondition()->getType()->isVectorTy())
978 return;
979
980 NSIs++;
981 switch (Mode) {
982 case VM_counting:
983 return;
984 case VM_instrument:
985 instrumentOneSelectInst(SI);
986 break;
987 case VM_annotate:
988 annotateOneSelectInst(SI);
989 break;
990 default:
991 assert(false && "Unknown visiting mode");
992 break;
993 }
994}
995
Rong Xu13b01dc2016-02-10 18:24:45 +0000996// Traverse all the indirect callsites and annotate the instructions.
997void PGOUseFunc::annotateIndirectCallSites() {
998 if (DisableValueProfiling)
999 return;
1000
Rong Xu8e8fe852016-04-01 16:43:30 +00001001 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001002 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001003
Rong Xu13b01dc2016-02-10 18:24:45 +00001004 unsigned IndirectCallSiteIndex = 0;
Rong Xu0eb36032016-04-01 23:16:44 +00001005 auto IndirectCallSites = findIndirectCallSites(F);
Rong Xu9e926e82016-02-29 19:16:04 +00001006 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +00001007 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +00001008 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001009 std::string Msg =
1010 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +00001011 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +00001012 auto &Ctx = M->getContext();
1013 Ctx.diagnose(
1014 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1015 return;
1016 }
1017
Rong Xu0eb36032016-04-01 23:16:44 +00001018 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001019 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +00001020 << IndirectCallSiteIndex << " out of " << NumValueSites
1021 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +00001022 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +00001023 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +00001024 IndirectCallSiteIndex++;
1025 }
1026}
Rong Xuf430ae42015-12-09 18:08:16 +00001027} // end anonymous namespace
1028
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001029// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001030// aware this is an ir_level profile so it can set the version flag.
1031static void createIRLevelProfileFlagVariable(Module &M) {
1032 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1033 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001034 auto IRLevelVersionVariable = new GlobalVariable(
1035 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1036 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001037 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001038 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1039 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001040 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001041 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001042 else
Rong Xu9e926e82016-02-29 19:16:04 +00001043 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001044 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001045}
1046
Rong Xu705f7772016-07-25 18:45:37 +00001047// Collect the set of members for each Comdat in module M and store
1048// in ComdatMembers.
1049static void collectComdatMembers(
1050 Module &M,
1051 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1052 if (!DoComdatRenaming)
1053 return;
1054 for (Function &F : M)
1055 if (Comdat *C = F.getComdat())
1056 ComdatMembers.insert(std::make_pair(C, &F));
1057 for (GlobalVariable &GV : M.globals())
1058 if (Comdat *C = GV.getComdat())
1059 ComdatMembers.insert(std::make_pair(C, &GV));
1060 for (GlobalAlias &GA : M.aliases())
1061 if (Comdat *C = GA.getComdat())
1062 ComdatMembers.insert(std::make_pair(C, &GA));
1063}
1064
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001065static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001066 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1067 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001068 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001069 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1070 collectComdatMembers(M, ComdatMembers);
1071
Rong Xuf430ae42015-12-09 18:08:16 +00001072 for (auto &F : M) {
1073 if (F.isDeclaration())
1074 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001075 auto *BPI = LookupBPI(F);
1076 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001077 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001078 }
1079 return true;
1080}
1081
Xinliang David Li8aebf442016-05-06 05:49:19 +00001082bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001083 if (skipModule(M))
1084 return false;
1085
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001086 auto LookupBPI = [this](Function &F) {
1087 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001088 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001089 auto LookupBFI = [this](Function &F) {
1090 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001091 };
1092 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1093}
1094
Xinliang David Li8aebf442016-05-06 05:49:19 +00001095PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001096 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001097
1098 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001099 auto LookupBPI = [&FAM](Function &F) {
1100 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001101 };
1102
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001103 auto LookupBFI = [&FAM](Function &F) {
1104 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001105 };
1106
1107 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1108 return PreservedAnalyses::all();
1109
1110 return PreservedAnalyses::none();
1111}
1112
Xinliang David Lida195582016-05-10 21:59:52 +00001113static bool annotateAllFunctions(
1114 Module &M, StringRef ProfileFileName,
1115 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001116 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001117 DEBUG(dbgs() << "Read in profile counters: ");
1118 auto &Ctx = M.getContext();
1119 // Read the counter array from file.
1120 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001121 if (Error E = ReaderOrErr.takeError()) {
1122 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1123 Ctx.diagnose(
1124 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1125 });
Rong Xuf430ae42015-12-09 18:08:16 +00001126 return false;
1127 }
1128
Xinliang David Lida195582016-05-10 21:59:52 +00001129 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1130 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001131 if (!PGOReader) {
1132 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001133 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001134 return false;
1135 }
Rong Xu33c76c02016-02-10 17:18:30 +00001136 // TODO: might need to change the warning once the clang option is finalized.
1137 if (!PGOReader->isIRLevelProfile()) {
1138 Ctx.diagnose(DiagnosticInfoPGOProfile(
1139 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1140 return false;
1141 }
1142
Rong Xu705f7772016-07-25 18:45:37 +00001143 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1144 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001145 std::vector<Function *> HotFunctions;
1146 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001147 for (auto &F : M) {
1148 if (F.isDeclaration())
1149 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001150 auto *BPI = LookupBPI(F);
1151 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001152 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001153 if (!Func.readCounters(PGOReader.get()))
1154 continue;
1155 Func.populateCounters();
1156 Func.setBranchWeights();
1157 Func.annotateIndirectCallSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001158 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1159 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001160 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001161 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1162 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +00001163 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001164 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001165 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001166 // We have to apply these attributes at the end because their presence
1167 // can affect the BranchProbabilityInfo of any callers, resulting in an
1168 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001169 for (auto &F : HotFunctions) {
1170 F->addFnAttr(llvm::Attribute::InlineHint);
1171 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1172 << "\n");
1173 }
1174 for (auto &F : ColdFunctions) {
1175 F->addFnAttr(llvm::Attribute::Cold);
1176 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1177 }
Rong Xuf430ae42015-12-09 18:08:16 +00001178 return true;
1179}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001180
Xinliang David Lida195582016-05-10 21:59:52 +00001181PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001182 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001183 if (!PGOTestProfileFile.empty())
1184 ProfileFileName = PGOTestProfileFile;
1185}
1186
1187PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001188 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001189
1190 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1191 auto LookupBPI = [&FAM](Function &F) {
1192 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1193 };
1194
1195 auto LookupBFI = [&FAM](Function &F) {
1196 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1197 };
1198
1199 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1200 return PreservedAnalyses::all();
1201
1202 return PreservedAnalyses::none();
1203}
1204
Xinliang David Lid55827f2016-05-07 05:39:12 +00001205bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1206 if (skipModule(M))
1207 return false;
1208
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001209 auto LookupBPI = [this](Function &F) {
1210 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001211 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001212 auto LookupBFI = [this](Function &F) {
1213 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001214 };
1215
Xinliang David Lida195582016-05-10 21:59:52 +00001216 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001217}