blob: f8bedb2ce36d6f63e9500ecd3d7f16e739702791 [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.");
89STATISTIC(NumOfPGOEdge, "Number of edges.");
90STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
91STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
92STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
93STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
94STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +000095STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +000096
97// Command line option to specify the file to read profile from. This is
98// mainly used for testing.
99static cl::opt<std::string>
100 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
101 cl::value_desc("filename"),
102 cl::desc("Specify the path of profile data file. This is"
103 "mainly for test purpose."));
104
Rong Xuecdc98f2016-03-04 22:08:44 +0000105// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000106// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000107static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
108 cl::Hidden,
109 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000110
Rong Xuecdc98f2016-03-04 22:08:44 +0000111// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000112// the metadata for a single indirect call callsite.
113static cl::opt<unsigned> MaxNumAnnotations(
114 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
115 cl::desc("Max number of annotations for a single indirect "
116 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000117
Rong Xu705f7772016-07-25 18:45:37 +0000118// Command line option to control appending FunctionHash to the name of a COMDAT
119// function. This is to avoid the hash mismatch caused by the preinliner.
120static cl::opt<bool> DoComdatRenaming(
121 "do-comdat-renaming", cl::init(true), cl::Hidden,
122 cl::desc("Append function hash to the name of COMDAT function to avoid "
123 "function hash mismatch due to the preinliner"));
124
Rong Xu0698de92016-05-13 17:26:06 +0000125// Command line option to enable/disable the warning about missing profile
126// information.
127static cl::opt<bool> NoPGOWarnMissing("no-pgo-warn-missing", cl::init(false),
128 cl::Hidden);
129
130// Command line option to enable/disable the warning about a hash mismatch in
131// the profile data.
132static cl::opt<bool> NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false),
133 cl::Hidden);
134
Rong Xuf430ae42015-12-09 18:08:16 +0000135namespace {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000136class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000137public:
138 static char ID;
139
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000140 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000141 initializePGOInstrumentationGenLegacyPassPass(
142 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000143 }
144
145 const char *getPassName() const override {
146 return "PGOInstrumentationGenPass";
147 }
148
149private:
150 bool runOnModule(Module &M) override;
151
152 void getAnalysisUsage(AnalysisUsage &AU) const override {
153 AU.addRequired<BlockFrequencyInfoWrapperPass>();
154 }
155};
156
Xinliang David Lid55827f2016-05-07 05:39:12 +0000157class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000158public:
159 static char ID;
160
161 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000162 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000163 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000164 if (!PGOTestProfileFile.empty())
165 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000166 initializePGOInstrumentationUseLegacyPassPass(
167 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000168 }
169
170 const char *getPassName() const override {
171 return "PGOInstrumentationUsePass";
172 }
173
174private:
175 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000176
Xinliang David Lida195582016-05-10 21:59:52 +0000177 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000178 void getAnalysisUsage(AnalysisUsage &AU) const override {
179 AU.addRequired<BlockFrequencyInfoWrapperPass>();
180 }
181};
182} // end anonymous namespace
183
Xinliang David Li8aebf442016-05-06 05:49:19 +0000184char PGOInstrumentationGenLegacyPass::ID = 0;
185INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000186 "PGO instrumentation.", false, false)
187INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
188INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000189INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000190 "PGO instrumentation.", false, false)
191
Xinliang David Li8aebf442016-05-06 05:49:19 +0000192ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
193 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000194}
195
Xinliang David Lid55827f2016-05-07 05:39:12 +0000196char PGOInstrumentationUseLegacyPass::ID = 0;
197INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000198 "Read PGO instrumentation profile.", false, false)
199INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
200INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000201INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000202 "Read PGO instrumentation profile.", false, false)
203
Xinliang David Lid55827f2016-05-07 05:39:12 +0000204ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
205 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000206}
207
208namespace {
209/// \brief An MST based instrumentation for PGO
210///
211/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
212/// in the function level.
213struct PGOEdge {
214 // This class implements the CFG edges. Note the CFG can be a multi-graph.
215 // So there might be multiple edges with same SrcBB and DestBB.
216 const BasicBlock *SrcBB;
217 const BasicBlock *DestBB;
218 uint64_t Weight;
219 bool InMST;
220 bool Removed;
221 bool IsCritical;
222 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
223 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
224 IsCritical(false) {}
225 // Return the information string of an edge.
226 const std::string infoString() const {
227 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
228 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
229 }
230};
231
232// This class stores the auxiliary information for each BB.
233struct BBInfo {
234 BBInfo *Group;
235 uint32_t Index;
236 uint32_t Rank;
237
238 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
239
240 // Return the information string of this object.
241 const std::string infoString() const {
242 return (Twine("Index=") + Twine(Index)).str();
243 }
244};
245
246// This class implements the CFG edges. Note the CFG can be a multi-graph.
247template <class Edge, class BBInfo> class FuncPGOInstrumentation {
248private:
249 Function &F;
250 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000251 void renameComdatFunction();
252 // A map that stores the Comdat group in function F.
253 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000254
255public:
256 std::string FuncName;
257 GlobalVariable *FuncNameVar;
258 // CFG hash value for this function.
259 uint64_t FunctionHash;
260
261 // The Minimum Spanning Tree of function CFG.
262 CFGMST<Edge, BBInfo> MST;
263
264 // Give an edge, find the BB that will be instrumented.
265 // Return nullptr if there is no BB to be instrumented.
266 BasicBlock *getInstrBB(Edge *E);
267
268 // Return the auxiliary BB information.
269 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
270
271 // Dump edges and BB information.
272 void dumpInfo(std::string Str = "") const {
273 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000274 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000275 }
276
Rong Xu705f7772016-07-25 18:45:37 +0000277 FuncPGOInstrumentation(
278 Function &Func,
279 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
280 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
281 BlockFrequencyInfo *BFI = nullptr)
282 : F(Func), ComdatMembers(ComdatMembers), FunctionHash(0),
283 MST(F, BPI, BFI) {
Rong Xuf430ae42015-12-09 18:08:16 +0000284 FuncName = getPGOFuncName(F);
285 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000286 if (ComdatMembers.size())
287 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000288 DEBUG(dumpInfo("after CFGMST"));
289
290 NumOfPGOBB += MST.BBInfos.size();
291 for (auto &E : MST.AllEdges) {
292 if (E->Removed)
293 continue;
294 NumOfPGOEdge++;
295 if (!E->InMST)
296 NumOfPGOInstrument++;
297 }
298
299 if (CreateGlobalVar)
300 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000301 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000302
303 // Return the number of profile counters needed for the function.
304 unsigned getNumCounters() {
305 unsigned NumCounters = 0;
306 for (auto &E : this->MST.AllEdges) {
307 if (!E->InMST && !E->Removed)
308 NumCounters++;
309 }
310 return NumCounters;
311 }
Rong Xuf430ae42015-12-09 18:08:16 +0000312};
313
314// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
315// value of each BB in the CFG. The higher 32 bits record the number of edges.
316template <class Edge, class BBInfo>
317void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
318 std::vector<char> Indexes;
319 JamCRC JC;
320 for (auto &BB : F) {
321 const TerminatorInst *TI = BB.getTerminator();
322 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
323 BasicBlock *Succ = TI->getSuccessor(I);
324 uint32_t Index = getBBInfo(Succ).Index;
325 for (int J = 0; J < 4; J++)
326 Indexes.push_back((char)(Index >> (J * 8)));
327 }
328 }
329 JC.update(Indexes);
Rong Xu705f7772016-07-25 18:45:37 +0000330 FunctionHash = (uint64_t)findIndirectCallSites(F).size() << 48 |
331 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
332}
333
334// Check if we can safely rename this Comdat function.
335static bool canRenameComdat(
336 Function &F,
337 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
338 if (F.getName().empty())
339 return false;
340 if (!needsComdatForCounter(F, *(F.getParent())))
341 return false;
342 // Only safe to do if this function may be discarded if it is not used
343 // in the compilation unit.
344 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
345 return false;
346
347 // For AvailableExternallyLinkage functions.
348 if (!F.hasComdat()) {
349 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
350 return true;
351 }
352
353 // FIXME: Current only handle those Comdat groups that only containing one
354 // function and function aliases.
355 // (1) For a Comdat group containing multiple functions, we need to have a
356 // unique postfix based on the hashes for each function. There is a
357 // non-trivial code refactoring to do this efficiently.
358 // (2) Variables can not be renamed, so we can not rename Comdat function in a
359 // group including global vars.
360 Comdat *C = F.getComdat();
361 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
362 if (dyn_cast<GlobalAlias>(CM.second))
363 continue;
364 Function *FM = dyn_cast<Function>(CM.second);
365 if (FM != &F)
366 return false;
367 }
368 return true;
369}
370
371// Append the CFGHash to the Comdat function name.
372template <class Edge, class BBInfo>
373void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
374 if (!canRenameComdat(F, ComdatMembers))
375 return;
376 std::string NewFuncName =
377 Twine(F.getName() + "." + Twine(FunctionHash)).str();
378 F.setName(Twine(NewFuncName));
379 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
380 Comdat *NewComdat;
381 Module *M = F.getParent();
382 // For AvailableExternallyLinkage functions, change the linkage to
383 // LinkOnceODR and put them into comdat. This is because after renaming, there
384 // is no backup external copy available for the function.
385 if (!F.hasComdat()) {
386 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
387 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
388 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
389 F.setComdat(NewComdat);
390 return;
391 }
392
393 // This function belongs to a single function Comdat group.
394 Comdat *OrigComdat = F.getComdat();
395 std::string NewComdatName =
396 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
397 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
398 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
399
400 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
401 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
402 // For aliases, change the name directly.
403 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
404 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
405 continue;
406 }
407 // Must be a function.
408 Function *CF = dyn_cast<Function>(CM.second);
409 assert(CF);
410 CF->setComdat(NewComdat);
411 }
Rong Xuf430ae42015-12-09 18:08:16 +0000412}
413
414// Given a CFG E to be instrumented, find which BB to place the instrumented
415// code. The function will split the critical edge if necessary.
416template <class Edge, class BBInfo>
417BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
418 if (E->InMST || E->Removed)
419 return nullptr;
420
421 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
422 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
423 // For a fake edge, instrument the real BB.
424 if (SrcBB == nullptr)
425 return DestBB;
426 if (DestBB == nullptr)
427 return SrcBB;
428
429 // Instrument the SrcBB if it has a single successor,
430 // otherwise, the DestBB if this is not a critical edge.
431 TerminatorInst *TI = SrcBB->getTerminator();
432 if (TI->getNumSuccessors() <= 1)
433 return SrcBB;
434 if (!E->IsCritical)
435 return DestBB;
436
437 // For a critical edge, we have to split. Instrument the newly
438 // created BB.
439 NumOfPGOSplit++;
440 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
441 << getBBInfo(DestBB).Index << "\n");
442 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
443 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
444 assert(InstrBB && "Critical edge is not split");
445
446 E->Removed = true;
447 return InstrBB;
448}
449
Rong Xued9fec72016-01-21 18:11:44 +0000450// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000451// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000452static void instrumentOneFunc(
453 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
454 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000455 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
456 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000457 unsigned NumCounters = FuncInfo.getNumCounters();
458
Rong Xuf430ae42015-12-09 18:08:16 +0000459 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000460 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000461 for (auto &E : FuncInfo.MST.AllEdges) {
462 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
463 if (!InstrBB)
464 continue;
465
466 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
467 assert(Builder.GetInsertPoint() != InstrBB->end() &&
468 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000469 Builder.CreateCall(
470 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
471 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
472 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
473 Builder.getInt32(I++)});
474 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000475 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000476
477 if (DisableValueProfiling)
478 return;
479
480 unsigned NumIndirectCallSites = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000481 for (auto &I : findIndirectCallSites(F)) {
Rong Xued9fec72016-01-21 18:11:44 +0000482 CallSite CS(I);
483 Value *Callee = CS.getCalledValue();
484 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
485 << NumIndirectCallSites << "\n");
486 IRBuilder<> Builder(I);
487 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
488 "Cannot get the Instrumentation point");
489 Builder.CreateCall(
490 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
491 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
492 Builder.getInt64(FuncInfo.FunctionHash),
493 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
494 Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget),
495 Builder.getInt32(NumIndirectCallSites++)});
496 }
497 NumOfPGOICall += NumIndirectCallSites;
Rong Xuf430ae42015-12-09 18:08:16 +0000498}
499
500// This class represents a CFG edge in profile use compilation.
501struct PGOUseEdge : public PGOEdge {
502 bool CountValid;
503 uint64_t CountValue;
504 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
505 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
506
507 // Set edge count value
508 void setEdgeCount(uint64_t Value) {
509 CountValue = Value;
510 CountValid = true;
511 }
512
513 // Return the information string for this object.
514 const std::string infoString() const {
515 if (!CountValid)
516 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000517 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
518 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000519 }
520};
521
522typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
523
524// This class stores the auxiliary information for each BB.
525struct UseBBInfo : public BBInfo {
526 uint64_t CountValue;
527 bool CountValid;
528 int32_t UnknownCountInEdge;
529 int32_t UnknownCountOutEdge;
530 DirectEdges InEdges;
531 DirectEdges OutEdges;
532 UseBBInfo(unsigned IX)
533 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
534 UnknownCountOutEdge(0) {}
535 UseBBInfo(unsigned IX, uint64_t C)
536 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
537 UnknownCountOutEdge(0) {}
538
539 // Set the profile count value for this BB.
540 void setBBInfoCount(uint64_t Value) {
541 CountValue = Value;
542 CountValid = true;
543 }
544
545 // Return the information string of this object.
546 const std::string infoString() const {
547 if (!CountValid)
548 return BBInfo::infoString();
549 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
550 }
551};
552
553// Sum up the count values for all the edges.
554static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
555 uint64_t Total = 0;
556 for (auto &E : Edges) {
557 if (E->Removed)
558 continue;
559 Total += E->CountValue;
560 }
561 return Total;
562}
563
564class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000565public:
Rong Xu705f7772016-07-25 18:45:37 +0000566 PGOUseFunc(Function &Func, Module *Modu,
567 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
568 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000569 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000570 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000571 FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000572
573 // Read counts for the instrumented BB from profile.
574 bool readCounters(IndexedInstrProfReader *PGOReader);
575
576 // Populate the counts for all BBs.
577 void populateCounters();
578
579 // Set the branch weights based on the count values.
580 void setBranchWeights();
581
582 // Annotate the indirect call sites.
583 void annotateIndirectCallSites();
584
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000585 // The hotness of the function from the profile count.
586 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
587
588 // Return the function hotness from the profile.
589 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
590
Rong Xu705f7772016-07-25 18:45:37 +0000591 // Return the function hash.
592 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000593 // Return the profile record for this function;
594 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
595
Rong Xuf430ae42015-12-09 18:08:16 +0000596private:
597 Function &F;
598 Module *M;
599 // This member stores the shared information with class PGOGenFunc.
600 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
601
602 // Return the auxiliary BB information.
603 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
604 return FuncInfo.getBBInfo(BB);
605 }
606
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000607 // The maximum count value in the profile. This is only used in PGO use
608 // compilation.
609 uint64_t ProgramMaxCount;
610
Rong Xu13b01dc2016-02-10 18:24:45 +0000611 // ProfileRecord for this function.
612 InstrProfRecord ProfileRecord;
613
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000614 // Function hotness info derived from profile.
615 FuncFreqAttr FreqAttr;
616
Rong Xuf430ae42015-12-09 18:08:16 +0000617 // Find the Instrumented BB and set the value.
618 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
619
620 // Set the edge counter value for the unknown edge -- there should be only
621 // one unknown edge.
622 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
623
624 // Return FuncName string;
625 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000626
627 // Set the hot/cold inline hints based on the count values.
628 // FIXME: This function should be removed once the functionality in
629 // the inliner is implemented.
630 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
631 if (ProgramMaxCount == 0)
632 return;
633 // Threshold of the hot functions.
634 const BranchProbability HotFunctionThreshold(1, 100);
635 // Threshold of the cold functions.
636 const BranchProbability ColdFunctionThreshold(2, 10000);
637 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
638 FreqAttr = FFA_Hot;
639 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
640 FreqAttr = FFA_Cold;
641 }
Rong Xuf430ae42015-12-09 18:08:16 +0000642};
643
644// Visit all the edges and assign the count value for the instrumented
645// edges and the BB.
646void PGOUseFunc::setInstrumentedCounts(
647 const std::vector<uint64_t> &CountFromProfile) {
648
Xinliang David Lid1197612016-08-01 20:25:06 +0000649 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000650 // Use a worklist as we will update the vector during the iteration.
651 std::vector<PGOUseEdge *> WorkList;
652 for (auto &E : FuncInfo.MST.AllEdges)
653 WorkList.push_back(E.get());
654
655 uint32_t I = 0;
656 for (auto &E : WorkList) {
657 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
658 if (!InstrBB)
659 continue;
660 uint64_t CountValue = CountFromProfile[I++];
661 if (!E->Removed) {
662 getBBInfo(InstrBB).setBBInfoCount(CountValue);
663 E->setEdgeCount(CountValue);
664 continue;
665 }
666
667 // Need to add two new edges.
668 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
669 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
670 // Add new edge of SrcBB->InstrBB.
671 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
672 NewEdge.setEdgeCount(CountValue);
673 // Add new edge of InstrBB->DestBB.
674 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
675 NewEdge1.setEdgeCount(CountValue);
676 NewEdge1.InMST = true;
677 getBBInfo(InstrBB).setBBInfoCount(CountValue);
678 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000679 assert(I == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000680}
681
682// Set the count value for the unknown edge. There should be one and only one
683// unknown edge in Edges vector.
684void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
685 for (auto &E : Edges) {
686 if (E->CountValid)
687 continue;
688 E->setEdgeCount(Value);
689
690 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
691 getBBInfo(E->DestBB).UnknownCountInEdge--;
692 return;
693 }
694 llvm_unreachable("Cannot find the unknown count edge");
695}
696
697// Read the profile from ProfileFileName and assign the value to the
698// instrumented BB and the edges. This function also updates ProgramMaxCount.
699// Return true if the profile are successfully read, and false on errors.
700bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
701 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000702 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000703 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000704 if (Error E = Result.takeError()) {
705 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
706 auto Err = IPE.get();
707 bool SkipWarning = false;
708 if (Err == instrprof_error::unknown_function) {
709 NumOfPGOMissing++;
710 SkipWarning = NoPGOWarnMissing;
711 } else if (Err == instrprof_error::hash_mismatch ||
712 Err == instrprof_error::malformed) {
713 NumOfPGOMismatch++;
714 SkipWarning = NoPGOWarnMismatch;
715 }
Rong Xuf430ae42015-12-09 18:08:16 +0000716
Vedant Kumar9152fd12016-05-19 03:54:45 +0000717 if (SkipWarning)
718 return;
719
720 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
721 Ctx.diagnose(
722 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
723 });
Rong Xuf430ae42015-12-09 18:08:16 +0000724 return false;
725 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000726 ProfileRecord = std::move(Result.get());
727 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000728
729 NumOfPGOFunc++;
730 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
731 uint64_t ValueSum = 0;
732 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
733 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
734 ValueSum += CountFromProfile[I];
735 }
736
737 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
738
739 getBBInfo(nullptr).UnknownCountOutEdge = 2;
740 getBBInfo(nullptr).UnknownCountInEdge = 2;
741
742 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000743 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000744 return true;
745}
746
747// Populate the counters from instrumented BBs to all BBs.
748// In the end of this operation, all BBs should have a valid count value.
749void PGOUseFunc::populateCounters() {
750 // First set up Count variable for all BBs.
751 for (auto &E : FuncInfo.MST.AllEdges) {
752 if (E->Removed)
753 continue;
754
755 const BasicBlock *SrcBB = E->SrcBB;
756 const BasicBlock *DestBB = E->DestBB;
757 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
758 UseBBInfo &DestInfo = getBBInfo(DestBB);
759 SrcInfo.OutEdges.push_back(E.get());
760 DestInfo.InEdges.push_back(E.get());
761 SrcInfo.UnknownCountOutEdge++;
762 DestInfo.UnknownCountInEdge++;
763
764 if (!E->CountValid)
765 continue;
766 DestInfo.UnknownCountInEdge--;
767 SrcInfo.UnknownCountOutEdge--;
768 }
769
770 bool Changes = true;
771 unsigned NumPasses = 0;
772 while (Changes) {
773 NumPasses++;
774 Changes = false;
775
776 // For efficient traversal, it's better to start from the end as most
777 // of the instrumented edges are at the end.
778 for (auto &BB : reverse(F)) {
779 UseBBInfo &Count = getBBInfo(&BB);
780 if (!Count.CountValid) {
781 if (Count.UnknownCountOutEdge == 0) {
782 Count.CountValue = sumEdgeCount(Count.OutEdges);
783 Count.CountValid = true;
784 Changes = true;
785 } else if (Count.UnknownCountInEdge == 0) {
786 Count.CountValue = sumEdgeCount(Count.InEdges);
787 Count.CountValid = true;
788 Changes = true;
789 }
790 }
791 if (Count.CountValid) {
792 if (Count.UnknownCountOutEdge == 1) {
793 uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);
794 setEdgeCount(Count.OutEdges, Total);
795 Changes = true;
796 }
797 if (Count.UnknownCountInEdge == 1) {
798 uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);
799 setEdgeCount(Count.InEdges, Total);
800 Changes = true;
801 }
802 }
803 }
804 }
805
806 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +0000807#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000808 // Assert every BB has a valid counter.
Sean Silva8c7e1212016-05-28 04:19:45 +0000809 for (auto &BB : F)
810 assert(getBBInfo(&BB).CountValid && "BB count is not valid");
811#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000812 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +0000813 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000814 uint64_t FuncMaxCount = FuncEntryCount;
Sean Silva8c7e1212016-05-28 04:19:45 +0000815 for (auto &BB : F)
816 FuncMaxCount = std::max(FuncMaxCount, getBBInfo(&BB).CountValue);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000817 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +0000818
819 DEBUG(FuncInfo.dumpInfo("after reading profile."));
820}
821
822// Assign the scaled count values to the BB with multiple out edges.
823void PGOUseFunc::setBranchWeights() {
824 // Generate MD_prof metadata for every branch instruction.
825 DEBUG(dbgs() << "\nSetting branch weights.\n");
826 MDBuilder MDB(M->getContext());
827 for (auto &BB : F) {
828 TerminatorInst *TI = BB.getTerminator();
829 if (TI->getNumSuccessors() < 2)
830 continue;
831 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
832 continue;
833 if (getBBInfo(&BB).CountValue == 0)
834 continue;
835
836 // We have a non-zero Branch BB.
837 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
838 unsigned Size = BBCountInfo.OutEdges.size();
839 SmallVector<unsigned, 2> EdgeCounts(Size, 0);
840 uint64_t MaxCount = 0;
841 for (unsigned s = 0; s < Size; s++) {
842 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
843 const BasicBlock *SrcBB = E->SrcBB;
844 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000845 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +0000846 continue;
847 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
848 uint64_t EdgeCount = E->CountValue;
849 if (EdgeCount > MaxCount)
850 MaxCount = EdgeCount;
851 EdgeCounts[SuccNum] = EdgeCount;
852 }
853 assert(MaxCount > 0 && "Bad max count");
854 uint64_t Scale = calculateCountScale(MaxCount);
855 SmallVector<unsigned, 4> Weights;
856 for (const auto &ECI : EdgeCounts)
857 Weights.push_back(scaleBranchCount(ECI, Scale));
858
859 TI->setMetadata(llvm::LLVMContext::MD_prof,
860 MDB.createBranchWeights(Weights));
861 DEBUG(dbgs() << "Weight is: ";
862 for (const auto &W : Weights) { dbgs() << W << " "; }
863 dbgs() << "\n";);
864 }
865}
Rong Xu13b01dc2016-02-10 18:24:45 +0000866
867// Traverse all the indirect callsites and annotate the instructions.
868void PGOUseFunc::annotateIndirectCallSites() {
869 if (DisableValueProfiling)
870 return;
871
Rong Xu8e8fe852016-04-01 16:43:30 +0000872 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +0000873 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +0000874
Rong Xu13b01dc2016-02-10 18:24:45 +0000875 unsigned IndirectCallSiteIndex = 0;
Rong Xu0eb36032016-04-01 23:16:44 +0000876 auto IndirectCallSites = findIndirectCallSites(F);
Rong Xu9e926e82016-02-29 19:16:04 +0000877 unsigned NumValueSites =
Rong Xu13b01dc2016-02-10 18:24:45 +0000878 ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget);
Rong Xu0eb36032016-04-01 23:16:44 +0000879 if (NumValueSites != IndirectCallSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000880 std::string Msg =
881 std::string("Inconsistent number of indirect call sites: ") +
Rong Xu9e926e82016-02-29 19:16:04 +0000882 F.getName().str();
Rong Xu13b01dc2016-02-10 18:24:45 +0000883 auto &Ctx = M->getContext();
884 Ctx.diagnose(
885 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
886 return;
887 }
888
Rong Xu0eb36032016-04-01 23:16:44 +0000889 for (auto &I : IndirectCallSites) {
Rong Xu13b01dc2016-02-10 18:24:45 +0000890 DEBUG(dbgs() << "Read one indirect call instrumentation: Index="
Rong Xu9e926e82016-02-29 19:16:04 +0000891 << IndirectCallSiteIndex << " out of " << NumValueSites
892 << "\n");
Rong Xu13b01dc2016-02-10 18:24:45 +0000893 annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget,
Rong Xuecdc98f2016-03-04 22:08:44 +0000894 IndirectCallSiteIndex, MaxNumAnnotations);
Rong Xu13b01dc2016-02-10 18:24:45 +0000895 IndirectCallSiteIndex++;
896 }
897}
Rong Xuf430ae42015-12-09 18:08:16 +0000898} // end anonymous namespace
899
Xinliang David Lid382e9d2016-07-22 04:46:56 +0000900// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +0000901// aware this is an ir_level profile so it can set the version flag.
902static void createIRLevelProfileFlagVariable(Module &M) {
903 Type *IntTy64 = Type::getInt64Ty(M.getContext());
904 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +0000905 auto IRLevelVersionVariable = new GlobalVariable(
906 M, IntTy64, true, GlobalVariable::ExternalLinkage,
907 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +0000908 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +0000909 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
910 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +0000911 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +0000912 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +0000913 else
Rong Xu9e926e82016-02-29 19:16:04 +0000914 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +0000915 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +0000916}
917
Rong Xu705f7772016-07-25 18:45:37 +0000918// Collect the set of members for each Comdat in module M and store
919// in ComdatMembers.
920static void collectComdatMembers(
921 Module &M,
922 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
923 if (!DoComdatRenaming)
924 return;
925 for (Function &F : M)
926 if (Comdat *C = F.getComdat())
927 ComdatMembers.insert(std::make_pair(C, &F));
928 for (GlobalVariable &GV : M.globals())
929 if (Comdat *C = GV.getComdat())
930 ComdatMembers.insert(std::make_pair(C, &GV));
931 for (GlobalAlias &GA : M.aliases())
932 if (Comdat *C = GA.getComdat())
933 ComdatMembers.insert(std::make_pair(C, &GA));
934}
935
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000936static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000937 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
938 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +0000939 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +0000940 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
941 collectComdatMembers(M, ComdatMembers);
942
Rong Xuf430ae42015-12-09 18:08:16 +0000943 for (auto &F : M) {
944 if (F.isDeclaration())
945 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000946 auto *BPI = LookupBPI(F);
947 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +0000948 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +0000949 }
950 return true;
951}
952
Xinliang David Li8aebf442016-05-06 05:49:19 +0000953bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000954 if (skipModule(M))
955 return false;
956
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000957 auto LookupBPI = [this](Function &F) {
958 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000959 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000960 auto LookupBFI = [this](Function &F) {
961 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +0000962 };
963 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
964}
965
Xinliang David Li8aebf442016-05-06 05:49:19 +0000966PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000967 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000968
969 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000970 auto LookupBPI = [&FAM](Function &F) {
971 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +0000972 };
973
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000974 auto LookupBFI = [&FAM](Function &F) {
975 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +0000976 };
977
978 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
979 return PreservedAnalyses::all();
980
981 return PreservedAnalyses::none();
982}
983
Xinliang David Lida195582016-05-10 21:59:52 +0000984static bool annotateAllFunctions(
985 Module &M, StringRef ProfileFileName,
986 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000987 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +0000988 DEBUG(dbgs() << "Read in profile counters: ");
989 auto &Ctx = M.getContext();
990 // Read the counter array from file.
991 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000992 if (Error E = ReaderOrErr.takeError()) {
993 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
994 Ctx.diagnose(
995 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
996 });
Rong Xuf430ae42015-12-09 18:08:16 +0000997 return false;
998 }
999
Xinliang David Lida195582016-05-10 21:59:52 +00001000 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1001 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001002 if (!PGOReader) {
1003 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001004 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001005 return false;
1006 }
Rong Xu33c76c02016-02-10 17:18:30 +00001007 // TODO: might need to change the warning once the clang option is finalized.
1008 if (!PGOReader->isIRLevelProfile()) {
1009 Ctx.diagnose(DiagnosticInfoPGOProfile(
1010 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1011 return false;
1012 }
1013
Rong Xu705f7772016-07-25 18:45:37 +00001014 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1015 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001016 std::vector<Function *> HotFunctions;
1017 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001018 for (auto &F : M) {
1019 if (F.isDeclaration())
1020 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001021 auto *BPI = LookupBPI(F);
1022 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001023 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001024 if (!Func.readCounters(PGOReader.get()))
1025 continue;
1026 Func.populateCounters();
1027 Func.setBranchWeights();
1028 Func.annotateIndirectCallSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001029 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1030 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001031 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001032 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1033 HotFunctions.push_back(&F);
Rong Xuf430ae42015-12-09 18:08:16 +00001034 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001035 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001036 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001037 // We have to apply these attributes at the end because their presence
1038 // can affect the BranchProbabilityInfo of any callers, resulting in an
1039 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001040 for (auto &F : HotFunctions) {
1041 F->addFnAttr(llvm::Attribute::InlineHint);
1042 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1043 << "\n");
1044 }
1045 for (auto &F : ColdFunctions) {
1046 F->addFnAttr(llvm::Attribute::Cold);
1047 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1048 }
Rong Xuf430ae42015-12-09 18:08:16 +00001049 return true;
1050}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001051
Xinliang David Lida195582016-05-10 21:59:52 +00001052PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001053 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001054 if (!PGOTestProfileFile.empty())
1055 ProfileFileName = PGOTestProfileFile;
1056}
1057
1058PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001059 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001060
1061 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1062 auto LookupBPI = [&FAM](Function &F) {
1063 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1064 };
1065
1066 auto LookupBFI = [&FAM](Function &F) {
1067 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1068 };
1069
1070 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1071 return PreservedAnalyses::all();
1072
1073 return PreservedAnalyses::none();
1074}
1075
Xinliang David Lid55827f2016-05-07 05:39:12 +00001076bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1077 if (skipModule(M))
1078 return false;
1079
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001080 auto LookupBPI = [this](Function &F) {
1081 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001082 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001083 auto LookupBFI = [this](Function &F) {
1084 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001085 };
1086
Xinliang David Lida195582016-05-10 21:59:52 +00001087 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001088}