blob: 16ecb4a241577459216ac49a0cb5afa29d148428 [file] [log] [blame]
Eugene Zelenkofce43572017-10-21 00:57:46 +00001//===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
Rong Xuf430ae42015-12-09 18:08:16 +00002//
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"
Eugene Zelenkofce43572017-10-21 00:57:46 +000053#include "llvm/ADT/APInt.h"
54#include "llvm/ADT/ArrayRef.h"
Rong Xuf430ae42015-12-09 18:08:16 +000055#include "llvm/ADT/STLExtras.h"
Rong Xu705f7772016-07-25 18:45:37 +000056#include "llvm/ADT/SmallVector.h"
Rong Xuf430ae42015-12-09 18:08:16 +000057#include "llvm/ADT/Statistic.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000058#include "llvm/ADT/StringRef.h"
Rong Xu33c76c02016-02-10 17:18:30 +000059#include "llvm/ADT/Triple.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000060#include "llvm/ADT/Twine.h"
61#include "llvm/ADT/iterator.h"
62#include "llvm/ADT/iterator_range.h"
Rong Xuf430ae42015-12-09 18:08:16 +000063#include "llvm/Analysis/BlockFrequencyInfo.h"
64#include "llvm/Analysis/BranchProbabilityInfo.h"
65#include "llvm/Analysis/CFG.h"
Teresa Johnson1e44b5d2016-07-12 21:13:44 +000066#include "llvm/Analysis/IndirectCallSiteVisitor.h"
Xinliang David Licb253ce2017-01-23 18:58:24 +000067#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000068#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000069#include "llvm/IR/Attributes.h"
70#include "llvm/IR/BasicBlock.h"
71#include "llvm/IR/CFG.h"
Rong Xued9fec72016-01-21 18:11:44 +000072#include "llvm/IR/CallSite.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000073#include "llvm/IR/Comdat.h"
74#include "llvm/IR/Constant.h"
75#include "llvm/IR/Constants.h"
Rong Xuf430ae42015-12-09 18:08:16 +000076#include "llvm/IR/DiagnosticInfo.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000077#include "llvm/IR/Dominators.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000078#include "llvm/IR/Function.h"
79#include "llvm/IR/GlobalAlias.h"
Rong Xu705f7772016-07-25 18:45:37 +000080#include "llvm/IR/GlobalValue.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000081#include "llvm/IR/GlobalVariable.h"
Rong Xuf430ae42015-12-09 18:08:16 +000082#include "llvm/IR/IRBuilder.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000083#include "llvm/IR/InstVisitor.h"
84#include "llvm/IR/InstrTypes.h"
85#include "llvm/IR/Instruction.h"
Rong Xuf430ae42015-12-09 18:08:16 +000086#include "llvm/IR/Instructions.h"
87#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000088#include "llvm/IR/Intrinsics.h"
89#include "llvm/IR/LLVMContext.h"
Rong Xuf430ae42015-12-09 18:08:16 +000090#include "llvm/IR/MDBuilder.h"
91#include "llvm/IR/Module.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000092#include "llvm/IR/PassManager.h"
93#include "llvm/IR/ProfileSummary.h"
94#include "llvm/IR/Type.h"
95#include "llvm/IR/Value.h"
Rong Xuf430ae42015-12-09 18:08:16 +000096#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000097#include "llvm/ProfileData/InstrProf.h"
Rong Xuf430ae42015-12-09 18:08:16 +000098#include "llvm/ProfileData/InstrProfReader.h"
99#include "llvm/Support/BranchProbability.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000100#include "llvm/Support/Casting.h"
101#include "llvm/Support/CommandLine.h"
Xinliang David Lid289e452017-01-27 19:06:25 +0000102#include "llvm/Support/DOTGraphTraits.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000103#include "llvm/Support/Debug.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000104#include "llvm/Support/Error.h"
105#include "llvm/Support/ErrorHandling.h"
Xinliang David Lid289e452017-01-27 19:06:25 +0000106#include "llvm/Support/GraphWriter.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000107#include "llvm/Support/JamCRC.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000108#include "llvm/Support/raw_ostream.h"
Rong Xued9fec72016-01-21 18:11:44 +0000109#include "llvm/Transforms/Instrumentation.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000110#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Xinliang David Li8aebf442016-05-06 05:49:19 +0000111#include <algorithm>
Eugene Zelenkofce43572017-10-21 00:57:46 +0000112#include <cassert>
113#include <cstdint>
114#include <memory>
115#include <numeric>
Rong Xuf430ae42015-12-09 18:08:16 +0000116#include <string>
Rong Xu705f7772016-07-25 18:45:37 +0000117#include <unordered_map>
Rong Xuf430ae42015-12-09 18:08:16 +0000118#include <utility>
119#include <vector>
120
121using namespace llvm;
122
123#define DEBUG_TYPE "pgo-instrumentation"
124
125STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +0000126STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xu60faea12017-03-16 21:15:48 +0000127STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +0000128STATISTIC(NumOfPGOEdge, "Number of edges.");
129STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
130STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
131STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
132STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
133STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000134STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xuf430ae42015-12-09 18:08:16 +0000135
136// Command line option to specify the file to read profile from. This is
137// mainly used for testing.
138static cl::opt<std::string>
139 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
140 cl::value_desc("filename"),
141 cl::desc("Specify the path of profile data file. This is"
142 "mainly for test purpose."));
143
Rong Xuecdc98f2016-03-04 22:08:44 +0000144// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000145// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000146static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
147 cl::Hidden,
148 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000149
Rong Xuecdc98f2016-03-04 22:08:44 +0000150// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000151// the metadata for a single indirect call callsite.
152static cl::opt<unsigned> MaxNumAnnotations(
153 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
154 cl::desc("Max number of annotations for a single indirect "
155 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000156
Rong Xue60343d2017-03-17 18:07:26 +0000157// Command line option to set the maximum number of value annotations
158// to write to the metadata for a single memop intrinsic.
159static cl::opt<unsigned> MaxNumMemOPAnnotations(
160 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
161 cl::desc("Max number of preicise value annotations for a single memop"
162 "intrinsic"));
163
Rong Xu705f7772016-07-25 18:45:37 +0000164// Command line option to control appending FunctionHash to the name of a COMDAT
165// function. This is to avoid the hash mismatch caused by the preinliner.
166static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000167 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000168 cl::desc("Append function hash to the name of COMDAT function to avoid "
169 "function hash mismatch due to the preinliner"));
170
Rong Xu0698de92016-05-13 17:26:06 +0000171// Command line option to enable/disable the warning about missing profile
172// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000173static cl::opt<bool>
174 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
175 cl::desc("Use this option to turn on/off "
176 "warnings about missing profile data for "
177 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000178
179// Command line option to enable/disable the warning about a hash mismatch in
180// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000181static cl::opt<bool>
182 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
183 cl::desc("Use this option to turn off/on "
184 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000185
Rong Xu20f5df12017-01-11 20:19:41 +0000186// Command line option to enable/disable the warning about a hash mismatch in
187// the profile data for Comdat functions, which often turns out to be false
188// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000189static cl::opt<bool>
190 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
191 cl::Hidden,
192 cl::desc("The option is used to turn on/off "
193 "warnings about hash mismatch for comdat "
194 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000195
Xinliang David Li4ca17332016-09-18 18:34:07 +0000196// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000197static cl::opt<bool>
198 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
199 cl::desc("Use this option to turn on/off SELECT "
200 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000201
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000202// Command line option to turn on CFG dot or text dump of raw profile counts
203static cl::opt<PGOViewCountsType> PGOViewRawCounts(
204 "pgo-view-raw-counts", cl::Hidden,
205 cl::desc("A boolean option to show CFG dag or text "
206 "with raw profile counts from "
207 "profile data. See also option "
208 "-pgo-view-counts. To limit graph "
209 "display to only one function, use "
210 "filtering option -view-bfi-func-name."),
211 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
212 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
213 clEnumValN(PGOVCT_Text, "text", "show in text.")));
Xinliang David Lid289e452017-01-27 19:06:25 +0000214
Rong Xu8e06e802017-03-17 20:51:44 +0000215// Command line option to enable/disable memop intrinsic call.size profiling.
216static cl::opt<bool>
217 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
218 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000219 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000220
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000221// Emit branch probability as optimization remarks.
222static cl::opt<bool>
223 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
224 cl::desc("When this option is on, the annotated "
225 "branch probability will be emitted as "
226 " optimization remarks: -Rpass-analysis="
227 "pgo-instr-use"));
228
Xinliang David Licb253ce2017-01-23 18:58:24 +0000229// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000230// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000231extern cl::opt<PGOViewCountsType> PGOViewCounts;
Xinliang David Licb253ce2017-01-23 18:58:24 +0000232
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000233// Command line option to specify the name of the function for CFG dump
234// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
235extern cl::opt<std::string> ViewBlockFreqFuncName;
236
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000237// Return a string describing the branch condition that can be
238// used in static branch probability heuristics:
Eugene Zelenkofce43572017-10-21 00:57:46 +0000239static std::string getBranchCondString(Instruction *TI) {
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000240 BranchInst *BI = dyn_cast<BranchInst>(TI);
241 if (!BI || !BI->isConditional())
242 return std::string();
243
244 Value *Cond = BI->getCondition();
245 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
246 if (!CI)
247 return std::string();
248
249 std::string result;
250 raw_string_ostream OS(result);
251 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
252 CI->getOperand(0)->getType()->print(OS, true);
253
254 Value *RHS = CI->getOperand(1);
255 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
256 if (CV) {
257 if (CV->isZero())
258 OS << "_Zero";
259 else if (CV->isOne())
260 OS << "_One";
Craig Topper79ab6432017-07-06 18:39:47 +0000261 else if (CV->isMinusOne())
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000262 OS << "_MinusOne";
263 else
264 OS << "_Const";
265 }
266 OS.flush();
267 return result;
268}
269
Eugene Zelenkofce43572017-10-21 00:57:46 +0000270namespace {
271
Xinliang David Li4ca17332016-09-18 18:34:07 +0000272/// The select instruction visitor plays three roles specified
273/// by the mode. In \c VM_counting mode, it simply counts the number of
274/// select instructions. In \c VM_instrument mode, it inserts code to count
275/// the number times TrueValue of select is taken. In \c VM_annotate mode,
276/// it reads the profile data and annotate the select instruction with metadata.
277enum VisitMode { VM_counting, VM_instrument, VM_annotate };
278class PGOUseFunc;
279
280/// Instruction Visitor class to visit select instructions.
281struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
282 Function &F;
283 unsigned NSIs = 0; // Number of select instructions instrumented.
284 VisitMode Mode = VM_counting; // Visiting mode.
285 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
286 unsigned TotalNumCtrs = 0; // Total number of counters
287 GlobalVariable *FuncNameVar = nullptr;
288 uint64_t FuncHash = 0;
289 PGOUseFunc *UseFunc = nullptr;
290
291 SelectInstVisitor(Function &Func) : F(Func) {}
292
293 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000294 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000295 Mode = VM_counting;
296 visit(Func);
297 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000298
Xinliang David Li4ca17332016-09-18 18:34:07 +0000299 // Visit the IR stream and instrument all select instructions. \p
300 // Ind is a pointer to the counter index variable; \p TotalNC
301 // is the total number of counters; \p FNV is the pointer to the
302 // PGO function name var; \p FHash is the function hash.
303 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
304 GlobalVariable *FNV, uint64_t FHash) {
305 Mode = VM_instrument;
306 CurCtrIdx = Ind;
307 TotalNumCtrs = TotalNC;
308 FuncHash = FHash;
309 FuncNameVar = FNV;
310 visit(Func);
311 }
312
313 // Visit the IR stream and annotate all select instructions.
314 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
315 Mode = VM_annotate;
316 UseFunc = UF;
317 CurCtrIdx = Ind;
318 visit(Func);
319 }
320
321 void instrumentOneSelectInst(SelectInst &SI);
322 void annotateOneSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000323
Xinliang David Li4ca17332016-09-18 18:34:07 +0000324 // Visit \p SI instruction and perform tasks according to visit mode.
325 void visitSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000326
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000327 // Return the number of select instructions. This needs be called after
328 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000329 unsigned getNumOfSelectInsts() const { return NSIs; }
330};
331
Rong Xu60faea12017-03-16 21:15:48 +0000332/// Instruction Visitor class to visit memory intrinsic calls.
333struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
334 Function &F;
335 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
336 VisitMode Mode = VM_counting; // Visiting mode.
337 unsigned CurCtrId = 0; // Current counter index.
338 unsigned TotalNumCtrs = 0; // Total number of counters
339 GlobalVariable *FuncNameVar = nullptr;
340 uint64_t FuncHash = 0;
341 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000342 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000343
344 MemIntrinsicVisitor(Function &Func) : F(Func) {}
345
346 void countMemIntrinsics(Function &Func) {
347 NMemIs = 0;
348 Mode = VM_counting;
349 visit(Func);
350 }
Rong Xue60343d2017-03-17 18:07:26 +0000351
Rong Xu60faea12017-03-16 21:15:48 +0000352 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
353 GlobalVariable *FNV, uint64_t FHash) {
354 Mode = VM_instrument;
355 TotalNumCtrs = TotalNC;
356 FuncHash = FHash;
357 FuncNameVar = FNV;
358 visit(Func);
359 }
360
Rong Xue60343d2017-03-17 18:07:26 +0000361 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
362 Candidates.clear();
363 Mode = VM_annotate;
364 visit(Func);
365 return Candidates;
366 }
367
Rong Xu60faea12017-03-16 21:15:48 +0000368 // Visit the IR stream and annotate all mem intrinsic call instructions.
369 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000370
Rong Xu60faea12017-03-16 21:15:48 +0000371 // Visit \p MI instruction and perform tasks according to visit mode.
372 void visitMemIntrinsic(MemIntrinsic &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000373
Rong Xu60faea12017-03-16 21:15:48 +0000374 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
375};
376
Xinliang David Li8aebf442016-05-06 05:49:19 +0000377class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000378public:
379 static char ID;
380
Xinliang David Lidfa21c32016-05-09 21:37:12 +0000381 PGOInstrumentationGenLegacyPass() : ModulePass(ID) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000382 initializePGOInstrumentationGenLegacyPassPass(
383 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000384 }
385
Mehdi Amini117296c2016-10-01 02:56:57 +0000386 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000387
388private:
389 bool runOnModule(Module &M) override;
390
391 void getAnalysisUsage(AnalysisUsage &AU) const override {
392 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Xinliang David Licc35bc92017-12-05 17:19:41 +0000393 AU.addRequired<LoopInfoWrapperPass>();
Rong Xuf430ae42015-12-09 18:08:16 +0000394 }
395};
396
Xinliang David Lid55827f2016-05-07 05:39:12 +0000397class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000398public:
399 static char ID;
400
401 // Provide the profile filename as the parameter.
Xinliang David Lid55827f2016-05-07 05:39:12 +0000402 PGOInstrumentationUseLegacyPass(std::string Filename = "")
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000403 : ModulePass(ID), ProfileFileName(std::move(Filename)) {
Rong Xuf430ae42015-12-09 18:08:16 +0000404 if (!PGOTestProfileFile.empty())
405 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000406 initializePGOInstrumentationUseLegacyPassPass(
407 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000408 }
409
Mehdi Amini117296c2016-10-01 02:56:57 +0000410 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000411
412private:
413 std::string ProfileFileName;
Rong Xuf430ae42015-12-09 18:08:16 +0000414
Xinliang David Lida195582016-05-10 21:59:52 +0000415 bool runOnModule(Module &M) override;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000416
Rong Xuf430ae42015-12-09 18:08:16 +0000417 void getAnalysisUsage(AnalysisUsage &AU) const override {
418 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Xinliang David Licc35bc92017-12-05 17:19:41 +0000419 AU.addRequired<LoopInfoWrapperPass>();
Rong Xuf430ae42015-12-09 18:08:16 +0000420 }
421};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000422
Rong Xuf430ae42015-12-09 18:08:16 +0000423} // end anonymous namespace
424
Xinliang David Li8aebf442016-05-06 05:49:19 +0000425char PGOInstrumentationGenLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000426
Xinliang David Li8aebf442016-05-06 05:49:19 +0000427INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000428 "PGO instrumentation.", false, false)
429INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
430INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Licc35bc92017-12-05 17:19:41 +0000431INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000432INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000433 "PGO instrumentation.", false, false)
434
Xinliang David Li8aebf442016-05-06 05:49:19 +0000435ModulePass *llvm::createPGOInstrumentationGenLegacyPass() {
436 return new PGOInstrumentationGenLegacyPass();
Rong Xuf430ae42015-12-09 18:08:16 +0000437}
438
Xinliang David Lid55827f2016-05-07 05:39:12 +0000439char PGOInstrumentationUseLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000440
Xinliang David Lid55827f2016-05-07 05:39:12 +0000441INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000442 "Read PGO instrumentation profile.", false, false)
443INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
444INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Licc35bc92017-12-05 17:19:41 +0000445INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000446INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000447 "Read PGO instrumentation profile.", false, false)
448
Xinliang David Lid55827f2016-05-07 05:39:12 +0000449ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) {
450 return new PGOInstrumentationUseLegacyPass(Filename.str());
Rong Xuf430ae42015-12-09 18:08:16 +0000451}
452
453namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000454
Rong Xuf430ae42015-12-09 18:08:16 +0000455/// \brief An MST based instrumentation for PGO
456///
457/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
458/// in the function level.
459struct PGOEdge {
460 // This class implements the CFG edges. Note the CFG can be a multi-graph.
461 // So there might be multiple edges with same SrcBB and DestBB.
462 const BasicBlock *SrcBB;
463 const BasicBlock *DestBB;
464 uint64_t Weight;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000465 bool InMST = false;
466 bool Removed = false;
467 bool IsCritical = false;
468
Rong Xuf430ae42015-12-09 18:08:16 +0000469 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000470 : SrcBB(Src), DestBB(Dest), Weight(W) {}
471
Rong Xuf430ae42015-12-09 18:08:16 +0000472 // Return the information string of an edge.
473 const std::string infoString() const {
474 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
475 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
476 }
477};
478
479// This class stores the auxiliary information for each BB.
480struct BBInfo {
481 BBInfo *Group;
482 uint32_t Index;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000483 uint32_t Rank = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000484
Eugene Zelenkofce43572017-10-21 00:57:46 +0000485 BBInfo(unsigned IX) : Group(this), Index(IX) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000486
487 // Return the information string of this object.
488 const std::string infoString() const {
489 return (Twine("Index=") + Twine(Index)).str();
490 }
491};
492
493// This class implements the CFG edges. Note the CFG can be a multi-graph.
494template <class Edge, class BBInfo> class FuncPGOInstrumentation {
495private:
496 Function &F;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000497
Rong Xu705f7772016-07-25 18:45:37 +0000498 // A map that stores the Comdat group in function F.
499 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000500
Eugene Zelenkofce43572017-10-21 00:57:46 +0000501 void computeCFGHash();
502 void renameComdatFunction();
503
Rong Xuf430ae42015-12-09 18:08:16 +0000504public:
Rong Xua3bbf962017-03-15 18:23:39 +0000505 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000506 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000507 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000508 std::string FuncName;
509 GlobalVariable *FuncNameVar;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000510
Rong Xuf430ae42015-12-09 18:08:16 +0000511 // CFG hash value for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000512 uint64_t FunctionHash = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000513
514 // The Minimum Spanning Tree of function CFG.
515 CFGMST<Edge, BBInfo> MST;
516
517 // Give an edge, find the BB that will be instrumented.
518 // Return nullptr if there is no BB to be instrumented.
519 BasicBlock *getInstrBB(Edge *E);
520
521 // Return the auxiliary BB information.
522 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
523
Rong Xua5b57452016-12-02 19:10:29 +0000524 // Return the auxiliary BB information if available.
525 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
526
Rong Xuf430ae42015-12-09 18:08:16 +0000527 // Dump edges and BB information.
528 void dumpInfo(std::string Str = "") const {
529 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000530 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000531 }
532
Rong Xu705f7772016-07-25 18:45:37 +0000533 FuncPGOInstrumentation(
534 Function &Func,
535 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
536 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
Xinliang David Licc35bc92017-12-05 17:19:41 +0000537 BlockFrequencyInfo *BFI = nullptr, LoopInfo *LI = nullptr)
Rong Xua3bbf962017-03-15 18:23:39 +0000538 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1),
Xinliang David Licc35bc92017-12-05 17:19:41 +0000539 SIVisitor(Func), MIVisitor(Func), MST(F, BPI, BFI, LI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000540 // This should be done before CFG hash computation.
541 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000542 MIVisitor.countMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000543 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
Rong Xu60faea12017-03-16 21:15:48 +0000544 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
Rong Xua3bbf962017-03-15 18:23:39 +0000545 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func);
Rong Xue60343d2017-03-17 18:07:26 +0000546 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000547
Rong Xuf430ae42015-12-09 18:08:16 +0000548 FuncName = getPGOFuncName(F);
549 computeCFGHash();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000550 if (!ComdatMembers.empty())
Rong Xu705f7772016-07-25 18:45:37 +0000551 renameComdatFunction();
Rong Xuf430ae42015-12-09 18:08:16 +0000552 DEBUG(dumpInfo("after CFGMST"));
553
554 NumOfPGOBB += MST.BBInfos.size();
555 for (auto &E : MST.AllEdges) {
556 if (E->Removed)
557 continue;
558 NumOfPGOEdge++;
559 if (!E->InMST)
560 NumOfPGOInstrument++;
561 }
562
563 if (CreateGlobalVar)
564 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000565 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000566
567 // Return the number of profile counters needed for the function.
568 unsigned getNumCounters() {
569 unsigned NumCounters = 0;
570 for (auto &E : this->MST.AllEdges) {
571 if (!E->InMST && !E->Removed)
572 NumCounters++;
573 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000574 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000575 }
Rong Xuf430ae42015-12-09 18:08:16 +0000576};
577
Eugene Zelenkofce43572017-10-21 00:57:46 +0000578} // end anonymous namespace
579
Rong Xuf430ae42015-12-09 18:08:16 +0000580// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
581// value of each BB in the CFG. The higher 32 bits record the number of edges.
582template <class Edge, class BBInfo>
583void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
584 std::vector<char> Indexes;
585 JamCRC JC;
586 for (auto &BB : F) {
587 const TerminatorInst *TI = BB.getTerminator();
588 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
589 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000590 auto BI = findBBInfo(Succ);
591 if (BI == nullptr)
592 continue;
593 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000594 for (int J = 0; J < 4; J++)
595 Indexes.push_back((char)(Index >> (J * 8)));
596 }
597 }
598 JC.update(Indexes);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000599 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000600 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu705f7772016-07-25 18:45:37 +0000601 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
Xinliang David Li8e436982017-07-21 21:36:25 +0000602 DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
603 << " CRC = " << JC.getCRC()
604 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
605 << ", Edges = " << MST.AllEdges.size()
606 << ", ICSites = " << ValueSites[IPVK_IndirectCallTarget].size()
607 << ", Hash = " << FunctionHash << "\n";);
Rong Xu705f7772016-07-25 18:45:37 +0000608}
609
610// Check if we can safely rename this Comdat function.
611static bool canRenameComdat(
612 Function &F,
613 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000614 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000615 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000616
617 // FIXME: Current only handle those Comdat groups that only containing one
618 // function and function aliases.
619 // (1) For a Comdat group containing multiple functions, we need to have a
620 // unique postfix based on the hashes for each function. There is a
621 // non-trivial code refactoring to do this efficiently.
622 // (2) Variables can not be renamed, so we can not rename Comdat function in a
623 // group including global vars.
624 Comdat *C = F.getComdat();
625 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
626 if (dyn_cast<GlobalAlias>(CM.second))
627 continue;
628 Function *FM = dyn_cast<Function>(CM.second);
629 if (FM != &F)
630 return false;
631 }
632 return true;
633}
634
635// Append the CFGHash to the Comdat function name.
636template <class Edge, class BBInfo>
637void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
638 if (!canRenameComdat(F, ComdatMembers))
639 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000640 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000641 std::string NewFuncName =
642 Twine(F.getName() + "." + Twine(FunctionHash)).str();
643 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000644 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000645 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
646 Comdat *NewComdat;
647 Module *M = F.getParent();
648 // For AvailableExternallyLinkage functions, change the linkage to
649 // LinkOnceODR and put them into comdat. This is because after renaming, there
650 // is no backup external copy available for the function.
651 if (!F.hasComdat()) {
652 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
653 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
654 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
655 F.setComdat(NewComdat);
656 return;
657 }
658
659 // This function belongs to a single function Comdat group.
660 Comdat *OrigComdat = F.getComdat();
661 std::string NewComdatName =
662 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
663 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
664 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
665
666 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
667 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
668 // For aliases, change the name directly.
669 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000670 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000671 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000672 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000673 continue;
674 }
675 // Must be a function.
676 Function *CF = dyn_cast<Function>(CM.second);
677 assert(CF);
678 CF->setComdat(NewComdat);
679 }
Rong Xuf430ae42015-12-09 18:08:16 +0000680}
681
682// Given a CFG E to be instrumented, find which BB to place the instrumented
683// code. The function will split the critical edge if necessary.
684template <class Edge, class BBInfo>
685BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
686 if (E->InMST || E->Removed)
687 return nullptr;
688
689 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
690 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
691 // For a fake edge, instrument the real BB.
692 if (SrcBB == nullptr)
693 return DestBB;
694 if (DestBB == nullptr)
695 return SrcBB;
696
697 // Instrument the SrcBB if it has a single successor,
698 // otherwise, the DestBB if this is not a critical edge.
699 TerminatorInst *TI = SrcBB->getTerminator();
700 if (TI->getNumSuccessors() <= 1)
701 return SrcBB;
702 if (!E->IsCritical)
703 return DestBB;
704
705 // For a critical edge, we have to split. Instrument the newly
706 // created BB.
707 NumOfPGOSplit++;
708 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "
709 << getBBInfo(DestBB).Index << "\n");
710 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
711 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
712 assert(InstrBB && "Critical edge is not split");
713
714 E->Removed = true;
715 return InstrBB;
716}
717
Rong Xued9fec72016-01-21 18:11:44 +0000718// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000719// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000720static void instrumentOneFunc(
721 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
Xinliang David Licc35bc92017-12-05 17:19:41 +0000722 LoopInfo *LI,
Rong Xu705f7772016-07-25 18:45:37 +0000723 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu705f7772016-07-25 18:45:37 +0000724 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
Xinliang David Licc35bc92017-12-05 17:19:41 +0000725 BFI, LI);
Xinliang David Lid1197612016-08-01 20:25:06 +0000726 unsigned NumCounters = FuncInfo.getNumCounters();
727
Rong Xuf430ae42015-12-09 18:08:16 +0000728 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000729 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000730 for (auto &E : FuncInfo.MST.AllEdges) {
731 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
732 if (!InstrBB)
733 continue;
734
735 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
736 assert(Builder.GetInsertPoint() != InstrBB->end() &&
737 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000738 Builder.CreateCall(
739 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000740 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xuf430ae42015-12-09 18:08:16 +0000741 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
742 Builder.getInt32(I++)});
743 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000744
745 // Now instrument select instructions:
746 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
747 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000748 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000749
750 if (DisableValueProfiling)
751 return;
752
753 unsigned NumIndirectCallSites = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000754 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000755 CallSite CS(I);
756 Value *Callee = CS.getCalledValue();
757 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
758 << NumIndirectCallSites << "\n");
759 IRBuilder<> Builder(I);
760 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
761 "Cannot get the Instrumentation point");
762 Builder.CreateCall(
763 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000764 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xued9fec72016-01-21 18:11:44 +0000765 Builder.getInt64(FuncInfo.FunctionHash),
766 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000767 Builder.getInt32(IPVK_IndirectCallTarget),
Rong Xued9fec72016-01-21 18:11:44 +0000768 Builder.getInt32(NumIndirectCallSites++)});
769 }
770 NumOfPGOICall += NumIndirectCallSites;
Rong Xu60faea12017-03-16 21:15:48 +0000771
772 // Now instrument memop intrinsic calls.
773 FuncInfo.MIVisitor.instrumentMemIntrinsics(
774 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000775}
776
Eugene Zelenkofce43572017-10-21 00:57:46 +0000777namespace {
778
Rong Xuf430ae42015-12-09 18:08:16 +0000779// This class represents a CFG edge in profile use compilation.
780struct PGOUseEdge : public PGOEdge {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000781 bool CountValid = false;
782 uint64_t CountValue = 0;
783
Rong Xuf430ae42015-12-09 18:08:16 +0000784 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000785 : PGOEdge(Src, Dest, W) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000786
787 // Set edge count value
788 void setEdgeCount(uint64_t Value) {
789 CountValue = Value;
790 CountValid = true;
791 }
792
793 // Return the information string for this object.
794 const std::string infoString() const {
795 if (!CountValid)
796 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000797 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
798 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000799 }
800};
801
Eugene Zelenkofce43572017-10-21 00:57:46 +0000802using DirectEdges = SmallVector<PGOUseEdge *, 2>;
Rong Xuf430ae42015-12-09 18:08:16 +0000803
804// This class stores the auxiliary information for each BB.
805struct UseBBInfo : public BBInfo {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000806 uint64_t CountValue = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000807 bool CountValid;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000808 int32_t UnknownCountInEdge = 0;
809 int32_t UnknownCountOutEdge = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000810 DirectEdges InEdges;
811 DirectEdges OutEdges;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000812
813 UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
814
Rong Xuf430ae42015-12-09 18:08:16 +0000815 UseBBInfo(unsigned IX, uint64_t C)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000816 : BBInfo(IX), CountValue(C), CountValid(true) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000817
818 // Set the profile count value for this BB.
819 void setBBInfoCount(uint64_t Value) {
820 CountValue = Value;
821 CountValid = true;
822 }
823
824 // Return the information string of this object.
825 const std::string infoString() const {
826 if (!CountValid)
827 return BBInfo::infoString();
828 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
829 }
830};
831
Eugene Zelenkofce43572017-10-21 00:57:46 +0000832} // end anonymous namespace
833
Rong Xuf430ae42015-12-09 18:08:16 +0000834// Sum up the count values for all the edges.
835static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
836 uint64_t Total = 0;
837 for (auto &E : Edges) {
838 if (E->Removed)
839 continue;
840 Total += E->CountValue;
841 }
842 return Total;
843}
844
Eugene Zelenkofce43572017-10-21 00:57:46 +0000845namespace {
846
Rong Xuf430ae42015-12-09 18:08:16 +0000847class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000848public:
Rong Xu705f7772016-07-25 18:45:37 +0000849 PGOUseFunc(Function &Func, Module *Modu,
850 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
851 BranchProbabilityInfo *BPI = nullptr,
Xinliang David Licc35bc92017-12-05 17:19:41 +0000852 BlockFrequencyInfo *BFIin = nullptr,
853 LoopInfo *LI = nullptr)
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000854 : F(Func), M(Modu), BFI(BFIin),
Xinliang David Licc35bc92017-12-05 17:19:41 +0000855 FuncInfo(Func, ComdatMembers, false, BPI, BFIin, LI),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000856 FreqAttr(FFA_Normal) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000857
858 // Read counts for the instrumented BB from profile.
859 bool readCounters(IndexedInstrProfReader *PGOReader);
860
861 // Populate the counts for all BBs.
862 void populateCounters();
863
864 // Set the branch weights based on the count values.
865 void setBranchWeights();
866
Rong Xua3bbf962017-03-15 18:23:39 +0000867 // Annotate the value profile call sites all all value kind.
868 void annotateValueSites();
869
870 // Annotate the value profile call sites for one value kind.
871 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000872
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000873 // Annotate the irreducible loop header weights.
874 void annotateIrrLoopHeaderWeights();
875
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000876 // The hotness of the function from the profile count.
877 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
878
879 // Return the function hotness from the profile.
880 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
881
Rong Xu705f7772016-07-25 18:45:37 +0000882 // Return the function hash.
883 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000884
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000885 // Return the profile record for this function;
886 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
887
Xinliang David Li4ca17332016-09-18 18:34:07 +0000888 // Return the auxiliary BB information.
889 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
890 return FuncInfo.getBBInfo(BB);
891 }
892
Rong Xua5b57452016-12-02 19:10:29 +0000893 // Return the auxiliary BB information if available.
894 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
895 return FuncInfo.findBBInfo(BB);
896 }
897
Xinliang David Lid289e452017-01-27 19:06:25 +0000898 Function &getFunc() const { return F; }
899
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000900 void dumpInfo(std::string Str = "") const {
901 FuncInfo.dumpInfo(Str);
902 }
903
Rong Xuf430ae42015-12-09 18:08:16 +0000904private:
905 Function &F;
906 Module *M;
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000907 BlockFrequencyInfo *BFI;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000908
Rong Xuf430ae42015-12-09 18:08:16 +0000909 // This member stores the shared information with class PGOGenFunc.
910 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
911
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000912 // The maximum count value in the profile. This is only used in PGO use
913 // compilation.
914 uint64_t ProgramMaxCount;
915
Rong Xu33308f92016-10-25 21:47:24 +0000916 // Position of counter that remains to be read.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000917 uint32_t CountPosition = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000918
919 // Total size of the profile count for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000920 uint32_t ProfileCountSize = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000921
Rong Xu13b01dc2016-02-10 18:24:45 +0000922 // ProfileRecord for this function.
923 InstrProfRecord ProfileRecord;
924
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000925 // Function hotness info derived from profile.
926 FuncFreqAttr FreqAttr;
927
Rong Xuf430ae42015-12-09 18:08:16 +0000928 // Find the Instrumented BB and set the value.
929 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
930
931 // Set the edge counter value for the unknown edge -- there should be only
932 // one unknown edge.
933 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
934
935 // Return FuncName string;
936 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000937
938 // Set the hot/cold inline hints based on the count values.
939 // FIXME: This function should be removed once the functionality in
940 // the inliner is implemented.
941 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
942 if (ProgramMaxCount == 0)
943 return;
944 // Threshold of the hot functions.
945 const BranchProbability HotFunctionThreshold(1, 100);
946 // Threshold of the cold functions.
947 const BranchProbability ColdFunctionThreshold(2, 10000);
948 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
949 FreqAttr = FFA_Hot;
950 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
951 FreqAttr = FFA_Cold;
952 }
Rong Xuf430ae42015-12-09 18:08:16 +0000953};
954
Eugene Zelenkofce43572017-10-21 00:57:46 +0000955} // end anonymous namespace
956
Rong Xuf430ae42015-12-09 18:08:16 +0000957// Visit all the edges and assign the count value for the instrumented
958// edges and the BB.
959void PGOUseFunc::setInstrumentedCounts(
960 const std::vector<uint64_t> &CountFromProfile) {
Xinliang David Lid1197612016-08-01 20:25:06 +0000961 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +0000962 // Use a worklist as we will update the vector during the iteration.
963 std::vector<PGOUseEdge *> WorkList;
964 for (auto &E : FuncInfo.MST.AllEdges)
965 WorkList.push_back(E.get());
966
967 uint32_t I = 0;
968 for (auto &E : WorkList) {
969 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
970 if (!InstrBB)
971 continue;
972 uint64_t CountValue = CountFromProfile[I++];
973 if (!E->Removed) {
974 getBBInfo(InstrBB).setBBInfoCount(CountValue);
975 E->setEdgeCount(CountValue);
976 continue;
977 }
978
979 // Need to add two new edges.
980 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
981 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
982 // Add new edge of SrcBB->InstrBB.
983 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
984 NewEdge.setEdgeCount(CountValue);
985 // Add new edge of InstrBB->DestBB.
986 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
987 NewEdge1.setEdgeCount(CountValue);
988 NewEdge1.InMST = true;
989 getBBInfo(InstrBB).setBBInfoCount(CountValue);
990 }
Rong Xu0a2a1312017-03-09 19:08:55 +0000991 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +0000992 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +0000993}
994
995// Set the count value for the unknown edge. There should be one and only one
996// unknown edge in Edges vector.
997void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
998 for (auto &E : Edges) {
999 if (E->CountValid)
1000 continue;
1001 E->setEdgeCount(Value);
1002
1003 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1004 getBBInfo(E->DestBB).UnknownCountInEdge--;
1005 return;
1006 }
1007 llvm_unreachable("Cannot find the unknown count edge");
1008}
1009
1010// Read the profile from ProfileFileName and assign the value to the
1011// instrumented BB and the edges. This function also updates ProgramMaxCount.
1012// Return true if the profile are successfully read, and false on errors.
1013bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {
1014 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +00001015 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +00001016 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001017 if (Error E = Result.takeError()) {
1018 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1019 auto Err = IPE.get();
1020 bool SkipWarning = false;
1021 if (Err == instrprof_error::unknown_function) {
1022 NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +00001023 SkipWarning = !PGOWarnMissing;
Vedant Kumar9152fd12016-05-19 03:54:45 +00001024 } else if (Err == instrprof_error::hash_mismatch ||
1025 Err == instrprof_error::malformed) {
1026 NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +00001027 SkipWarning =
1028 NoPGOWarnMismatch ||
1029 (NoPGOWarnMismatchComdat &&
1030 (F.hasComdat() ||
1031 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Vedant Kumar9152fd12016-05-19 03:54:45 +00001032 }
Rong Xuf430ae42015-12-09 18:08:16 +00001033
Vedant Kumar9152fd12016-05-19 03:54:45 +00001034 if (SkipWarning)
1035 return;
1036
1037 std::string Msg = IPE.message() + std::string(" ") + F.getName().str();
1038 Ctx.diagnose(
1039 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1040 });
Rong Xuf430ae42015-12-09 18:08:16 +00001041 return false;
1042 }
Rong Xu13b01dc2016-02-10 18:24:45 +00001043 ProfileRecord = std::move(Result.get());
1044 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +00001045
1046 NumOfPGOFunc++;
1047 DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1048 uint64_t ValueSum = 0;
1049 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1050 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
1051 ValueSum += CountFromProfile[I];
1052 }
1053
1054 DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
1055
1056 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1057 getBBInfo(nullptr).UnknownCountInEdge = 2;
1058
1059 setInstrumentedCounts(CountFromProfile);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001060 ProgramMaxCount = PGOReader->getMaximumFunctionCount();
Rong Xuf430ae42015-12-09 18:08:16 +00001061 return true;
1062}
1063
1064// Populate the counters from instrumented BBs to all BBs.
1065// In the end of this operation, all BBs should have a valid count value.
1066void PGOUseFunc::populateCounters() {
1067 // First set up Count variable for all BBs.
1068 for (auto &E : FuncInfo.MST.AllEdges) {
1069 if (E->Removed)
1070 continue;
1071
1072 const BasicBlock *SrcBB = E->SrcBB;
1073 const BasicBlock *DestBB = E->DestBB;
1074 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1075 UseBBInfo &DestInfo = getBBInfo(DestBB);
1076 SrcInfo.OutEdges.push_back(E.get());
1077 DestInfo.InEdges.push_back(E.get());
1078 SrcInfo.UnknownCountOutEdge++;
1079 DestInfo.UnknownCountInEdge++;
1080
1081 if (!E->CountValid)
1082 continue;
1083 DestInfo.UnknownCountInEdge--;
1084 SrcInfo.UnknownCountOutEdge--;
1085 }
1086
1087 bool Changes = true;
1088 unsigned NumPasses = 0;
1089 while (Changes) {
1090 NumPasses++;
1091 Changes = false;
1092
1093 // For efficient traversal, it's better to start from the end as most
1094 // of the instrumented edges are at the end.
1095 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +00001096 UseBBInfo *Count = findBBInfo(&BB);
1097 if (Count == nullptr)
1098 continue;
1099 if (!Count->CountValid) {
1100 if (Count->UnknownCountOutEdge == 0) {
1101 Count->CountValue = sumEdgeCount(Count->OutEdges);
1102 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001103 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +00001104 } else if (Count->UnknownCountInEdge == 0) {
1105 Count->CountValue = sumEdgeCount(Count->InEdges);
1106 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001107 Changes = true;
1108 }
1109 }
Rong Xua5b57452016-12-02 19:10:29 +00001110 if (Count->CountValid) {
1111 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001112 uint64_t Total = 0;
1113 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1114 // If the one of the successor block can early terminate (no-return),
1115 // we can end up with situation where out edge sum count is larger as
1116 // the source BB's count is collected by a post-dominated block.
1117 if (Count->CountValue > OutSum)
1118 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +00001119 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001120 Changes = true;
1121 }
Rong Xua5b57452016-12-02 19:10:29 +00001122 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001123 uint64_t Total = 0;
1124 uint64_t InSum = sumEdgeCount(Count->InEdges);
1125 if (Count->CountValue > InSum)
1126 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001127 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001128 Changes = true;
1129 }
1130 }
1131 }
1132 }
1133
1134 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001135#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001136 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001137 for (auto &BB : F) {
1138 auto BI = findBBInfo(&BB);
1139 if (BI == nullptr)
1140 continue;
1141 assert(BI->CountValid && "BB count is not valid");
1142 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001143#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001144 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Sean Silva02b9d892016-05-28 04:05:36 +00001145 F.setEntryCount(FuncEntryCount);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001146 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001147 for (auto &BB : F) {
1148 auto BI = findBBInfo(&BB);
1149 if (BI == nullptr)
1150 continue;
1151 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1152 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001153 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001154
Rong Xu33308f92016-10-25 21:47:24 +00001155 // Now annotate select instructions
1156 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1157 assert(CountPosition == ProfileCountSize);
1158
Rong Xuf430ae42015-12-09 18:08:16 +00001159 DEBUG(FuncInfo.dumpInfo("after reading profile."));
1160}
1161
1162// Assign the scaled count values to the BB with multiple out edges.
1163void PGOUseFunc::setBranchWeights() {
1164 // Generate MD_prof metadata for every branch instruction.
1165 DEBUG(dbgs() << "\nSetting branch weights.\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001166 for (auto &BB : F) {
1167 TerminatorInst *TI = BB.getTerminator();
1168 if (TI->getNumSuccessors() < 2)
1169 continue;
Rong Xu15848e52017-08-23 21:36:02 +00001170 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1171 isa<IndirectBrInst>(TI)))
Rong Xuf430ae42015-12-09 18:08:16 +00001172 continue;
1173 if (getBBInfo(&BB).CountValue == 0)
1174 continue;
1175
1176 // We have a non-zero Branch BB.
1177 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1178 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001179 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001180 uint64_t MaxCount = 0;
1181 for (unsigned s = 0; s < Size; s++) {
1182 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1183 const BasicBlock *SrcBB = E->SrcBB;
1184 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001185 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001186 continue;
1187 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1188 uint64_t EdgeCount = E->CountValue;
1189 if (EdgeCount > MaxCount)
1190 MaxCount = EdgeCount;
1191 EdgeCounts[SuccNum] = EdgeCount;
1192 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001193 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001194 }
1195}
Rong Xu13b01dc2016-02-10 18:24:45 +00001196
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001197static bool isIndirectBrTarget(BasicBlock *BB) {
1198 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1199 if (isa<IndirectBrInst>((*PI)->getTerminator()))
1200 return true;
1201 }
1202 return false;
1203}
1204
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001205void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1206 DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1207 // Find irr loop headers
1208 for (auto &BB : F) {
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001209 // As a heuristic also annotate indrectbr targets as they have a high chance
1210 // to become an irreducible loop header after the indirectbr tail
1211 // duplication.
1212 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001213 TerminatorInst *TI = BB.getTerminator();
1214 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1215 setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1216 }
1217 }
1218}
1219
Xinliang David Li4ca17332016-09-18 18:34:07 +00001220void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1221 Module *M = F.getParent();
1222 IRBuilder<> Builder(&SI);
1223 Type *Int64Ty = Builder.getInt64Ty();
1224 Type *I8PtrTy = Builder.getInt8PtrTy();
1225 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1226 Builder.CreateCall(
1227 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001228 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001229 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1230 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001231 ++(*CurCtrIdx);
1232}
1233
1234void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1235 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1236 assert(*CurCtrIdx < CountFromProfile.size() &&
1237 "Out of bound access of counters");
1238 uint64_t SCounts[2];
1239 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1240 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001241 uint64_t TotalCount = 0;
1242 auto BI = UseFunc->findBBInfo(SI.getParent());
1243 if (BI != nullptr)
1244 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001245 // False Count
1246 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1247 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001248 if (MaxCount)
1249 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001250}
1251
1252void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1253 if (!PGOInstrSelect)
1254 return;
1255 // FIXME: do not handle this yet.
1256 if (SI.getCondition()->getType()->isVectorTy())
1257 return;
1258
Xinliang David Li4ca17332016-09-18 18:34:07 +00001259 switch (Mode) {
1260 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001261 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001262 return;
1263 case VM_instrument:
1264 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001265 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001266 case VM_annotate:
1267 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001268 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001269 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001270
1271 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001272}
1273
Rong Xu60faea12017-03-16 21:15:48 +00001274void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1275 Module *M = F.getParent();
1276 IRBuilder<> Builder(&MI);
1277 Type *Int64Ty = Builder.getInt64Ty();
1278 Type *I8PtrTy = Builder.getInt8PtrTy();
1279 Value *Length = MI.getLength();
1280 assert(!dyn_cast<ConstantInt>(Length));
1281 Builder.CreateCall(
1282 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001283 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Ana Pazosf731bde2017-06-19 20:04:33 +00001284 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
Rong Xu60faea12017-03-16 21:15:48 +00001285 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1286 ++CurCtrId;
1287}
1288
1289void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1290 if (!PGOInstrMemOP)
1291 return;
1292 Value *Length = MI.getLength();
1293 // Not instrument constant length calls.
1294 if (dyn_cast<ConstantInt>(Length))
1295 return;
1296
1297 switch (Mode) {
1298 case VM_counting:
1299 NMemIs++;
1300 return;
1301 case VM_instrument:
1302 instrumentOneMemIntrinsic(MI);
1303 return;
1304 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001305 Candidates.push_back(&MI);
1306 return;
Rong Xu60faea12017-03-16 21:15:48 +00001307 }
1308 llvm_unreachable("Unknown visiting mode");
1309}
1310
Rong Xua3bbf962017-03-15 18:23:39 +00001311// Traverse all valuesites and annotate the instructions for all value kind.
1312void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001313 if (DisableValueProfiling)
1314 return;
1315
Rong Xu8e8fe852016-04-01 16:43:30 +00001316 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001317 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001318
Rong Xua3bbf962017-03-15 18:23:39 +00001319 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001320 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001321}
1322
1323// Annotate the instructions for a specific value kind.
1324void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1325 unsigned ValueSiteIndex = 0;
1326 auto &ValueSites = FuncInfo.ValueSites[Kind];
1327 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1328 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001329 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001330 Ctx.diagnose(DiagnosticInfoPGOProfile(
1331 M->getName().data(),
1332 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1333 " in " + F.getName().str(),
1334 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001335 return;
1336 }
1337
Rong Xua3bbf962017-03-15 18:23:39 +00001338 for (auto &I : ValueSites) {
1339 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1340 << "): Index = " << ValueSiteIndex << " out of "
1341 << NumValueSites << "\n");
1342 annotateValueSite(*M, *I, ProfileRecord,
1343 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001344 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1345 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001346 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001347 }
1348}
Rong Xuf430ae42015-12-09 18:08:16 +00001349
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001350// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
Rong Xu33c76c02016-02-10 17:18:30 +00001351// aware this is an ir_level profile so it can set the version flag.
1352static void createIRLevelProfileFlagVariable(Module &M) {
1353 Type *IntTy64 = Type::getInt64Ty(M.getContext());
1354 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
Rong Xu9e926e82016-02-29 19:16:04 +00001355 auto IRLevelVersionVariable = new GlobalVariable(
1356 M, IntTy64, true, GlobalVariable::ExternalLinkage,
1357 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)),
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001358 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
Rong Xu33c76c02016-02-10 17:18:30 +00001359 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1360 Triple TT(M.getTargetTriple());
Xinliang David Li11c849c2016-05-27 16:22:03 +00001361 if (!TT.supportsCOMDAT())
Rong Xuca28a0a2016-05-11 00:31:59 +00001362 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage);
Rong Xu33c76c02016-02-10 17:18:30 +00001363 else
Rong Xu9e926e82016-02-29 19:16:04 +00001364 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(
Xinliang David Lid382e9d2016-07-22 04:46:56 +00001365 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR))));
Rong Xu33c76c02016-02-10 17:18:30 +00001366}
1367
Rong Xu705f7772016-07-25 18:45:37 +00001368// Collect the set of members for each Comdat in module M and store
1369// in ComdatMembers.
1370static void collectComdatMembers(
1371 Module &M,
1372 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1373 if (!DoComdatRenaming)
1374 return;
1375 for (Function &F : M)
1376 if (Comdat *C = F.getComdat())
1377 ComdatMembers.insert(std::make_pair(C, &F));
1378 for (GlobalVariable &GV : M.globals())
1379 if (Comdat *C = GV.getComdat())
1380 ComdatMembers.insert(std::make_pair(C, &GV));
1381 for (GlobalAlias &GA : M.aliases())
1382 if (Comdat *C = GA.getComdat())
1383 ComdatMembers.insert(std::make_pair(C, &GA));
1384}
1385
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001386static bool InstrumentAllFunctions(
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001387 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Licc35bc92017-12-05 17:19:41 +00001388 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI,
1389 function_ref<LoopInfo *(Function &)> LookupLI) {
Rong Xu33c76c02016-02-10 17:18:30 +00001390 createIRLevelProfileFlagVariable(M);
Rong Xu705f7772016-07-25 18:45:37 +00001391 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1392 collectComdatMembers(M, ComdatMembers);
1393
Rong Xuf430ae42015-12-09 18:08:16 +00001394 for (auto &F : M) {
1395 if (F.isDeclaration())
1396 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001397 auto *BPI = LookupBPI(F);
1398 auto *BFI = LookupBFI(F);
Xinliang David Licc35bc92017-12-05 17:19:41 +00001399 auto *LI = LookupLI(F);
1400 instrumentOneFunc(F, &M, BPI, BFI, LI, ComdatMembers);
Rong Xuf430ae42015-12-09 18:08:16 +00001401 }
1402 return true;
1403}
1404
Xinliang David Li8aebf442016-05-06 05:49:19 +00001405bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001406 if (skipModule(M))
1407 return false;
1408
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001409 auto LookupBPI = [this](Function &F) {
1410 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001411 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001412 auto LookupBFI = [this](Function &F) {
1413 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001414 };
Xinliang David Licc35bc92017-12-05 17:19:41 +00001415 auto LookupLI = [this](Function &F) {
1416 return &this->getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
1417 };
1418 return InstrumentAllFunctions(M, LookupBPI, LookupBFI, LookupLI);
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001419}
1420
Xinliang David Li8aebf442016-05-06 05:49:19 +00001421PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001422 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001423 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001424 auto LookupBPI = [&FAM](Function &F) {
1425 return &FAM.getResult<BranchProbabilityAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001426 };
1427
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001428 auto LookupBFI = [&FAM](Function &F) {
1429 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001430 };
1431
Xinliang David Licc35bc92017-12-05 17:19:41 +00001432 auto LookupLI = [&FAM](Function &F) {
1433 return &FAM.getResult<LoopAnalysis>(F);
1434 };
1435
1436 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI, LookupLI))
Xinliang David Li8aebf442016-05-06 05:49:19 +00001437 return PreservedAnalyses::all();
1438
1439 return PreservedAnalyses::none();
1440}
1441
Xinliang David Lida195582016-05-10 21:59:52 +00001442static bool annotateAllFunctions(
1443 Module &M, StringRef ProfileFileName,
1444 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Xinliang David Licc35bc92017-12-05 17:19:41 +00001445 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI,
1446 function_ref<LoopInfo *(Function &)> LookupLI) {
Rong Xuf430ae42015-12-09 18:08:16 +00001447 DEBUG(dbgs() << "Read in profile counters: ");
1448 auto &Ctx = M.getContext();
1449 // Read the counter array from file.
1450 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001451 if (Error E = ReaderOrErr.takeError()) {
1452 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1453 Ctx.diagnose(
1454 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1455 });
Rong Xuf430ae42015-12-09 18:08:16 +00001456 return false;
1457 }
1458
Xinliang David Lida195582016-05-10 21:59:52 +00001459 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1460 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001461 if (!PGOReader) {
1462 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001463 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001464 return false;
1465 }
Rong Xu33c76c02016-02-10 17:18:30 +00001466 // TODO: might need to change the warning once the clang option is finalized.
1467 if (!PGOReader->isIRLevelProfile()) {
1468 Ctx.diagnose(DiagnosticInfoPGOProfile(
1469 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1470 return false;
1471 }
1472
Rong Xu705f7772016-07-25 18:45:37 +00001473 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1474 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001475 std::vector<Function *> HotFunctions;
1476 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001477 for (auto &F : M) {
1478 if (F.isDeclaration())
1479 continue;
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001480 auto *BPI = LookupBPI(F);
1481 auto *BFI = LookupBFI(F);
Xinliang David Licc35bc92017-12-05 17:19:41 +00001482 auto *LI = LookupLI(F);
1483 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI, LI);
Sean Silva2e8f0952016-05-28 04:19:40 +00001484 if (!Func.readCounters(PGOReader.get()))
1485 continue;
1486 Func.populateCounters();
1487 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001488 Func.annotateValueSites();
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001489 Func.annotateIrrLoopHeaderWeights();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001490 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1491 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001492 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001493 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1494 HotFunctions.push_back(&F);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001495 if (PGOViewCounts != PGOVCT_None &&
1496 (ViewBlockFreqFuncName.empty() ||
1497 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001498 LoopInfo LI{DominatorTree(F)};
1499 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1500 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1501 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1502 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001503 if (PGOViewCounts == PGOVCT_Graph)
1504 NewBFI->view();
1505 else if (PGOViewCounts == PGOVCT_Text) {
1506 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1507 NewBFI->print(dbgs());
1508 }
Xinliang David Licb253ce2017-01-23 18:58:24 +00001509 }
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001510 if (PGOViewRawCounts != PGOVCT_None &&
1511 (ViewBlockFreqFuncName.empty() ||
1512 F.getName().equals(ViewBlockFreqFuncName))) {
1513 if (PGOViewRawCounts == PGOVCT_Graph)
1514 if (ViewBlockFreqFuncName.empty())
1515 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1516 else
1517 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1518 else if (PGOViewRawCounts == PGOVCT_Text) {
1519 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1520 Func.dumpInfo();
1521 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001522 }
Rong Xuf430ae42015-12-09 18:08:16 +00001523 }
Easwaran Raman8bceb9d2016-06-21 19:29:49 +00001524 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext()));
Rong Xu6090afd2016-03-28 17:08:56 +00001525 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001526 // We have to apply these attributes at the end because their presence
1527 // can affect the BranchProbabilityInfo of any callers, resulting in an
1528 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001529 for (auto &F : HotFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001530 F->addFnAttr(Attribute::InlineHint);
Rong Xu6090afd2016-03-28 17:08:56 +00001531 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1532 << "\n");
1533 }
1534 for (auto &F : ColdFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001535 F->addFnAttr(Attribute::Cold);
Rong Xu6090afd2016-03-28 17:08:56 +00001536 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n");
1537 }
Rong Xuf430ae42015-12-09 18:08:16 +00001538 return true;
1539}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001540
Xinliang David Lida195582016-05-10 21:59:52 +00001541PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00001542 : ProfileFileName(std::move(Filename)) {
Xinliang David Lida195582016-05-10 21:59:52 +00001543 if (!PGOTestProfileFile.empty())
1544 ProfileFileName = PGOTestProfileFile;
1545}
1546
1547PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001548 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001549
1550 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1551 auto LookupBPI = [&FAM](Function &F) {
1552 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1553 };
1554
1555 auto LookupBFI = [&FAM](Function &F) {
1556 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1557 };
1558
Xinliang David Licc35bc92017-12-05 17:19:41 +00001559 auto LookupLI = [&FAM](Function &F) {
1560 return &FAM.getResult<LoopAnalysis>(F);
1561 };
1562
1563 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI, LookupLI))
Xinliang David Lida195582016-05-10 21:59:52 +00001564 return PreservedAnalyses::all();
1565
1566 return PreservedAnalyses::none();
1567}
1568
Xinliang David Lid55827f2016-05-07 05:39:12 +00001569bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1570 if (skipModule(M))
1571 return false;
1572
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001573 auto LookupBPI = [this](Function &F) {
1574 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001575 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001576 auto LookupBFI = [this](Function &F) {
1577 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001578 };
Xinliang David Licc35bc92017-12-05 17:19:41 +00001579 auto LookupLI = [this](Function &F) {
1580 return &this->getAnalysis<LoopInfoWrapperPass>(F).getLoopInfo();
1581 };
Xinliang David Lid55827f2016-05-07 05:39:12 +00001582
Xinliang David Licc35bc92017-12-05 17:19:41 +00001583 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI, LookupLI);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001584}
Xinliang David Lid289e452017-01-27 19:06:25 +00001585
Eugene Zelenkofce43572017-10-21 00:57:46 +00001586static std::string getSimpleNodeName(const BasicBlock *Node) {
1587 if (!Node->getName().empty())
1588 return Node->getName();
1589
1590 std::string SimpleNodeName;
1591 raw_string_ostream OS(SimpleNodeName);
1592 Node->printAsOperand(OS, false);
1593 return OS.str();
1594}
1595
1596void llvm::setProfMetadata(Module *M, Instruction *TI,
1597 ArrayRef<uint64_t> EdgeCounts,
1598 uint64_t MaxCount) {
Rong Xu48596b62017-04-04 16:42:20 +00001599 MDBuilder MDB(M->getContext());
1600 assert(MaxCount > 0 && "Bad max count");
1601 uint64_t Scale = calculateCountScale(MaxCount);
1602 SmallVector<unsigned, 4> Weights;
1603 for (const auto &ECI : EdgeCounts)
1604 Weights.push_back(scaleBranchCount(ECI, Scale));
1605
1606 DEBUG(dbgs() << "Weight is: ";
1607 for (const auto &W : Weights) { dbgs() << W << " "; }
1608 dbgs() << "\n";);
Eugene Zelenkofce43572017-10-21 00:57:46 +00001609 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001610 if (EmitBranchProbability) {
1611 std::string BrCondStr = getBranchCondString(TI);
1612 if (BrCondStr.empty())
1613 return;
1614
1615 unsigned WSum =
1616 std::accumulate(Weights.begin(), Weights.end(), 0,
1617 [](unsigned w1, unsigned w2) { return w1 + w2; });
1618 uint64_t TotalCount =
1619 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), 0,
1620 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
1621 BranchProbability BP(Weights[0], WSum);
1622 std::string BranchProbStr;
1623 raw_string_ostream OS(BranchProbStr);
1624 OS << BP;
1625 OS << " (total count : " << TotalCount << ")";
1626 OS.flush();
1627 Function *F = TI->getParent()->getParent();
Davide Italiano0c8d26c2017-07-20 20:43:05 +00001628 OptimizationRemarkEmitter ORE(F);
Vivek Pandya95906582017-10-11 17:12:59 +00001629 ORE.emit([&]() {
1630 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1631 << BrCondStr << " is true with probability : " << BranchProbStr;
1632 });
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001633 }
Rong Xu48596b62017-04-04 16:42:20 +00001634}
1635
Eugene Zelenkofce43572017-10-21 00:57:46 +00001636namespace llvm {
1637
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001638void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1639 MDBuilder MDB(M->getContext());
1640 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1641 MDB.createIrrLoopHeaderWeight(Count));
1642}
1643
Xinliang David Lid289e452017-01-27 19:06:25 +00001644template <> struct GraphTraits<PGOUseFunc *> {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001645 using NodeRef = const BasicBlock *;
1646 using ChildIteratorType = succ_const_iterator;
1647 using nodes_iterator = pointer_iterator<Function::const_iterator>;
Xinliang David Lid289e452017-01-27 19:06:25 +00001648
1649 static NodeRef getEntryNode(const PGOUseFunc *G) {
1650 return &G->getFunc().front();
1651 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001652
Xinliang David Lid289e452017-01-27 19:06:25 +00001653 static ChildIteratorType child_begin(const NodeRef N) {
1654 return succ_begin(N);
1655 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001656
Xinliang David Lid289e452017-01-27 19:06:25 +00001657 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001658
Xinliang David Lid289e452017-01-27 19:06:25 +00001659 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1660 return nodes_iterator(G->getFunc().begin());
1661 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001662
Xinliang David Lid289e452017-01-27 19:06:25 +00001663 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1664 return nodes_iterator(G->getFunc().end());
1665 }
1666};
1667
1668template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1669 explicit DOTGraphTraits(bool isSimple = false)
1670 : DefaultDOTGraphTraits(isSimple) {}
1671
1672 static std::string getGraphName(const PGOUseFunc *G) {
1673 return G->getFunc().getName();
1674 }
1675
1676 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1677 std::string Result;
1678 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001679
1680 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001681 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001682 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001683 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001684 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001685 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001686 OS << "Unknown\\l";
1687
1688 if (!PGOInstrSelect)
1689 return Result;
1690
1691 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1692 auto *I = &*BI;
1693 if (!isa<SelectInst>(I))
1694 continue;
1695 // Display scaled counts for SELECT instruction:
1696 OS << "SELECT : { T = ";
1697 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001698 bool HasProf = I->extractProfMetadata(TC, FC);
1699 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001700 OS << "Unknown, F = Unknown }\\l";
1701 else
1702 OS << TC << ", F = " << FC << " }\\l";
1703 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001704 return Result;
1705 }
1706};
Eugene Zelenkofce43572017-10-21 00:57:46 +00001707
1708} // end namespace llvm