blob: ef955f17bfa9eea2dcfb67927ea9e8a60f48b99b [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
Xinliang David Lid289e452017-01-27 19:06:25 +0000170// Command line option to turn on CFG dot dump of raw profile counts
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000171static cl::opt<bool>
172 PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden,
173 cl::desc("A boolean option to show CFG dag "
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."));
Xinliang David Lid289e452017-01-27 19:06:25 +0000179
Rong Xu8e06e802017-03-17 20:51:44 +0000180// Command line option to enable/disable memop intrinsic call.size profiling.
181static cl::opt<bool>
182 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
183 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000184 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000185
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000186// Emit branch probability as optimization remarks.
187static cl::opt<bool>
188 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
189 cl::desc("When this option is on, the annotated "
190 "branch probability will be emitted as "
191 " optimization remarks: -Rpass-analysis="
192 "pgo-instr-use"));
193
Xinliang David Licb253ce2017-01-23 18:58:24 +0000194// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000195// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Xinliang David Licb253ce2017-01-23 18:58:24 +0000196extern cl::opt<bool> PGOViewCounts;
197
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000198// Command line option to specify the name of the function for CFG dump
199// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
200extern cl::opt<std::string> ViewBlockFreqFuncName;
201
Rong Xuf430ae42015-12-09 18:08:16 +0000202namespace {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000203
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000204// Return a string describing the branch condition that can be
205// used in static branch probability heuristics:
206std::string getBranchCondString(Instruction *TI) {
207 BranchInst *BI = dyn_cast<BranchInst>(TI);
208 if (!BI || !BI->isConditional())
209 return std::string();
210
211 Value *Cond = BI->getCondition();
212 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
213 if (!CI)
214 return std::string();
215
216 std::string result;
217 raw_string_ostream OS(result);
218 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
219 CI->getOperand(0)->getType()->print(OS, true);
220
221 Value *RHS = CI->getOperand(1);
222 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
223 if (CV) {
224 if (CV->isZero())
225 OS << "_Zero";
226 else if (CV->isOne())
227 OS << "_One";
Craig Topper79ab6432017-07-06 18:39:47 +0000228 else if (CV->isMinusOne())
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000229 OS << "_MinusOne";
230 else
231 OS << "_Const";
232 }
233 OS.flush();
234 return result;
235}
236
Xinliang David Li4ca17332016-09-18 18:34:07 +0000237/// The select instruction visitor plays three roles specified
238/// by the mode. In \c VM_counting mode, it simply counts the number of
239/// select instructions. In \c VM_instrument mode, it inserts code to count
240/// the number times TrueValue of select is taken. In \c VM_annotate mode,
241/// it reads the profile data and annotate the select instruction with metadata.
242enum VisitMode { VM_counting, VM_instrument, VM_annotate };
243class PGOUseFunc;
244
245/// Instruction Visitor class to visit select instructions.
246struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
247 Function &F;
248 unsigned NSIs = 0; // Number of select instructions instrumented.
249 VisitMode Mode = VM_counting; // Visiting mode.
250 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
251 unsigned TotalNumCtrs = 0; // Total number of counters
252 GlobalVariable *FuncNameVar = nullptr;
253 uint64_t FuncHash = 0;
254 PGOUseFunc *UseFunc = nullptr;
255
256 SelectInstVisitor(Function &Func) : F(Func) {}
257
258 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000259 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000260 Mode = VM_counting;
261 visit(Func);
262 }
263 // Visit the IR stream and instrument all select instructions. \p
264 // Ind is a pointer to the counter index variable; \p TotalNC
265 // is the total number of counters; \p FNV is the pointer to the
266 // PGO function name var; \p FHash is the function hash.
267 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
268 GlobalVariable *FNV, uint64_t FHash) {
269 Mode = VM_instrument;
270 CurCtrIdx = Ind;
271 TotalNumCtrs = TotalNC;
272 FuncHash = FHash;
273 FuncNameVar = FNV;
274 visit(Func);
275 }
276
277 // Visit the IR stream and annotate all select instructions.
278 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
279 Mode = VM_annotate;
280 UseFunc = UF;
281 CurCtrIdx = Ind;
282 visit(Func);
283 }
284
285 void instrumentOneSelectInst(SelectInst &SI);
286 void annotateOneSelectInst(SelectInst &SI);
287 // Visit \p SI instruction and perform tasks according to visit mode.
288 void visitSelectInst(SelectInst &SI);
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000289 // Return the number of select instructions. This needs be called after
290 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000291 unsigned getNumOfSelectInsts() const { return NSIs; }
292};
293
Rong Xu60faea12017-03-16 21:15:48 +0000294/// Instruction Visitor class to visit memory intrinsic calls.
295struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
296 Function &F;
297 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
298 VisitMode Mode = VM_counting; // Visiting mode.
299 unsigned CurCtrId = 0; // Current counter index.
300 unsigned TotalNumCtrs = 0; // Total number of counters
301 GlobalVariable *FuncNameVar = nullptr;
302 uint64_t FuncHash = 0;
303 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000304 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000305
306 MemIntrinsicVisitor(Function &Func) : F(Func) {}
307
308 void countMemIntrinsics(Function &Func) {
309 NMemIs = 0;
310 Mode = VM_counting;
311 visit(Func);
312 }
Rong Xue60343d2017-03-17 18:07:26 +0000313
Rong Xu60faea12017-03-16 21:15:48 +0000314 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
315 GlobalVariable *FNV, uint64_t FHash) {
316 Mode = VM_instrument;
317 TotalNumCtrs = TotalNC;
318 FuncHash = FHash;
319 FuncNameVar = FNV;
320 visit(Func);
321 }
322
Rong Xue60343d2017-03-17 18:07:26 +0000323 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
324 Candidates.clear();
325 Mode = VM_annotate;
326 visit(Func);
327 return Candidates;
328 }
329
Rong Xu60faea12017-03-16 21:15:48 +0000330 // Visit the IR stream and annotate all mem intrinsic call instructions.
331 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
332 // Visit \p MI instruction and perform tasks according to visit mode.
333 void visitMemIntrinsic(MemIntrinsic &SI);
334 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
335};
336
Xinliang David Li8aebf442016-05-06 05:49:19 +0000337class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000338public:
339 static char ID;
340
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000341 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000342 initializePGOInstrumentationGenLegacyPassPass(
343 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000344 }
345
Mehdi Amini117296c2016-10-01 02:56:57 +0000346 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000347
348private:
349 bool runOnModule(Module &M) override;
350
351 void getAnalysisUsage(AnalysisUsage &AU) const override {
352 AU.addRequired<BlockFrequencyInfoWrapperPass>();
353 }
354};
355
Xinliang David Lid55827f2016-05-07 05:39:12 +0000356class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000357public:
358 static char ID;
359
360 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000361 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000362 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000363 if (!PGOTestProfileFile.empty())
364 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000365 initializePGOInstrumentationUseLegacyPassPass(
366 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000367 }
368
Mehdi Amini117296c2016-10-01 02:56:57 +0000369 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000370
371private:
372 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000373
Xinliang David Lida195582016-05-10 21:59:52 +0000374 bool runOnModule(Module &M) override;
Rong Xuf430ae42015-12-09 18:08:16 +0000375 void getAnalysisUsage(AnalysisUsage &AU) const override {
376 AU.addRequired<BlockFrequencyInfoWrapperPass>();
377 }
378};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000379
Rong Xuf430ae42015-12-09 18:08:16 +0000380} // end anonymous namespace
381
Xinliang David Li8aebf442016-05-06 05:49:19 +0000382char PGOInstrumentationGenLegacyPass::ID = 0;
383INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000384 "PGO instrumentation.", false, false)
385INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
386INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000387INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000388 "PGO instrumentation.", false, false)
389
Xinliang David Li8aebf442016-05-06 05:49:19 +0000390ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
391 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000392}
393
Xinliang David Lid55827f2016-05-07 05:39:12 +0000394char PGOInstrumentationUseLegacyPass::ID = 0;
395INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000396 "Read PGO instrumentation profile.", false, false)
397INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
398INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000399INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000400 "Read PGO instrumentation profile.", false, false)
401
Xinliang David Lid55827f2016-05-07 05:39:12 +0000402ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
403 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000404}
405
406namespace {
407/// \brief An MST based instrumentation for PGO
408///
409/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
410/// in the function level.
411struct PGOEdge {
412 // This class implements the CFG edges. Note the CFG can be a multi-graph.
413 // So there might be multiple edges with same SrcBB and DestBB.
414 const BasicBlock *SrcBB;
415 const BasicBlock *DestBB;
416 uint64_t Weight;
417 bool InMST;
418 bool Removed;
419 bool IsCritical;
420 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
421 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),
422 IsCritical(false) {}
423 // Return the information string of an edge.
424 const std::string infoString() const {
425 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
426 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
427 }
428};
429
430// This class stores the auxiliary information for each BB.
431struct BBInfo {
432 BBInfo *Group;
433 uint32_t Index;
434 uint32_t Rank;
435
436 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}
437
438 // Return the information string of this object.
439 const std::string infoString() const {
440 return (Twine("Index=") + Twine(Index)).str();
441 }
442};
443
444// This class implements the CFG edges. Note the CFG can be a multi-graph.
445template <class Edge, class BBInfo> class FuncPGOInstrumentation {
446private:
447 Function &F;
448 void computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000449 void renameComdatFunction();
450 // A map that stores the Comdat group in function F.
451 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000452
453public:
Rong Xua3bbf962017-03-15 18:23:39 +0000454 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000455 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000456 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000457 std::string FuncName;
458 GlobalVariable *FuncNameVar;
459 // CFG hash value for this function.
460 uint64_t FunctionHash;
461
462 // The Minimum Spanning Tree of function CFG.
463 CFGMST<Edge, BBInfo> MST;
464
465 // Give an edge, find the BB that will be instrumented.
466 // Return nullptr if there is no BB to be instrumented.
467 BasicBlock *getInstrBB(Edge *E);
468
469 // Return the auxiliary BB information.
470 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
471
Rong Xua5b57452016-12-02 19:10:29 +0000472 // Return the auxiliary BB information if available.
473 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
474
Rong Xuf430ae42015-12-09 18:08:16 +0000475 // Dump edges and BB information.
476 void dumpInfo(std::string Str = "") const {
477 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000478 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000479 }
480
Rong Xu705f7772016-07-25 18:45:37 +0000481 FuncPGOInstrumentation(
482 Function &Func,
483 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
484 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
485 BlockFrequencyInfo *BFI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000486 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Rong Xu60faea12017-03-16 21:15:48 +0000487 SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000488
489 // This should be done before CFG hash computation.
490 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000491 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000492 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu60faea12017-03-16 21:15:48 +0000493 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Rong Xua3bbf962017-03-15 18:23:39 +0000494 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Rong Xue60343d2017-03-17 18:07:26 +0000495 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000496
Rong Xuf430ae42015-12-09 18:08:16 +0000497 FuncName = getPGOFuncName(F);
498 computeCFGHash();
Rong Xu705f7772016-07-25 18:45:37 +0000499 if (ComdatMembers.size())
500 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000501 DEBUG(dumpInfo("after CFGMST"));
502
503 NumOfPGOBB += MST.BBInfos.size();
504 for (auto &E : MST.AllEdges) {
505 if (E->Removed)
506 continue;
507 NumOfPGOEdge++;
508 if (!E->InMST)
509 NumOfPGOInstrument++;
510 }
511
512 if (CreateGlobalVar)
513 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000514 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000515
516 // Return the number of profile counters needed for the function.
517 unsigned getNumCounters() {
518 unsigned NumCounters = 0;
519 for (auto &E : this->MST.AllEdges) {
520 if (!E->InMST && !E->Removed)
521 NumCounters++;
522 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000523 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000524 }
Rong Xuf430ae42015-12-09 18:08:16 +0000525};
526
527// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
528// value of each BB in the CFG. The higher 32 bits record the number of edges.
529template <class Edge, class BBInfo>
530void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
531 std::vector<char> Indexes;
532 JamCRC JC;
533 for (auto &BB : F) {
534 const TerminatorInst *TI = BB.getTerminator();
535 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
536 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000537 auto BI = findBBInfo(Succ);
538 if (BI == nullptr)
539 continue;
540 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000541 for (int J = 0; J < 4; J++)
542 Indexes.push_back((char)(Index >> (J * 8)));
543 }
544 }
545 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000546 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000547 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000548 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
Xinliang David Li8e436982017-07-21 21:36:25 +0000549 DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
550 << " CRC = " << JC.getCRC()
551 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
552 << ", Edges = " << MST.AllEdges.size()
553 << ", ICSites = " << ValueSites[IPVK_IndirectCallTarget].size()
554 << ", Hash = " << FunctionHash << "\n";);
Rong Xu705f7772016-07-25 18:45:37 +0000555}
556
557// Check if we can safely rename this Comdat function.
558static bool canRenameComdat(
559 Function &F,
560 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000561 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000562 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000563
564 // FIXME: Current only handle those Comdat groups that only containing one
565 // function and function aliases.
566 // (1) For a Comdat group containing multiple functions, we need to have a
567 // unique postfix based on the hashes for each function. There is a
568 // non-trivial code refactoring to do this efficiently.
569 // (2) Variables can not be renamed, so we can not rename Comdat function in a
570 // group including global vars.
571 Comdat *C = F.getComdat();
572 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
573 if (dyn_cast<GlobalAlias>(CM.second))
574 continue;
575 Function *FM = dyn_cast<Function>(CM.second);
576 if (FM != &F)
577 return false;
578 }
579 return true;
580}
581
582// Append the CFGHash to the Comdat function name.
583template <class Edge, class BBInfo>
584void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
585 if (!canRenameComdat(F, ComdatMembers))
586 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000587 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000588 std::string NewFuncName =
589 Twine(F.getName() + "." + Twine(FunctionHash)).str();
590 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000591 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000592 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
593 Comdat *NewComdat;
594 Module *M = F.getParent();
595 // For AvailableExternallyLinkage functions, change the linkage to
596 // LinkOnceODR and put them into comdat. This is because after renaming, there
597 // is no backup external copy available for the function.
598 if (!F.hasComdat()) {
599 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
600 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
601 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
602 F.setComdat(NewComdat);
603 return;
604 }
605
606 // This function belongs to a single function Comdat group.
607 Comdat *OrigComdat = F.getComdat();
608 std::string NewComdatName =
609 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
610 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
611 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
612
613 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
614 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
615 // For aliases, change the name directly.
616 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000617 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000618 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000619 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000620 continue;
621 }
622 // Must be a function.
623 Function *CF = dyn_cast<Function>(CM.second);
624 assert(CF);
625 CF->setComdat(NewComdat);
626 }
Rong Xuf430ae42015-12-09 18:08:16 +0000627}
628
629// Given a CFG E to be instrumented, find which BB to place the instrumented
630// code. The function will split the critical edge if necessary.
631template <class Edge, class BBInfo>
632BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
633 if (E->InMST || E->Removed)
634 return nullptr;
635
636 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
637 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
638 // For a fake edge, instrument the real BB.
639 if (SrcBB == nullptr)
640 return DestBB;
641 if (DestBB == nullptr)
642 return SrcBB;
643
644 // Instrument the SrcBB if it has a single successor,
645 // otherwise, the DestBB if this is not a critical edge.
646 TerminatorInst *TI = SrcBB->getTerminator();
647 if (TI->getNumSuccessors() <= 1)
648 return SrcBB;
649 if (!E->IsCritical)
650 return DestBB;
651
652 // For a critical edge, we have to split. Instrument the newly
653 // created BB.
654 NumOfPGOSplit++;
655 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
656 << getBBInfo(DestBB).Index << "\n");
657 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
658 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
659 assert(InstrBB && "Critical edge is not split");
660
661 E->Removed = true;
662 return InstrBB;
663}
664
Rong Xued9fec72016-01-21 18:11:44 +0000665// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000666// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000667static void instrumentOneFunc(
668 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
669 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000670 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
671 BFI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000672 unsigned NumCounters = FuncInfo.getNumCounters();
673
Rong Xuf430ae42015-12-09 18:08:16 +0000674 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000675 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000676 for (auto &E : FuncInfo.MST.AllEdges) {
677 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
678 if (!InstrBB)
679 continue;
680
681 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
682 assert(Builder.GetInsertPoint() != InstrBB->end() &&
683 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000684 Builder.CreateCall(
685 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
686 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
687 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
688 Builder.getInt32(I++)});
689 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000690
691 // Now instrument select instructions:
692 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
693 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000694 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000695
696 if (DisableValueProfiling)
697 return;
698
699 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000700 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000701 CallSite CS(I);
702 Value *Callee = CS.getCalledValue();
703 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
704 << NumIndirectCallSites << "\n");
705 IRBuilder<> Builder(I);
706 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
707 "Cannot get the Instrumentation point");
708 Builder.CreateCall(
709 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
710 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
711 Builder.getInt64(FuncInfo.FunctionHash),
712 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000713 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000714 Builder.getInt32(NumIndirectCallSites++)});
715 }
716 NumOfPGOICall += NumIndirectCallSites;
Rong Xu60faea12017-03-16 21:15:48 +0000717
718 // Now instrument memop intrinsic calls.
719 FuncInfo.MIVisitor.instrumentMemIntrinsics(
720 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000721}
722
723// This class represents a CFG edge in profile use compilation.
724struct PGOUseEdge : public PGOEdge {
725 bool CountValid;
726 uint64_t CountValue;
727 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
728 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}
729
730 // Set edge count value
731 void setEdgeCount(uint64_t Value) {
732 CountValue = Value;
733 CountValid = true;
734 }
735
736 // Return the information string for this object.
737 const std::string infoString() const {
738 if (!CountValid)
739 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000740 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
741 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000742 }
743};
744
745typedef SmallVector<PGOUseEdge *, 2> DirectEdges;
746
747// This class stores the auxiliary information for each BB.
748struct UseBBInfo : public BBInfo {
749 uint64_t CountValue;
750 bool CountValid;
751 int32_t UnknownCountInEdge;
752 int32_t UnknownCountOutEdge;
753 DirectEdges InEdges;
754 DirectEdges OutEdges;
755 UseBBInfo(unsigned IX)
756 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),
757 UnknownCountOutEdge(0) {}
758 UseBBInfo(unsigned IX, uint64_t C)
759 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),
760 UnknownCountOutEdge(0) {}
761
762 // Set the profile count value for this BB.
763 void setBBInfoCount(uint64_t Value) {
764 CountValue = Value;
765 CountValid = true;
766 }
767
768 // Return the information string of this object.
769 const std::string infoString() const {
770 if (!CountValid)
771 return BBInfo::infoString();
772 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
773 }
774};
775
776// Sum up the count values for all the edges.
777static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
778 uint64_t Total = 0;
779 for (auto &E : Edges) {
780 if (E->Removed)
781 continue;
782 Total += E->CountValue;
783 }
784 return Total;
785}
786
787class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000788public:
Rong Xu705f7772016-07-25 18:45:37 +0000789 PGOUseFunc(Function &Func, Module *Modu,
790 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
791 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6090afd2016-03-28 17:08:56 +0000792 BlockFrequencyInfo *BFI = nullptr)
Rong Xu705f7772016-07-25 18:45:37 +0000793 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI),
Rong Xu33308f92016-10-25 21:47:24 +0000794 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000795
796 // Read counts for the instrumented BB from profile.
797 bool readCounters(IndexedInstrProfReader *PGOReader);
798
799 // Populate the counts for all BBs.
800 void populateCounters();
801
802 // Set the branch weights based on the count values.
803 void setBranchWeights();
804
Rong Xua3bbf962017-03-15 18:23:39 +0000805 // Annotate the value profile call sites all all value kind.
806 void annotateValueSites();
807
808 // Annotate the value profile call sites for one value kind.
809 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000810
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000811 // The hotness of the function from the profile count.
812 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
813
814 // Return the function hotness from the profile.
815 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
816
Rong Xu705f7772016-07-25 18:45:37 +0000817 // Return the function hash.
818 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000819 // Return the profile record for this function;
820 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
821
Xinliang David Li4ca17332016-09-18 18:34:07 +0000822 // Return the auxiliary BB information.
823 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
824 return FuncInfo.getBBInfo(BB);
825 }
826
Rong Xua5b57452016-12-02 19:10:29 +0000827 // Return the auxiliary BB information if available.
828 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
829 return FuncInfo.findBBInfo(BB);
830 }
831
Xinliang David Lid289e452017-01-27 19:06:25 +0000832 Function &getFunc() const { return F; }
833
Rong Xuf430ae42015-12-09 18:08:16 +0000834private:
835 Function &F;
836 Module *M;
837 // This member stores the shared information with class PGOGenFunc.
838 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
839
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000840 // The maximum count value in the profile. This is only used in PGO use
841 // compilation.
842 uint64_t ProgramMaxCount;
843
Rong Xu33308f92016-10-25 21:47:24 +0000844 // Position of counter that remains to be read.
845 uint32_t CountPosition;
846
847 // Total size of the profile count for this function.
848 uint32_t ProfileCountSize;
849
Rong Xu13b01dc2016-02-10 18:24:45 +0000850 // ProfileRecord for this function.
851 InstrProfRecord ProfileRecord;
852
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000853 // Function hotness info derived from profile.
854 FuncFreqAttr FreqAttr;
855
Rong Xuf430ae42015-12-09 18:08:16 +0000856 // Find the Instrumented BB and set the value.
857 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
858
859 // Set the edge counter value for the unknown edge -- there should be only
860 // one unknown edge.
861 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
862
863 // Return FuncName string;
864 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000865
866 // Set the hot/cold inline hints based on the count values.
867 // FIXME: This function should be removed once the functionality in
868 // the inliner is implemented.
869 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
870 if (ProgramMaxCount == 0)
871 return;
872 // Threshold of the hot functions.
873 const BranchProbability HotFunctionThreshold(1, 100);
874 // Threshold of the cold functions.
875 const BranchProbability ColdFunctionThreshold(2, 10000);
876 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
877 FreqAttr = FFA_Hot;
878 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
879 FreqAttr = FFA_Cold;
880 }
Rong Xuf430ae42015-12-09 18:08:16 +0000881};
882
883// Visit all the edges and assign the count value for the instrumented
884// edges and the BB.
885void PGOUseFunc::setInstrumentedCounts(
886 const std::vector<uint64_t> &CountFromProfile) {
887
Xinliang David Lid1197612016-08-01 20:25:06 +0000888 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000889 // Use a worklist as we will update the vector during the iteration.
890 std::vector<PGOUseEdge *> WorkList;
891 for (auto &E : FuncInfo.MST.AllEdges)
892 WorkList.push_back(E.get());
893
894 uint32_t I = 0;
895 for (auto &E : WorkList) {
896 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
897 if (!InstrBB)
898 continue;
899 uint64_t CountValue = CountFromProfile[I++];
900 if (!E->Removed) {
901 getBBInfo(InstrBB).setBBInfoCount(CountValue);
902 E->setEdgeCount(CountValue);
903 continue;
904 }
905
906 // Need to add two new edges.
907 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
908 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
909 // Add new edge of SrcBB->InstrBB.
910 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
911 NewEdge.setEdgeCount(CountValue);
912 // Add new edge of InstrBB->DestBB.
913 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
914 NewEdge1.setEdgeCount(CountValue);
915 NewEdge1.InMST = true;
916 getBBInfo(InstrBB).setBBInfoCount(CountValue);
917 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000918 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000919 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000920}
921
922// Set the count value for the unknown edge. There should be one and only one
923// unknown edge in Edges vector.
924void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
925 for (auto &E : Edges) {
926 if (E->CountValid)
927 continue;
928 E->setEdgeCount(Value);
929
930 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
931 getBBInfo(E->DestBB).UnknownCountInEdge--;
932 return;
933 }
934 llvm_unreachable("Cannot find the unknown count edge");
935}
936
937// Read the profile from ProfileFileName and assign the value to the
938// instrumented BB and the edges. This function also updates ProgramMaxCount.
939// Return true if the profile are successfully read, and false on errors.
940bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
941 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000942 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +0000943 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000944 if (Error E = Result.takeError()) {
945 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
946 auto Err = IPE.get();
947 bool SkipWarning = false;
948 if (Err == instrprof_error::unknown_function) {
949 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +0000950 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000951 } else if (Err == instrprof_error::hash_mismatch ||
952 Err == instrprof_error::malformed) {
953 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +0000954 SkipWarning =
955 NoPGOWarnMismatch ||
956 (NoPGOWarnMismatchComdat &&
957 (F.hasComdat() ||
958 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000959 }
Rong Xuf430ae42015-12-09 18:08:16 +0000960
Vedant Kumar9152fd12016-05-19 03:54:45 +0000961 if (SkipWarning)
962 return;
963
964 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
965 Ctx.diagnose(
966 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
967 });
Rong Xuf430ae42015-12-09 18:08:16 +0000968 return false;
969 }
Rong Xu13b01dc2016-02-10 18:24:45 +0000970 ProfileRecord = std::move(Result.get());
971 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +0000972
973 NumOfPGOFunc++;
974 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
975 uint64_t ValueSum = 0;
976 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
977 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
978 ValueSum += CountFromProfile[I];
979 }
980
981 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
982
983 getBBInfo(nullptr).UnknownCountOutEdge = 2;
984 getBBInfo(nullptr).UnknownCountInEdge = 2;
985
986 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000987 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +0000988 return true;
989}
990
991// Populate the counters from instrumented BBs to all BBs.
992// In the end of this operation, all BBs should have a valid count value.
993void PGOUseFunc::populateCounters() {
994 // First set up Count variable for all BBs.
995 for (auto &E : FuncInfo.MST.AllEdges) {
996 if (E->Removed)
997 continue;
998
999 const BasicBlock *SrcBB = E->SrcBB;
1000 const BasicBlock *DestBB = E->DestBB;
1001 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1002 UseBBInfo &DestInfo = getBBInfo(DestBB);
1003 SrcInfo.OutEdges.push_back(E.get());
1004 DestInfo.InEdges.push_back(E.get());
1005 SrcInfo.UnknownCountOutEdge++;
1006 DestInfo.UnknownCountInEdge++;
1007
1008 if (!E->CountValid)
1009 continue;
1010 DestInfo.UnknownCountInEdge--;
1011 SrcInfo.UnknownCountOutEdge--;
1012 }
1013
1014 bool Changes = true;
1015 unsigned NumPasses = 0;
1016 while (Changes) {
1017 NumPasses++;
1018 Changes = false;
1019
1020 // For efficient traversal, it's better to start from the end as most
1021 // of the instrumented edges are at the end.
1022 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +00001023 UseBBInfo *Count = findBBInfo(&BB);
1024 if (Count == nullptr)
1025 continue;
1026 if (!Count->CountValid) {
1027 if (Count->UnknownCountOutEdge == 0) {
1028 Count->CountValue = sumEdgeCount(Count->OutEdges);
1029 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001030 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +00001031 } else if (Count->UnknownCountInEdge == 0) {
1032 Count->CountValue = sumEdgeCount(Count->InEdges);
1033 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001034 Changes = true;
1035 }
1036 }
Rong Xua5b57452016-12-02 19:10:29 +00001037 if (Count->CountValid) {
1038 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001039 uint64_t Total = 0;
1040 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1041 // If the one of the successor block can early terminate (no-return),
1042 // we can end up with situation where out edge sum count is larger as
1043 // the source BB's count is collected by a post-dominated block.
1044 if (Count->CountValue > OutSum)
1045 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +00001046 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001047 Changes = true;
1048 }
Rong Xua5b57452016-12-02 19:10:29 +00001049 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001050 uint64_t Total = 0;
1051 uint64_t InSum = sumEdgeCount(Count->InEdges);
1052 if (Count->CountValue > InSum)
1053 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001054 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001055 Changes = true;
1056 }
1057 }
1058 }
1059 }
1060
1061 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001062#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001063 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001064 for (auto &BB : F) {
1065 auto BI = findBBInfo(&BB);
1066 if (BI == nullptr)
1067 continue;
1068 assert(BI->CountValid && "BB count is not valid");
1069 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001070#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001071 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +00001072 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001073 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001074 for (auto &BB : F) {
1075 auto BI = findBBInfo(&BB);
1076 if (BI == nullptr)
1077 continue;
1078 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1079 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001080 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001081
Rong Xu33308f92016-10-25 21:47:24 +00001082 // Now annotate select instructions
1083 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1084 assert(CountPosition == ProfileCountSize);
1085
Rong Xuf430ae42015-12-09 18:08:16 +00001086 DEBUG(FuncInfo.dumpInfo("after reading profile."));
1087}
1088
1089// Assign the scaled count values to the BB with multiple out edges.
1090void PGOUseFunc::setBranchWeights() {
1091 // Generate MD_prof metadata for every branch instruction.
1092 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001093 for (auto &BB : F) {
1094 TerminatorInst *TI = BB.getTerminator();
1095 if (TI->getNumSuccessors() < 2)
1096 continue;
1097 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1098 continue;
1099 if (getBBInfo(&BB).CountValue == 0)
1100 continue;
1101
1102 // We have a non-zero Branch BB.
1103 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1104 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001105 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001106 uint64_t MaxCount = 0;
1107 for (unsigned s = 0; s < Size; s++) {
1108 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1109 const BasicBlock *SrcBB = E->SrcBB;
1110 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001111 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001112 continue;
1113 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1114 uint64_t EdgeCount = E->CountValue;
1115 if (EdgeCount > MaxCount)
1116 MaxCount = EdgeCount;
1117 EdgeCounts[SuccNum] = EdgeCount;
1118 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001119 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001120 }
1121}
Rong Xu13b01dc2016-02-10 18:24:45 +00001122
Xinliang David Li4ca17332016-09-18 18:34:07 +00001123void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1124 Module *M = F.getParent();
1125 IRBuilder<> Builder(&SI);
1126 Type *Int64Ty = Builder.getInt64Ty();
1127 Type *I8PtrTy = Builder.getInt8PtrTy();
1128 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1129 Builder.CreateCall(
1130 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
1131 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001132 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1133 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001134 ++(*CurCtrIdx);
1135}
1136
1137void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1138 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1139 assert(*CurCtrIdx < CountFromProfile.size() &&
1140 "Out of bound access of counters");
1141 uint64_t SCounts[2];
1142 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1143 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001144 uint64_t TotalCount = 0;
1145 auto BI = UseFunc->findBBInfo(SI.getParent());
1146 if (BI != nullptr)
1147 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001148 // False Count
1149 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1150 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001151 if (MaxCount)
1152 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001153}
1154
1155void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1156 if (!PGOInstrSelect)
1157 return;
1158 // FIXME: do not handle this yet.
1159 if (SI.getCondition()->getType()->isVectorTy())
1160 return;
1161
Xinliang David Li4ca17332016-09-18 18:34:07 +00001162 switch (Mode) {
1163 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001164 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001165 return;
1166 case VM_instrument:
1167 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001168 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001169 case VM_annotate:
1170 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001171 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001172 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001173
1174 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001175}
1176
Rong Xu60faea12017-03-16 21:15:48 +00001177void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1178 Module *M = F.getParent();
1179 IRBuilder<> Builder(&MI);
1180 Type *Int64Ty = Builder.getInt64Ty();
1181 Type *I8PtrTy = Builder.getInt8PtrTy();
1182 Value *Length = MI.getLength();
1183 assert(!dyn_cast<ConstantInt>(Length));
1184 Builder.CreateCall(
1185 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
1186 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Ana Pazosf731bde2017-06-19 20:04:33 +00001187 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
Rong Xu60faea12017-03-16 21:15:48 +00001188 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1189 ++CurCtrId;
1190}
1191
1192void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1193 if (!PGOInstrMemOP)
1194 return;
1195 Value *Length = MI.getLength();
1196 // Not instrument constant length calls.
1197 if (dyn_cast<ConstantInt>(Length))
1198 return;
1199
1200 switch (Mode) {
1201 case VM_counting:
1202 NMemIs++;
1203 return;
1204 case VM_instrument:
1205 instrumentOneMemIntrinsic(MI);
1206 return;
1207 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001208 Candidates.push_back(&MI);
1209 return;
Rong Xu60faea12017-03-16 21:15:48 +00001210 }
1211 llvm_unreachable("Unknown visiting mode");
1212}
1213
Rong Xua3bbf962017-03-15 18:23:39 +00001214// Traverse all valuesites and annotate the instructions for all value kind.
1215void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001216 if (DisableValueProfiling)
1217 return;
1218
Rong Xu8e8fe852016-04-01 16:43:30 +00001219 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001220 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001221
Rong Xua3bbf962017-03-15 18:23:39 +00001222 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001223 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001224}
1225
1226// Annotate the instructions for a specific value kind.
1227void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1228 unsigned ValueSiteIndex = 0;
1229 auto &ValueSites = FuncInfo.ValueSites[Kind];
1230 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1231 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001232 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001233 Ctx.diagnose(DiagnosticInfoPGOProfile(
1234 M->getName().data(),
1235 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1236 " in " + F.getName().str(),
1237 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001238 return;
1239 }
1240
Rong Xua3bbf962017-03-15 18:23:39 +00001241 for (auto &I : ValueSites) {
1242 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1243 << "): Index = " << ValueSiteIndex << " out of "
1244 << NumValueSites << "\n");
1245 annotateValueSite(*M, *I, ProfileRecord,
1246 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001247 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1248 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001249 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001250 }
1251}
Rong Xuf430ae42015-12-09 18:08:16 +00001252} // end anonymous namespace
1253
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001254// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001255// aware this is an ir_level profile so it can set the version flag.
1256static void createIRLevelProfileFlagVariable(Module &M) {
1257 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1258 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001259 auto IRLevelVersionVariable = new GlobalVariable(
1260 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1261 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001262 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001263 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1264 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001265 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001266 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001267 else
Rong Xu9e926e82016-02-29 19:16:04 +00001268 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001269 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001270}
1271
Rong Xu705f7772016-07-25 18:45:37 +00001272// Collect the set of members for each Comdat in module M and store
1273// in ComdatMembers.
1274static void collectComdatMembers(
1275 Module &M,
1276 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1277 if (!DoComdatRenaming)
1278 return;
1279 for (Function &F : M)
1280 if (Comdat *C = F.getComdat())
1281 ComdatMembers.insert(std::make_pair(C, &F));
1282 for (GlobalVariable &GV : M.globals())
1283 if (Comdat *C = GV.getComdat())
1284 ComdatMembers.insert(std::make_pair(C, &GV));
1285 for (GlobalAlias &GA : M.aliases())
1286 if (Comdat *C = GA.getComdat())
1287 ComdatMembers.insert(std::make_pair(C, &GA));
1288}
1289
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001290static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001291 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
1292 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001293 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001294 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1295 collectComdatMembers(M, ComdatMembers);
1296
Rong Xuf430ae42015-12-09 18:08:16 +00001297 for (auto &F : M) {
1298 if (F.isDeclaration())
1299 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001300 auto *BPI = LookupBPI(F);
1301 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001302 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001303 }
1304 return true;
1305}
1306
Xinliang David Li8aebf442016-05-06 05:49:19 +00001307bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001308 if (skipModule(M))
1309 return false;
1310
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001311 auto LookupBPI = [this](Function &F) {
1312 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001313 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001314 auto LookupBFI = [this](Function &F) {
1315 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001316 };
1317 return InstrumentAllFunctions(M, LookupBPI, LookupBFI);
1318}
1319
Xinliang David Li8aebf442016-05-06 05:49:19 +00001320PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001321 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001322
1323 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001324 auto LookupBPI = [&FAM](Function &F) {
1325 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001326 };
1327
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001328 auto LookupBFI = [&FAM](Function &F) {
1329 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001330 };
1331
1332 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI))
1333 return PreservedAnalyses::all();
1334
1335 return PreservedAnalyses::none();
1336}
1337
Xinliang David Lida195582016-05-10 21:59:52 +00001338static bool annotateAllFunctions(
1339 Module &M, StringRef ProfileFileName,
1340 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001341 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001342 DEBUG(dbgs() << "Read in profile counters: ");
1343 auto &Ctx = M.getContext();
1344 // Read the counter array from file.
1345 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001346 if (Error E = ReaderOrErr.takeError()) {
1347 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1348 Ctx.diagnose(
1349 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1350 });
Rong Xuf430ae42015-12-09 18:08:16 +00001351 return false;
1352 }
1353
Xinliang David Lida195582016-05-10 21:59:52 +00001354 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1355 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001356 if (!PGOReader) {
1357 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001358 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001359 return false;
1360 }
Rong Xu33c76c02016-02-10 17:18:30 +00001361 // TODO: might need to change the warning once the clang option is finalized.
1362 if (!PGOReader->isIRLevelProfile()) {
1363 Ctx.diagnose(DiagnosticInfoPGOProfile(
1364 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1365 return false;
1366 }
1367
Rong Xu705f7772016-07-25 18:45:37 +00001368 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1369 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001370 std::vector<Function *> HotFunctions;
1371 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001372 for (auto &F : M) {
1373 if (F.isDeclaration())
1374 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001375 auto *BPI = LookupBPI(F);
1376 auto *BFI = LookupBFI(F);
Rong Xu705f7772016-07-25 18:45:37 +00001377 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001378 if (!Func.readCounters(PGOReader.get()))
1379 continue;
1380 Func.populateCounters();
1381 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001382 Func.annotateValueSites();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001383 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1384 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001385 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001386 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1387 HotFunctions.push_back(&F);
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001388 if (PGOViewCounts && (ViewBlockFreqFuncName.empty() ||
1389 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001390 LoopInfo LI{DominatorTree(F)};
1391 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1392 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1393 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1394 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
1395
1396 NewBFI->view();
1397 }
Xinliang David Li58fcc9b2017-02-02 21:29:17 +00001398 if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() ||
1399 F.getName().equals(ViewBlockFreqFuncName))) {
1400 if (ViewBlockFreqFuncName.empty())
Xinliang David Lid289e452017-01-27 19:06:25 +00001401 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1402 else
1403 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1404 }
Rong Xuf430ae42015-12-09 18:08:16 +00001405 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001406 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001407 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001408 // We have to apply these attributes at the end because their presence
1409 // can affect the BranchProbabilityInfo of any callers, resulting in an
1410 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001411 for (auto &F : HotFunctions) {
1412 F->addFnAttr(llvm::Attribute::InlineHint);
1413 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1414 << "\n");
1415 }
1416 for (auto &F : ColdFunctions) {
1417 F->addFnAttr(llvm::Attribute::Cold);
1418 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1419 }
Rong Xuf430ae42015-12-09 18:08:16 +00001420 return true;
1421}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001422
Xinliang David Lida195582016-05-10 21:59:52 +00001423PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001424 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001425 if (!PGOTestProfileFile.empty())
1426 ProfileFileName = PGOTestProfileFile;
1427}
1428
1429PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001430 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001431
1432 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1433 auto LookupBPI = [&FAM](Function &F) {
1434 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1435 };
1436
1437 auto LookupBFI = [&FAM](Function &F) {
1438 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1439 };
1440
1441 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI))
1442 return PreservedAnalyses::all();
1443
1444 return PreservedAnalyses::none();
1445}
1446
Xinliang David Lid55827f2016-05-07 05:39:12 +00001447bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1448 if (skipModule(M))
1449 return false;
1450
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001451 auto LookupBPI = [this](Function &F) {
1452 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001453 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001454 auto LookupBFI = [this](Function &F) {
1455 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001456 };
1457
Xinliang David Lida195582016-05-10 21:59:52 +00001458 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001459}
Xinliang David Lid289e452017-01-27 19:06:25 +00001460
1461namespace llvm {
Rong Xu48596b62017-04-04 16:42:20 +00001462void setProfMetadata(Module *M, Instruction *TI, ArrayRef<uint64_t> EdgeCounts,
1463 uint64_t MaxCount) {
1464 MDBuilder MDB(M->getContext());
1465 assert(MaxCount > 0 && "Bad max count");
1466 uint64_t Scale = calculateCountScale(MaxCount);
1467 SmallVector<unsigned, 4> Weights;
1468 for (const auto &ECI : EdgeCounts)
1469 Weights.push_back(scaleBranchCount(ECI, Scale));
1470
1471 DEBUG(dbgs() << "Weight is: ";
1472 for (const auto &W : Weights) { dbgs() << W << " "; }
1473 dbgs() << "\n";);
1474 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001475 if (EmitBranchProbability) {
1476 std::string BrCondStr = getBranchCondString(TI);
1477 if (BrCondStr.empty())
1478 return;
1479
1480 unsigned WSum =
1481 std::accumulate(Weights.begin(), Weights.end(), 0,
1482 [](unsigned w1, unsigned w2) { return w1 + w2; });
1483 uint64_t TotalCount =
1484 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0,
1485 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1486 BranchProbability BP(Weights[0], WSum);
1487 std::string BranchProbStr;
1488 raw_string_ostream OS(BranchProbStr);
1489 OS << BP;
1490 OS << " (total count : " << TotalCount << ")";
1491 OS.flush();
1492 Function *F = TI->getParent()->getParent();
Davide Italiano0c8d26c2017-07-20 20:43:05 +00001493 OptimizationRemarkEmitter ORE(F);
1494 ORE.emit(OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1495 << BrCondStr << " is true with probability : " << BranchProbStr);
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001496 }
Rong Xu48596b62017-04-04 16:42:20 +00001497}
1498
Xinliang David Lid289e452017-01-27 19:06:25 +00001499template <> struct GraphTraits<PGOUseFunc *> {
1500 typedef const BasicBlock *NodeRef;
1501 typedef succ_const_iterator ChildIteratorType;
1502 typedef pointer_iterator<Function::const_iterator> nodes_iterator;
1503
1504 static NodeRef getEntryNode(const PGOUseFunc *G) {
1505 return &G->getFunc().front();
1506 }
1507 static ChildIteratorType child_begin(const NodeRef N) {
1508 return succ_begin(N);
1509 }
1510 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
1511 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1512 return nodes_iterator(G->getFunc().begin());
1513 }
1514 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1515 return nodes_iterator(G->getFunc().end());
1516 }
1517};
1518
Xinliang David Li6144a592017-02-03 21:57:51 +00001519static std::string getSimpleNodeName(const BasicBlock *Node) {
1520 if (!Node->getName().empty())
1521 return Node->getName();
1522
1523 std::string SimpleNodeName;
1524 raw_string_ostream OS(SimpleNodeName);
1525 Node->printAsOperand(OS, false);
1526 return OS.str();
1527}
1528
Xinliang David Lid289e452017-01-27 19:06:25 +00001529template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1530 explicit DOTGraphTraits(bool isSimple = false)
1531 : DefaultDOTGraphTraits(isSimple) {}
1532
1533 static std::string getGraphName(const PGOUseFunc *G) {
1534 return G->getFunc().getName();
1535 }
1536
1537 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1538 std::string Result;
1539 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001540
1541 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001542 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001543 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001544 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001545 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001546 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001547 OS << "Unknown\\l";
1548
1549 if (!PGOInstrSelect)
1550 return Result;
1551
1552 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1553 auto *I = &*BI;
1554 if (!isa<SelectInst>(I))
1555 continue;
1556 // Display scaled counts for SELECT instruction:
1557 OS << "SELECT : { T = ";
1558 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001559 bool HasProf = I->extractProfMetadata(TC, FC);
1560 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001561 OS << "Unknown, F = Unknown }\\l";
1562 else
1563 OS << TC << ", F = " << FC << " }\\l";
1564 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001565 return Result;
1566 }
1567};
Rong Xu0a2a1312017-03-09 19:08:55 +00001568} // namespace llvm