blob: d14ab9db7ecdcdc6b0ccb2f44e1709e064d3e6db [file] [log] [blame]
Rong Xuf430ae42015-12-09 18:08:16 +00001//===-- PGOInstrumentation.cpp - MST-based PGO Instrumentation ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements PGO instrumentation using a minimum spanning tree based
11// on the following paper:
12// [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
13// for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
14// Issue 3, pp 313-322
15// The idea of the algorithm based on the fact that for each node (except for
16// the entry and exit), the sum of incoming edge counts equals the sum of
17// outgoing edge counts. The count of edge on spanning tree can be derived from
18// those edges not on the spanning tree. Knuth proves this method instruments
19// the minimum number of edges.
20//
21// The minimal spanning tree here is actually a maximum weight tree -- on-tree
22// edges have higher frequencies (more likely to execute). The idea is to
23// instrument those less frequently executed edges to reduce the runtime
24// overhead of instrumented binaries.
25//
26// This file contains two passes:
27// (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
Rong Xu13b01dc2016-02-10 18:24:45 +000028// count profile, and generates the instrumentation for indirect call
29// profiling.
Rong Xuf430ae42015-12-09 18:08:16 +000030// (2) Pass PGOInstrumentationUse which reads the edge count profile and
Rong Xu13b01dc2016-02-10 18:24:45 +000031// annotates the branch weights. It also reads the indirect call value
32// profiling records and annotate the indirect call instructions.
33//
Rong Xuf430ae42015-12-09 18:08:16 +000034// To get the precise counter information, These two passes need to invoke at
35// the same compilation point (so they see the same IR). For pass
36// PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
37// pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
38// the profile is opened in module level and passed to each PGOUseFunc instance.
39// The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
40// in class FuncPGOInstrumentation.
41//
42// Class PGOEdge represents a CFG edge and some auxiliary information. Class
43// BBInfo contains auxiliary information for each BB. These two classes are used
44// in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
45// class of PGOEdge and BBInfo, respectively. They contains extra data structure
46// used in populating profile counters.
47// The MST implementation is in Class CFGMST (CFGMST.h).
48//
49//===----------------------------------------------------------------------===//
50
Xinliang David Li8aebf442016-05-06 05:49:19 +000051#include "llvm/Transforms/PGOInstrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000052#include "CFGMST.h"
Rong Xuf430ae42015-12-09 18:08:16 +000053#include "llvm/ADT/STLExtras.h"
Rong Xu705f7772016-07-25 18:45:37 +000054#include "llvm/ADT/SmallVector.h"
Rong Xuf430ae42015-12-09 18:08:16 +000055#include "llvm/ADT/Statistic.h"
Rong Xu33c76c02016-02-10 17:18:30 +000056#include "llvm/ADT/Triple.h"
Rong Xuf430ae42015-12-09 18:08:16 +000057#include "llvm/Analysis/BlockFrequencyInfo.h"
58#include "llvm/Analysis/BranchProbabilityInfo.h"
59#include "llvm/Analysis/CFG.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000060#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Xinliang David Licb253ce2017-01-23 18:58:24 +000061#include "llvm/Analysis/LoopInfo.h"
Davide Italiano0c8d26c2017-07-20 20:43:05 +000062#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Rong Xued9fec72016-01-21 18:11:44 +000063#include "llvm/IR/CallSite.h"
Rong Xuf430ae42015-12-09 18:08:16 +000064#include "llvm/IR/DiagnosticInfo.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000065#include "llvm/IR/Dominators.h"
Rong Xu705f7772016-07-25 18:45:37 +000066#include "llvm/IR/GlobalValue.h"
Rong Xuf430ae42015-12-09 18:08:16 +000067#include "llvm/IR/IRBuilder.h"
68#include "llvm/IR/InstIterator.h"
69#include "llvm/IR/Instructions.h"
70#include "llvm/IR/IntrinsicInst.h"
71#include "llvm/IR/MDBuilder.h"
72#include "llvm/IR/Module.h"
73#include "llvm/Pass.h"
74#include "llvm/ProfileData/InstrProfReader.h"
Easwaran Raman5fe04a12016-05-26 22:57:11 +000075#include "llvm/ProfileData/ProfileCommon.h"
Rong Xuf430ae42015-12-09 18:08:16 +000076#include "llvm/Support/BranchProbability.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000077#include "llvm/Support/DOTGraphTraits.h"
Rong Xuf430ae42015-12-09 18:08:16 +000078#include "llvm/Support/Debug.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000079#include "llvm/Support/GraphWriter.h"
Rong Xuf430ae42015-12-09 18:08:16 +000080#include "llvm/Support/JamCRC.h"
Rong Xued9fec72016-01-21 18:11:44 +000081#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +000082#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +000083#include <algorithm>
Rong Xuf430ae42015-12-09 18:08:16 +000084#include <string>
Rong Xu705f7772016-07-25 18:45:37 +000085#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +000086#include <utility>
87#include <vector>
88
89using namespace llvm;
90
91#define DEBUG_TYPE "pgo-instrumentation"
92
93STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +000094STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xu60faea12017-03-16 21:15:48 +000095STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +000096STATISTIC(NumOfPGOEdge, "Number of edges.");
97STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
98STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
99STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
100STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
101STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000102STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +0000103
104// Command line option to specify the file to read profile from. This is
105// mainly used for testing.
106static cl::opt<std::string>
107 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
108 cl::value_desc("filename"),
109 cl::desc("Specify the path of profile data file. This is"
110 "mainly for test purpose."));
111
Rong Xuecdc98f2016-03-04 22:08:44 +0000112// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000113// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000114static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
115 cl::Hidden,
116 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000117
Rong Xuecdc98f2016-03-04 22:08:44 +0000118// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000119// the metadata for a single indirect call callsite.
120static cl::opt<unsigned> MaxNumAnnotations(
121 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
122 cl::desc("Max number of annotations for a single indirect "
123 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000124
Rong Xue60343d2017-03-17 18:07:26 +0000125// Command line option to set the maximum number of value annotations
126// to write to the metadata for a single memop intrinsic.
127static cl::opt<unsigned> MaxNumMemOPAnnotations(
128 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
129 cl::desc("Max number of preicise value annotations for a single memop"
130 "intrinsic"));
131
Rong Xu705f7772016-07-25 18:45:37 +0000132// Command line option to control appending FunctionHash to the name of a COMDAT
133// function. This is to avoid the hash mismatch caused by the preinliner.
134static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000135 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000136 cl::desc("Append function hash to the name of COMDAT function to avoid "
137 "function hash mismatch due to the preinliner"));
138
Rong Xu0698de92016-05-13 17:26:06 +0000139// Command line option to enable/disable the warning about missing profile
140// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000141static cl::opt<bool>
142 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
143 cl::desc("Use this option to turn on/off "
144 "warnings about missing profile data for "
145 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000146
147// Command line option to enable/disable the warning about a hash mismatch in
148// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000149static cl::opt<bool>
150 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
151 cl::desc("Use this option to turn off/on "
152 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000153
Rong Xu20f5df12017-01-11 20:19:41 +0000154// Command line option to enable/disable the warning about a hash mismatch in
155// the profile data for Comdat functions, which often turns out to be false
156// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000157static cl::opt<bool>
158 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
159 cl::Hidden,
160 cl::desc("The option is used to turn on/off "
161 "warnings about hash mismatch for comdat "
162 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000163
Xinliang David Li4ca17332016-09-18 18:34:07 +0000164// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000165static cl::opt<bool>
166 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
167 cl::desc("Use this option to turn on/off SELECT "
168 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000169
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000170// Command line option to turn on CFG dot or text dump of raw profile counts
171static cl::opt<PGOViewCountsType> PGOViewRawCounts(
172 "pgo-view-raw-counts", cl::Hidden,
173 cl::desc("A boolean option to show CFG dag or text "
174 "with raw profile counts from "
175 "profile data. See also option "
176 "-pgo-view-counts. To limit graph "
177 "display to only one function, use "
178 "filtering option -view-bfi-func-name."),
179 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
180 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
181 clEnumValN(PGOVCT_Text, "text", "show in text.")));
Xinliang David Lid289e452017-01-27 19:06:25 +0000182
Rong Xu8e06e802017-03-17 20:51:44 +0000183// Command line option to enable/disable memop intrinsic call.size profiling.
184static cl::opt<bool>
185 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
186 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000187 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000188
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000189// Emit branch probability as optimization remarks.
190static cl::opt<bool>
191 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
192 cl::desc("When this option is on, the annotated "
193 "branch probability will be emitted as "
194 " optimization remarks: -Rpass-analysis="
195 "pgo-instr-use"));
196
Xinliang David Licb253ce2017-01-23 18:58:24 +0000197// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000198// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000199extern cl::opt<PGOViewCountsType> PGOViewCounts;
Xinliang David Licb253ce2017-01-23 18:58:24 +0000200
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000201// Command line option to specify the name of the function for CFG dump
202// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
203extern cl::opt<std::string> ViewBlockFreqFuncName;
204
Rong Xuf430ae42015-12-09 18:08:16 +0000205namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000206
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000207// Return a string describing the branch condition that can be
208// used in static branch probability heuristics:
209std::string getBranchCondString(Instruction *TI) {
210 BranchInst *BI = dyn_cast<BranchInst>(TI);
211 if (!BI || !BI->isConditional())
212 return std::string();
213
214 Value *Cond = BI->getCondition();
215 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
216 if (!CI)
217 return std::string();
218
219 std::string result;
220 raw_string_ostream OS(result);
221 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
222 CI->getOperand(0)->getType()->print(OS, true);
223
224 Value *RHS = CI->getOperand(1);
225 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
226 if (CV) {
227 if (CV->isZero())
228 OS << "_Zero";
229 else if (CV->isOne())
230 OS << "_One";
Craig Topper79ab6432017-07-06 18:39:47 +0000231 else if (CV->isMinusOne())
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000232 OS << "_MinusOne";
233 else
234 OS << "_Const";
235 }
236 OS.flush();
237 return result;
238}
239
Xinliang David Li4ca17332016-09-18 18:34:07 +0000240/// The select instruction visitor plays three roles specified
241/// by the mode. In \c VM_counting mode, it simply counts the number of
242/// select instructions. In \c VM_instrument mode, it inserts code to count
243/// the number times TrueValue of select is taken. In \c VM_annotate mode,
244/// it reads the profile data and annotate the select instruction with metadata.
245enum VisitMode { VM_counting, VM_instrument, VM_annotate };
246class PGOUseFunc;
247
248/// Instruction Visitor class to visit select instructions.
249struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
250 Function &F;
251 unsigned NSIs = 0; // Number of select instructions instrumented.
252 VisitMode Mode = VM_counting; // Visiting mode.
253 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
254 unsigned TotalNumCtrs = 0; // Total number of counters
255 GlobalVariable *FuncNameVar = nullptr;
256 uint64_t FuncHash = 0;
257 PGOUseFunc *UseFunc = nullptr;
258
259 SelectInstVisitor(Function &Func) : F(Func) {}
260
261 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000262 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000263 Mode = VM_counting;
264 visit(Func);
265 }
266 // Visit the IR stream and instrument all select instructions. \p
267 // Ind is a pointer to the counter index variable; \p TotalNC
268 // is the total number of counters; \p FNV is the pointer to the
269 // PGO function name var; \p FHash is the function hash.
270 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
271 GlobalVariable *FNV, uint64_t FHash) {
272 Mode = VM_instrument;
273 CurCtrIdx = Ind;
274 TotalNumCtrs = TotalNC;
275 FuncHash = FHash;
276 FuncNameVar = FNV;
277 visit(Func);
278 }
279
280 // Visit the IR stream and annotate all select instructions.
281 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
282 Mode = VM_annotate;
283 UseFunc = UF;
284 CurCtrIdx = Ind;
285 visit(Func);
286 }
287
288 void instrumentOneSelectInst(SelectInst &SI);
289 void annotateOneSelectInst(SelectInst &SI);
290 // Visit \p SI instruction and perform tasks according to visit mode.
291 void visitSelectInst(SelectInst &SI);
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000292 // Return the number of select instructions. This needs be called after
293 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000294 unsigned getNumOfSelectInsts() const { return NSIs; }
295};
296
Rong Xu60faea12017-03-16 21:15:48 +0000297/// Instruction Visitor class to visit memory intrinsic calls.
298struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
299 Function &F;
300 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
301 VisitMode Mode = VM_counting; // Visiting mode.
302 unsigned CurCtrId = 0; // Current counter index.
303 unsigned TotalNumCtrs = 0; // Total number of counters
304 GlobalVariable *FuncNameVar = nullptr;
305 uint64_t FuncHash = 0;
306 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000307 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000308
309 MemIntrinsicVisitor(Function &Func) : F(Func) {}
310
311 void countMemIntrinsics(Function &Func) {
312 NMemIs = 0;
313 Mode = VM_counting;
314 visit(Func);
315 }
Rong Xue60343d2017-03-17 18:07:26 +0000316
Rong Xu60faea12017-03-16 21:15:48 +0000317 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
318 GlobalVariable *FNV, uint64_t FHash) {
319 Mode = VM_instrument;
320 TotalNumCtrs = TotalNC;
321 FuncHash = FHash;
322 FuncNameVar = FNV;
323 visit(Func);
324 }
325
Rong Xue60343d2017-03-17 18:07:26 +0000326 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
327 Candidates.clear();
328 Mode = VM_annotate;
329 visit(Func);
330 return Candidates;
331 }
332
Rong Xu60faea12017-03-16 21:15:48 +0000333 // Visit the IR stream and annotate all mem intrinsic call instructions.
334 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
335 // Visit \p MI instruction and perform tasks according to visit mode.
336 void visitMemIntrinsic(MemIntrinsic &SI);
337 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
338};
339
Xinliang David Li8aebf442016-05-06 05:49:19 +0000340class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000341public:
342 static char ID;
343
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000344 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000345 initializePGOInstrumentationGenLegacyPassPass(
346 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000347 }
348
Mehdi Amini117296c2016-10-01 02:56:57 +0000349 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000350
351private:
352 bool runOnModule(Module &M) override;
353
354 void getAnalysisUsage(AnalysisUsage &AU) const override {
355 AU.addRequired<BlockFrequencyInfoWrapperPass>();
356 }
357};
358
Xinliang David Lid55827f2016-05-07 05:39:12 +0000359class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000360public:
361 static char ID;
362
363 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000364 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000365 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000366 if (!PGOTestProfileFile.empty())
367 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000368 initializePGOInstrumentationUseLegacyPassPass(
369 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000370 }
371
Mehdi Amini117296c2016-10-01 02:56:57 +0000372 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000373
374private:
375 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000376
Xinliang David Lida195582016-05-10 21:59:52 +0000377 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000378 void getAnalysisUsage(AnalysisUsage &AU) const override {
379 AU.addRequired<BlockFrequencyInfoWrapperPass>();
380 }
381};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000382
Rong Xuf430ae42015-12-09 18:08:16 +0000383} // end anonymous namespace
384
Xinliang David Li8aebf442016-05-06 05:49:19 +0000385char PGOInstrumentationGenLegacyPass::ID = 0;
386INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000387 "PGO instrumentation.", false, false)
388INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
389INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000390INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000391 "PGO instrumentation.", false, false)
392
Xinliang David Li8aebf442016-05-06 05:49:19 +0000393ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
394 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000395}
396
Xinliang David Lid55827f2016-05-07 05:39:12 +0000397char PGOInstrumentationUseLegacyPass::ID = 0;
398INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000399 "Read PGO instrumentation profile.", false, false)
400INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
401INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000402INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000403 "Read PGO instrumentation profile.", false, false)
404
Xinliang David Lid55827f2016-05-07 05:39:12 +0000405ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
406 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000407}
408
409namespace {
410/// \brief An MST based instrumentation for PGO
411///
412/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
413/// in the function level.
414struct PGOEdge {
415 // This class implements the CFG edges. Note the CFG can be a multi-graph.
416 // So there might be multiple edges with same SrcBB and DestBB.
417 const BasicBlock *SrcBB;
418 const BasicBlock *DestBB;
419 uint64_t Weight;
420 bool InMST;
421 bool Removed;
422 bool IsCritical;
423 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
424 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
425 IsCritical(false) {}
426 // Return the information string of an edge.
427 const std::string infoString() const {
428 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
429 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
430 }
431};
432
433// This class stores the auxiliary information for each BB.
434struct BBInfo {
435 BBInfo *Group;
436 uint32_t Index;
437 uint32_t Rank;
438
439 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
440
441 // Return the information string of this object.
442 const std::string infoString() const {
443 return (Twine("Index=") + Twine(Index)).str();
444 }
445};
446
447// This class implements the CFG edges. Note the CFG can be a multi-graph.
448template <class Edge, class BBInfo> class FuncPGOInstrumentation {
449private:
450 Function &F;
451 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000452 void renameComdatFunction();
453 // A map that stores the Comdat group in function F.
454 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000455
456public:
Rong Xua3bbf962017-03-15 18:23:39 +0000457 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000458 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000459 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000460 std::string FuncName;
461 GlobalVariable *FuncNameVar;
462 // CFG hash value for this function.
463 uint64_t FunctionHash;
464
465 // The Minimum Spanning Tree of function CFG.
466 CFGMST<Edge, BBInfo> MST;
467
468 // Give an edge, find the BB that will be instrumented.
469 // Return nullptr if there is no BB to be instrumented.
470 BasicBlock *getInstrBB(Edge *E);
471
472 // Return the auxiliary BB information.
473 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
474
Rong Xua5b57452016-12-02 19:10:29 +0000475 // Return the auxiliary BB information if available.
476 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
477
Rong Xuf430ae42015-12-09 18:08:16 +0000478 // Dump edges and BB information.
479 void dumpInfo(std::string Str = "") const {
480 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000481 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000482 }
483
Rong Xu705f7772016-07-25 18:45:37 +0000484 FuncPGOInstrumentation(
485 Function &Func,
486 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
487 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
488 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000489 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Rong Xu60faea12017-03-16 21:15:48 +0000490 SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000491
492 // This should be done before CFG hash computation.
493 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000494 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000495 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu60faea12017-03-16 21:15:48 +0000496 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Rong Xua3bbf962017-03-15 18:23:39 +0000497 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Rong Xue60343d2017-03-17 18:07:26 +0000498 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000499
Rong Xuf430ae42015-12-09 18:08:16 +0000500 FuncName = getPGOFuncName(F);
501 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000502 if (ComdatMembers.size())
503 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000504 DEBUG(dumpInfo("after CFGMST"));
505
506 NumOfPGOBB += MST.BBInfos.size();
507 for (auto &E : MST.AllEdges) {
508 if (E->Removed)
509 continue;
510 NumOfPGOEdge++;
511 if (!E->InMST)
512 NumOfPGOInstrument++;
513 }
514
515 if (CreateGlobalVar)
516 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000517 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000518
519 // Return the number of profile counters needed for the function.
520 unsigned getNumCounters() {
521 unsigned NumCounters = 0;
522 for (auto &E : this->MST.AllEdges) {
523 if (!E->InMST && !E->Removed)
524 NumCounters++;
525 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000526 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000527 }
Rong Xuf430ae42015-12-09 18:08:16 +0000528};
529
530// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
531// value of each BB in the CFG. The higher 32 bits record the number of edges.
532template <class Edge, class BBInfo>
533void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
534 std::vector<char> Indexes;
535 JamCRC JC;
536 for (auto &BB : F) {
537 const TerminatorInst *TI = BB.getTerminator();
538 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
539 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000540 auto BI = findBBInfo(Succ);
541 if (BI == nullptr)
542 continue;
543 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000544 for (int J = 0; J < 4; J++)
545 Indexes.push_back((char)(Index >> (J * 8)));
546 }
547 }
548 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000549 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000550 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000551 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
Xinliang David Li8e436982017-07-21 21:36:25 +0000552 DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
553 << " CRC = " << JC.getCRC()
554 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
555 << ", Edges = " << MST.AllEdges.size()
556 << ", ICSites = " << ValueSites[IPVK_IndirectCallTarget].size()
557 << ", Hash = " << FunctionHash << "\n";);
Rong Xu705f7772016-07-25 18:45:37 +0000558}
559
560// Check if we can safely rename this Comdat function.
561static bool canRenameComdat(
562 Function &F,
563 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000564 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000565 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000566
567 // FIXME: Current only handle those Comdat groups that only containing one
568 // function and function aliases.
569 // (1) For a Comdat group containing multiple functions, we need to have a
570 // unique postfix based on the hashes for each function. There is a
571 // non-trivial code refactoring to do this efficiently.
572 // (2) Variables can not be renamed, so we can not rename Comdat function in a
573 // group including global vars.
574 Comdat *C = F.getComdat();
575 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
576 if (dyn_cast<GlobalAlias>(CM.second))
577 continue;
578 Function *FM = dyn_cast<Function>(CM.second);
579 if (FM != &F)
580 return false;
581 }
582 return true;
583}
584
585// Append the CFGHash to the Comdat function name.
586template <class Edge, class BBInfo>
587void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
588 if (!canRenameComdat(F, ComdatMembers))
589 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000590 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000591 std::string NewFuncName =
592 Twine(F.getName() + "." + Twine(FunctionHash)).str();
593 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000594 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000595 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
596 Comdat *NewComdat;
597 Module *M = F.getParent();
598 // For AvailableExternallyLinkage functions, change the linkage to
599 // LinkOnceODR and put them into comdat. This is because after renaming, there
600 // is no backup external copy available for the function.
601 if (!F.hasComdat()) {
602 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
603 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
604 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
605 F.setComdat(NewComdat);
606 return;
607 }
608
609 // This function belongs to a single function Comdat group.
610 Comdat *OrigComdat = F.getComdat();
611 std::string NewComdatName =
612 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
613 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
614 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
615
616 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
617 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
618 // For aliases, change the name directly.
619 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000620 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000621 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000622 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000623 continue;
624 }
625 // Must be a function.
626 Function *CF = dyn_cast<Function>(CM.second);
627 assert(CF);
628 CF->setComdat(NewComdat);
629 }
Rong Xuf430ae42015-12-09 18:08:16 +0000630}
631
632// Given a CFG E to be instrumented, find which BB to place the instrumented
633// code. The function will split the critical edge if necessary.
634template <class Edge, class BBInfo>
635BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
636 if (E->InMST || E->Removed)
637 return nullptr;
638
639 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
640 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
641 // For a fake edge, instrument the real BB.
642 if (SrcBB == nullptr)
643 return DestBB;
644 if (DestBB == nullptr)
645 return SrcBB;
646
647 // Instrument the SrcBB if it has a single successor,
648 // otherwise, the DestBB if this is not a critical edge.
649 TerminatorInst *TI = SrcBB->getTerminator();
650 if (TI->getNumSuccessors() <= 1)
651 return SrcBB;
652 if (!E->IsCritical)
653 return DestBB;
654
655 // For a critical edge, we have to split. Instrument the newly
656 // created BB.
657 NumOfPGOSplit++;
658 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
659 << getBBInfo(DestBB).Index << "\n");
660 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
661 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
662 assert(InstrBB && "Critical edge is not split");
663
664 E->Removed = true;
665 return InstrBB;
666}
667
Rong Xued9fec72016-01-21 18:11:44 +0000668// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000669// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000670static void instrumentOneFunc(
671 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
672 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000673 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
674 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000675 unsigned NumCounters = FuncInfo.getNumCounters();
676
Rong Xuf430ae42015-12-09 18:08:16 +0000677 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000678 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000679 for (auto &E : FuncInfo.MST.AllEdges) {
680 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
681 if (!InstrBB)
682 continue;
683
684 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
685 assert(Builder.GetInsertPoint() != InstrBB->end() &&
686 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000687 Builder.CreateCall(
688 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
689 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
690 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
691 Builder.getInt32(I++)});
692 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000693
694 // Now instrument select instructions:
695 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
696 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000697 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000698
699 if (DisableValueProfiling)
700 return;
701
702 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000703 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000704 CallSite CS(I);
705 Value *Callee = CS.getCalledValue();
706 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
707 << NumIndirectCallSites << "\n");
708 IRBuilder<> Builder(I);
709 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
710 "Cannot get the Instrumentation point");
711 Builder.CreateCall(
712 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
713 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
714 Builder.getInt64(FuncInfo.FunctionHash),
715 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000716 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000717 Builder.getInt32(NumIndirectCallSites++)});
718 }
719 NumOfPGOICall += NumIndirectCallSites;
Rong Xu60faea12017-03-16 21:15:48 +0000720
721 // Now instrument memop intrinsic calls.
722 FuncInfo.MIVisitor.instrumentMemIntrinsics(
723 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000724}
725
726// This class represents a CFG edge in profile use compilation.
727struct PGOUseEdge : public PGOEdge {
728 bool CountValid;
729 uint64_t CountValue;
730 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
731 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
732
733 // Set edge count value
734 void setEdgeCount(uint64_t Value) {
735 CountValue = Value;
736 CountValid = true;
737 }
738
739 // Return the information string for this object.
740 const std::string infoString() const {
741 if (!CountValid)
742 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000743 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
744 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000745 }
746};
747
748typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
749
750// This class stores the auxiliary information for each BB.
751struct UseBBInfo : public BBInfo {
752 uint64_t CountValue;
753 bool CountValid;
754 int32_t UnknownCountInEdge;
755 int32_t UnknownCountOutEdge;
756 DirectEdges InEdges;
757 DirectEdges OutEdges;
758 UseBBInfo(unsigned IX)
759 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
760 UnknownCountOutEdge(0) {}
761 UseBBInfo(unsigned IX, uint64_t C)
762 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
763 UnknownCountOutEdge(0) {}
764
765 // Set the profile count value for this BB.
766 void setBBInfoCount(uint64_t Value) {
767 CountValue = Value;
768 CountValid = true;
769 }
770
771 // Return the information string of this object.
772 const std::string infoString() const {
773 if (!CountValid)
774 return BBInfo::infoString();
775 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
776 }
777};
778
779// Sum up the count values for all the edges.
780static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
781 uint64_t Total = 0;
782 for (auto &E : Edges) {
783 if (E->Removed)
784 continue;
785 Total += E->CountValue;
786 }
787 return Total;
788}
789
790class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000791public:
Rong Xu705f7772016-07-25 18:45:37 +0000792 PGOUseFunc(Function &Func, Module *Modu,
793 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
794 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000795 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000796 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Rong Xu33308f92016-10-25 21:47:24 +0000797 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000798
799 // Read counts for the instrumented BB from profile.
800 bool readCounters(IndexedInstrProfReader *PGOReader);
801
802 // Populate the counts for all BBs.
803 void populateCounters();
804
805 // Set the branch weights based on the count values.
806 void setBranchWeights();
807
Rong Xua3bbf962017-03-15 18:23:39 +0000808 // Annotate the value profile call sites all all value kind.
809 void annotateValueSites();
810
811 // Annotate the value profile call sites for one value kind.
812 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000813
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000814 // The hotness of the function from the profile count.
815 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
816
817 // Return the function hotness from the profile.
818 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
819
Rong Xu705f7772016-07-25 18:45:37 +0000820 // Return the function hash.
821 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000822 // Return the profile record for this function;
823 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
824
Xinliang David Li4ca17332016-09-18 18:34:07 +0000825 // Return the auxiliary BB information.
826 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
827 return FuncInfo.getBBInfo(BB);
828 }
829
Rong Xua5b57452016-12-02 19:10:29 +0000830 // Return the auxiliary BB information if available.
831 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
832 return FuncInfo.findBBInfo(BB);
833 }
834
Xinliang David Lid289e452017-01-27 19:06:25 +0000835 Function &getFunc() const { return F; }
836
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000837 void dumpInfo(std::string Str = "") const {
838 FuncInfo.dumpInfo(Str);
839 }
840
Rong Xuf430ae42015-12-09 18:08:16 +0000841private:
842 Function &F;
843 Module *M;
844 // This member stores the shared information with class PGOGenFunc.
845 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
846
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000847 // The maximum count value in the profile. This is only used in PGO use
848 // compilation.
849 uint64_t ProgramMaxCount;
850
Rong Xu33308f92016-10-25 21:47:24 +0000851 // Position of counter that remains to be read.
852 uint32_t CountPosition;
853
854 // Total size of the profile count for this function.
855 uint32_t ProfileCountSize;
856
Rong Xu13b01dc2016-02-10 18:24:45 +0000857 // ProfileRecord for this function.
858 InstrProfRecord ProfileRecord;
859
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000860 // Function hotness info derived from profile.
861 FuncFreqAttr FreqAttr;
862
Rong Xuf430ae42015-12-09 18:08:16 +0000863 // Find the Instrumented BB and set the value.
864 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
865
866 // Set the edge counter value for the unknown edge -- there should be only
867 // one unknown edge.
868 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
869
870 // Return FuncName string;
871 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000872
873 // Set the hot/cold inline hints based on the count values.
874 // FIXME: This function should be removed once the functionality in
875 // the inliner is implemented.
876 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
877 if (ProgramMaxCount == 0)
878 return;
879 // Threshold of the hot functions.
880 const BranchProbability HotFunctionThreshold(1, 100);
881 // Threshold of the cold functions.
882 const BranchProbability ColdFunctionThreshold(2, 10000);
883 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
884 FreqAttr = FFA_Hot;
885 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
886 FreqAttr = FFA_Cold;
887 }
Rong Xuf430ae42015-12-09 18:08:16 +0000888};
889
890// Visit all the edges and assign the count value for the instrumented
891// edges and the BB.
892void PGOUseFunc::setInstrumentedCounts(
893 const std::vector<uint64_t> &CountFromProfile) {
894
Xinliang David Lid1197612016-08-01 20:25:06 +0000895 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000896 // Use a worklist as we will update the vector during the iteration.
897 std::vector<PGOUseEdge *> WorkList;
898 for (auto &E : FuncInfo.MST.AllEdges)
899 WorkList.push_back(E.get());
900
901 uint32_t I = 0;
902 for (auto &E : WorkList) {
903 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
904 if (!InstrBB)
905 continue;
906 uint64_t CountValue = CountFromProfile[I++];
907 if (!E->Removed) {
908 getBBInfo(InstrBB).setBBInfoCount(CountValue);
909 E->setEdgeCount(CountValue);
910 continue;
911 }
912
913 // Need to add two new edges.
914 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
915 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
916 // Add new edge of SrcBB->InstrBB.
917 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
918 NewEdge.setEdgeCount(CountValue);
919 // Add new edge of InstrBB->DestBB.
920 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
921 NewEdge1.setEdgeCount(CountValue);
922 NewEdge1.InMST = true;
923 getBBInfo(InstrBB).setBBInfoCount(CountValue);
924 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000925 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000926 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000927}
928
929// Set the count value for the unknown edge. There should be one and only one
930// unknown edge in Edges vector.
931void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
932 for (auto &E : Edges) {
933 if (E->CountValid)
934 continue;
935 E->setEdgeCount(Value);
936
937 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
938 getBBInfo(E->DestBB).UnknownCountInEdge--;
939 return;
940 }
941 llvm_unreachable("Cannot find the unknown count edge");
942}
943
944// Read the profile from ProfileFileName and assign the value to the
945// instrumented BB and the edges. This function also updates ProgramMaxCount.
946// Return true if the profile are successfully read, and false on errors.
947bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
948 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000949 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000950 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000951 if (Error E = Result.takeError()) {
952 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
953 auto Err = IPE.get();
954 bool SkipWarning = false;
955 if (Err == instrprof_error::unknown_function) {
956 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000957 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000958 } else if (Err == instrprof_error::hash_mismatch ||
959 Err == instrprof_error::malformed) {
960 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +0000961 SkipWarning =
962 NoPGOWarnMismatch ||
963 (NoPGOWarnMismatchComdat &&
964 (F.hasComdat() ||
965 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000966 }
Rong Xuf430ae42015-12-09 18:08:16 +0000967
Vedant Kumar9152fd12016-05-19 03:54:45 +0000968 if (SkipWarning)
969 return;
970
971 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
972 Ctx.diagnose(
973 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
974 });
Rong Xuf430ae42015-12-09 18:08:16 +0000975 return false;
976 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000977 ProfileRecord = std::move(Result.get());
978 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000979
980 NumOfPGOFunc++;
981 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
982 uint64_t ValueSum = 0;
983 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
984 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
985 ValueSum += CountFromProfile[I];
986 }
987
988 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
989
990 getBBInfo(nullptr).UnknownCountOutEdge = 2;
991 getBBInfo(nullptr).UnknownCountInEdge = 2;
992
993 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000994 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000995 return true;
996}
997
998// Populate the counters from instrumented BBs to all BBs.
999// In the end of this operation, all BBs should have a valid count value.
1000void PGOUseFunc::populateCounters() {
1001 // First set up Count variable for all BBs.
1002 for (auto &E : FuncInfo.MST.AllEdges) {
1003 if (E->Removed)
1004 continue;
1005
1006 const BasicBlock *SrcBB = E->SrcBB;
1007 const BasicBlock *DestBB = E->DestBB;
1008 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1009 UseBBInfo &DestInfo = getBBInfo(DestBB);
1010 SrcInfo.OutEdges.push_back(E.get());
1011 DestInfo.InEdges.push_back(E.get());
1012 SrcInfo.UnknownCountOutEdge++;
1013 DestInfo.UnknownCountInEdge++;
1014
1015 if (!E->CountValid)
1016 continue;
1017 DestInfo.UnknownCountInEdge--;
1018 SrcInfo.UnknownCountOutEdge--;
1019 }
1020
1021 bool Changes = true;
1022 unsigned NumPasses = 0;
1023 while (Changes) {
1024 NumPasses++;
1025 Changes = false;
1026
1027 // For efficient traversal, it's better to start from the end as most
1028 // of the instrumented edges are at the end.
1029 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +00001030 UseBBInfo *Count = findBBInfo(&BB);
1031 if (Count == nullptr)
1032 continue;
1033 if (!Count->CountValid) {
1034 if (Count->UnknownCountOutEdge == 0) {
1035 Count->CountValue = sumEdgeCount(Count->OutEdges);
1036 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001037 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +00001038 } else if (Count->UnknownCountInEdge == 0) {
1039 Count->CountValue = sumEdgeCount(Count->InEdges);
1040 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001041 Changes = true;
1042 }
1043 }
Rong Xua5b57452016-12-02 19:10:29 +00001044 if (Count->CountValid) {
1045 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001046 uint64_t Total = 0;
1047 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1048 // If the one of the successor block can early terminate (no-return),
1049 // we can end up with situation where out edge sum count is larger as
1050 // the source BB's count is collected by a post-dominated block.
1051 if (Count->CountValue > OutSum)
1052 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +00001053 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001054 Changes = true;
1055 }
Rong Xua5b57452016-12-02 19:10:29 +00001056 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001057 uint64_t Total = 0;
1058 uint64_t InSum = sumEdgeCount(Count->InEdges);
1059 if (Count->CountValue > InSum)
1060 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001061 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001062 Changes = true;
1063 }
1064 }
1065 }
1066 }
1067
1068 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001069#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001070 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001071 for (auto &BB : F) {
1072 auto BI = findBBInfo(&BB);
1073 if (BI == nullptr)
1074 continue;
1075 assert(BI->CountValid && "BB count is not valid");
1076 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001077#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001078 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +00001079 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001080 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001081 for (auto &BB : F) {
1082 auto BI = findBBInfo(&BB);
1083 if (BI == nullptr)
1084 continue;
1085 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1086 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001087 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001088
Rong Xu33308f92016-10-25 21:47:24 +00001089 // Now annotate select instructions
1090 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1091 assert(CountPosition == ProfileCountSize);
1092
Rong Xuf430ae42015-12-09 18:08:16 +00001093 DEBUG(FuncInfo.dumpInfo("after reading profile."));
1094}
1095
1096// Assign the scaled count values to the BB with multiple out edges.
1097void PGOUseFunc::setBranchWeights() {
1098 // Generate MD_prof metadata for every branch instruction.
1099 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001100 for (auto &BB : F) {
1101 TerminatorInst *TI = BB.getTerminator();
1102 if (TI->getNumSuccessors() < 2)
1103 continue;
Rong Xu15848e52017-08-23 21:36:02 +00001104 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1105 isa<IndirectBrInst>(TI)))
Rong Xuf430ae42015-12-09 18:08:16 +00001106 continue;
1107 if (getBBInfo(&BB).CountValue == 0)
1108 continue;
1109
1110 // We have a non-zero Branch BB.
1111 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1112 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001113 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001114 uint64_t MaxCount = 0;
1115 for (unsigned s = 0; s < Size; s++) {
1116 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1117 const BasicBlock *SrcBB = E->SrcBB;
1118 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001119 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001120 continue;
1121 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1122 uint64_t EdgeCount = E->CountValue;
1123 if (EdgeCount > MaxCount)
1124 MaxCount = EdgeCount;
1125 EdgeCounts[SuccNum] = EdgeCount;
1126 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001127 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001128 }
1129}
Rong Xu13b01dc2016-02-10 18:24:45 +00001130
Xinliang David Li4ca17332016-09-18 18:34:07 +00001131void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1132 Module *M = F.getParent();
1133 IRBuilder<> Builder(&SI);
1134 Type *Int64Ty = Builder.getInt64Ty();
1135 Type *I8PtrTy = Builder.getInt8PtrTy();
1136 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1137 Builder.CreateCall(
1138 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1139 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001140 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1141 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001142 ++(*CurCtrIdx);
1143}
1144
1145void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1146 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1147 assert(*CurCtrIdx < CountFromProfile.size() &&
1148 "Out of bound access of counters");
1149 uint64_t SCounts[2];
1150 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1151 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001152 uint64_t TotalCount = 0;
1153 auto BI = UseFunc->findBBInfo(SI.getParent());
1154 if (BI != nullptr)
1155 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001156 // False Count
1157 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1158 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001159 if (MaxCount)
1160 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001161}
1162
1163void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1164 if (!PGOInstrSelect)
1165 return;
1166 // FIXME: do not handle this yet.
1167 if (SI.getCondition()->getType()->isVectorTy())
1168 return;
1169
Xinliang David Li4ca17332016-09-18 18:34:07 +00001170 switch (Mode) {
1171 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001172 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001173 return;
1174 case VM_instrument:
1175 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001176 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001177 case VM_annotate:
1178 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001179 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001180 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001181
1182 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001183}
1184
Rong Xu60faea12017-03-16 21:15:48 +00001185void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1186 Module *M = F.getParent();
1187 IRBuilder<> Builder(&MI);
1188 Type *Int64Ty = Builder.getInt64Ty();
1189 Type *I8PtrTy = Builder.getInt8PtrTy();
1190 Value *Length = MI.getLength();
1191 assert(!dyn_cast<ConstantInt>(Length));
1192 Builder.CreateCall(
1193 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
1194 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Ana Pazosf731bde2017-06-19 20:04:33 +00001195 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
Rong Xu60faea12017-03-16 21:15:48 +00001196 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1197 ++CurCtrId;
1198}
1199
1200void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1201 if (!PGOInstrMemOP)
1202 return;
1203 Value *Length = MI.getLength();
1204 // Not instrument constant length calls.
1205 if (dyn_cast<ConstantInt>(Length))
1206 return;
1207
1208 switch (Mode) {
1209 case VM_counting:
1210 NMemIs++;
1211 return;
1212 case VM_instrument:
1213 instrumentOneMemIntrinsic(MI);
1214 return;
1215 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001216 Candidates.push_back(&MI);
1217 return;
Rong Xu60faea12017-03-16 21:15:48 +00001218 }
1219 llvm_unreachable("Unknown visiting mode");
1220}
1221
Rong Xua3bbf962017-03-15 18:23:39 +00001222// Traverse all valuesites and annotate the instructions for all value kind.
1223void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001224 if (DisableValueProfiling)
1225 return;
1226
Rong Xu8e8fe852016-04-01 16:43:30 +00001227 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001228 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001229
Rong Xua3bbf962017-03-15 18:23:39 +00001230 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001231 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001232}
1233
1234// Annotate the instructions for a specific value kind.
1235void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1236 unsigned ValueSiteIndex = 0;
1237 auto &ValueSites = FuncInfo.ValueSites[Kind];
1238 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1239 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001240 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001241 Ctx.diagnose(DiagnosticInfoPGOProfile(
1242 M->getName().data(),
1243 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1244 " in " + F.getName().str(),
1245 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001246 return;
1247 }
1248
Rong Xua3bbf962017-03-15 18:23:39 +00001249 for (auto &I : ValueSites) {
1250 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1251 << "): Index = " << ValueSiteIndex << " out of "
1252 << NumValueSites << "\n");
1253 annotateValueSite(*M, *I, ProfileRecord,
1254 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001255 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1256 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001257 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001258 }
1259}
Rong Xuf430ae42015-12-09 18:08:16 +00001260} // end anonymous namespace
1261
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001262// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001263// aware this is an ir_level profile so it can set the version flag.
1264static void createIRLevelProfileFlagVariable(Module &M) {
1265 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1266 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001267 auto IRLevelVersionVariable = new GlobalVariable(
1268 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1269 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001270 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001271 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1272 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001273 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001274 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001275 else
Rong Xu9e926e82016-02-29 19:16:04 +00001276 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001277 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001278}
1279
Rong Xu705f7772016-07-25 18:45:37 +00001280// Collect the set of members for each Comdat in module M and store
1281// in ComdatMembers.
1282static void collectComdatMembers(
1283 Module &M,
1284 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1285 if (!DoComdatRenaming)
1286 return;
1287 for (Function &F : M)
1288 if (Comdat *C = F.getComdat())
1289 ComdatMembers.insert(std::make_pair(C, &F));
1290 for (GlobalVariable &GV : M.globals())
1291 if (Comdat *C = GV.getComdat())
1292 ComdatMembers.insert(std::make_pair(C, &GV));
1293 for (GlobalAlias &GA : M.aliases())
1294 if (Comdat *C = GA.getComdat())
1295 ComdatMembers.insert(std::make_pair(C, &GA));
1296}
1297
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001298static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001299 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1300 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001301 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001302 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1303 collectComdatMembers(M, ComdatMembers);
1304
Rong Xuf430ae42015-12-09 18:08:16 +00001305 for (auto &F : M) {
1306 if (F.isDeclaration())
1307 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001308 auto *BPI = LookupBPI(F);
1309 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001310 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001311 }
1312 return true;
1313}
1314
Xinliang David Li8aebf442016-05-06 05:49:19 +00001315bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001316 if (skipModule(M))
1317 return false;
1318
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001319 auto LookupBPI = [this](Function &F) {
1320 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001321 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001322 auto LookupBFI = [this](Function &F) {
1323 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001324 };
1325 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1326}
1327
Xinliang David Li8aebf442016-05-06 05:49:19 +00001328PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001329 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001330
1331 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001332 auto LookupBPI = [&FAM](Function &F) {
1333 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001334 };
1335
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001336 auto LookupBFI = [&FAM](Function &F) {
1337 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001338 };
1339
1340 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1341 return PreservedAnalyses::all();
1342
1343 return PreservedAnalyses::none();
1344}
1345
Xinliang David Lida195582016-05-10 21:59:52 +00001346static bool annotateAllFunctions(
1347 Module &M, StringRef ProfileFileName,
1348 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001349 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001350 DEBUG(dbgs() << "Read in profile counters: ");
1351 auto &Ctx = M.getContext();
1352 // Read the counter array from file.
1353 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001354 if (Error E = ReaderOrErr.takeError()) {
1355 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1356 Ctx.diagnose(
1357 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1358 });
Rong Xuf430ae42015-12-09 18:08:16 +00001359 return false;
1360 }
1361
Xinliang David Lida195582016-05-10 21:59:52 +00001362 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1363 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001364 if (!PGOReader) {
1365 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001366 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001367 return false;
1368 }
Rong Xu33c76c02016-02-10 17:18:30 +00001369 // TODO: might need to change the warning once the clang option is finalized.
1370 if (!PGOReader->isIRLevelProfile()) {
1371 Ctx.diagnose(DiagnosticInfoPGOProfile(
1372 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1373 return false;
1374 }
1375
Rong Xu705f7772016-07-25 18:45:37 +00001376 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1377 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001378 std::vector<Function *> HotFunctions;
1379 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001380 for (auto &F : M) {
1381 if (F.isDeclaration())
1382 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001383 auto *BPI = LookupBPI(F);
1384 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001385 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001386 if (!Func.readCounters(PGOReader.get()))
1387 continue;
1388 Func.populateCounters();
1389 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001390 Func.annotateValueSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001391 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1392 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001393 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001394 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1395 HotFunctions.push_back(&F);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001396 if (PGOViewCounts != PGOVCT_None &&
1397 (ViewBlockFreqFuncName.empty() ||
1398 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001399 LoopInfo LI{DominatorTree(F)};
1400 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1401 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1402 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1403 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001404 if (PGOViewCounts == PGOVCT_Graph)
1405 NewBFI->view();
1406 else if (PGOViewCounts == PGOVCT_Text) {
1407 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1408 NewBFI->print(dbgs());
1409 }
Xinliang David Licb253ce2017-01-23 18:58:24 +00001410 }
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001411 if (PGOViewRawCounts != PGOVCT_None &&
1412 (ViewBlockFreqFuncName.empty() ||
1413 F.getName().equals(ViewBlockFreqFuncName))) {
1414 if (PGOViewRawCounts == PGOVCT_Graph)
1415 if (ViewBlockFreqFuncName.empty())
1416 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1417 else
1418 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1419 else if (PGOViewRawCounts == PGOVCT_Text) {
1420 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1421 Func.dumpInfo();
1422 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001423 }
Rong Xuf430ae42015-12-09 18:08:16 +00001424 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001425 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001426 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001427 // We have to apply these attributes at the end because their presence
1428 // can affect the BranchProbabilityInfo of any callers, resulting in an
1429 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001430 for (auto &F : HotFunctions) {
1431 F->addFnAttr(llvm::Attribute::InlineHint);
1432 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1433 << "\n");
1434 }
1435 for (auto &F : ColdFunctions) {
1436 F->addFnAttr(llvm::Attribute::Cold);
1437 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1438 }
Rong Xuf430ae42015-12-09 18:08:16 +00001439 return true;
1440}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001441
Xinliang David Lida195582016-05-10 21:59:52 +00001442PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001443 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001444 if (!PGOTestProfileFile.empty())
1445 ProfileFileName = PGOTestProfileFile;
1446}
1447
1448PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001449 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001450
1451 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1452 auto LookupBPI = [&FAM](Function &F) {
1453 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1454 };
1455
1456 auto LookupBFI = [&FAM](Function &F) {
1457 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1458 };
1459
1460 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1461 return PreservedAnalyses::all();
1462
1463 return PreservedAnalyses::none();
1464}
1465
Xinliang David Lid55827f2016-05-07 05:39:12 +00001466bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1467 if (skipModule(M))
1468 return false;
1469
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001470 auto LookupBPI = [this](Function &F) {
1471 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001472 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001473 auto LookupBFI = [this](Function &F) {
1474 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001475 };
1476
Xinliang David Lida195582016-05-10 21:59:52 +00001477 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001478}
Xinliang David Lid289e452017-01-27 19:06:25 +00001479
1480namespace llvm {
Rong Xu48596b62017-04-04 16:42:20 +00001481void setProfMetadata(Module *M, Instruction *TI, ArrayRef<uint64_t> EdgeCounts,
1482 uint64_t MaxCount) {
1483 MDBuilder MDB(M->getContext());
1484 assert(MaxCount > 0 && "Bad max count");
1485 uint64_t Scale = calculateCountScale(MaxCount);
1486 SmallVector<unsigned, 4> Weights;
1487 for (const auto &ECI : EdgeCounts)
1488 Weights.push_back(scaleBranchCount(ECI, Scale));
1489
1490 DEBUG(dbgs() << "Weight is: ";
1491 for (const auto &W : Weights) { dbgs() << W << " "; }
1492 dbgs() << "\n";);
1493 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001494 if (EmitBranchProbability) {
1495 std::string BrCondStr = getBranchCondString(TI);
1496 if (BrCondStr.empty())
1497 return;
1498
1499 unsigned WSum =
1500 std::accumulate(Weights.begin(), Weights.end(), 0,
1501 [](unsigned w1, unsigned w2) { return w1 + w2; });
1502 uint64_t TotalCount =
1503 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0,
1504 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1505 BranchProbability BP(Weights[0], WSum);
1506 std::string BranchProbStr;
1507 raw_string_ostream OS(BranchProbStr);
1508 OS << BP;
1509 OS << " (total count : " << TotalCount << ")";
1510 OS.flush();
1511 Function *F = TI->getParent()->getParent();
Davide Italiano0c8d26c2017-07-20 20:43:05 +00001512 OptimizationRemarkEmitter ORE(F);
1513 ORE.emit(OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1514 << BrCondStr << " is true with probability : " << BranchProbStr);
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001515 }
Rong Xu48596b62017-04-04 16:42:20 +00001516}
1517
Xinliang David Lid289e452017-01-27 19:06:25 +00001518template <> struct GraphTraits<PGOUseFunc *> {
1519 typedef const BasicBlock *NodeRef;
1520 typedef succ_const_iterator ChildIteratorType;
1521 typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1522
1523 static NodeRef getEntryNode(const PGOUseFunc *G) {
1524 return &G->getFunc().front();
1525 }
1526 static ChildIteratorType child_begin(const NodeRef N) {
1527 return succ_begin(N);
1528 }
1529 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1530 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1531 return nodes_iterator(G->getFunc().begin());
1532 }
1533 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1534 return nodes_iterator(G->getFunc().end());
1535 }
1536};
1537
Xinliang David Li6144a592017-02-03 21:57:51 +00001538static std::string getSimpleNodeName(const BasicBlock *Node) {
1539 if (!Node->getName().empty())
1540 return Node->getName();
1541
1542 std::string SimpleNodeName;
1543 raw_string_ostream OS(SimpleNodeName);
1544 Node->printAsOperand(OS, false);
1545 return OS.str();
1546}
1547
Xinliang David Lid289e452017-01-27 19:06:25 +00001548template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1549 explicit DOTGraphTraits(bool isSimple = false)
1550 : DefaultDOTGraphTraits(isSimple) {}
1551
1552 static std::string getGraphName(const PGOUseFunc *G) {
1553 return G->getFunc().getName();
1554 }
1555
1556 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1557 std::string Result;
1558 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001559
1560 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001561 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001562 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001563 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001564 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001565 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001566 OS << "Unknown\\l";
1567
1568 if (!PGOInstrSelect)
1569 return Result;
1570
1571 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1572 auto *I = &*BI;
1573 if (!isa<SelectInst>(I))
1574 continue;
1575 // Display scaled counts for SELECT instruction:
1576 OS << "SELECT : { T = ";
1577 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001578 bool HasProf = I->extractProfMetadata(TC, FC);
1579 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001580 OS << "Unknown, F = Unknown }\\l";
1581 else
1582 OS << TC << ", F = " << FC << " }\\l";
1583 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001584 return Result;
1585 }
1586};
Rong Xu0a2a1312017-03-09 19:08:55 +00001587} // namespace llvm