blob: ac97f7fb9b2fb39ce5e6e361106aed57281aaa22 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Rong Xuf430ae42015-12-09 18:08:16 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements PGO instrumentation using a minimum spanning tree based
10// on the following paper:
11// [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
12// for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
13// Issue 3, pp 313-322
14// The idea of the algorithm based on the fact that for each node (except for
15// the entry and exit), the sum of incoming edge counts equals the sum of
16// outgoing edge counts. The count of edge on spanning tree can be derived from
17// those edges not on the spanning tree. Knuth proves this method instruments
18// the minimum number of edges.
19//
20// The minimal spanning tree here is actually a maximum weight tree -- on-tree
21// edges have higher frequencies (more likely to execute). The idea is to
22// instrument those less frequently executed edges to reduce the runtime
23// overhead of instrumented binaries.
24//
25// This file contains two passes:
26// (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
Rong Xu13b01dc2016-02-10 18:24:45 +000027// count profile, and generates the instrumentation for indirect call
28// profiling.
Rong Xuf430ae42015-12-09 18:08:16 +000029// (2) Pass PGOInstrumentationUse which reads the edge count profile and
Rong Xu13b01dc2016-02-10 18:24:45 +000030// annotates the branch weights. It also reads the indirect call value
31// profiling records and annotate the indirect call instructions.
32//
Rong Xuf430ae42015-12-09 18:08:16 +000033// To get the precise counter information, These two passes need to invoke at
34// the same compilation point (so they see the same IR). For pass
35// PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
36// pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
37// the profile is opened in module level and passed to each PGOUseFunc instance.
38// The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
39// in class FuncPGOInstrumentation.
40//
41// Class PGOEdge represents a CFG edge and some auxiliary information. Class
42// BBInfo contains auxiliary information for each BB. These two classes are used
43// in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
44// class of PGOEdge and BBInfo, respectively. They contains extra data structure
45// used in populating profile counters.
46// The MST implementation is in Class CFGMST (CFGMST.h).
47//
48//===----------------------------------------------------------------------===//
49
Rong Xuf430ae42015-12-09 18:08:16 +000050#include "CFGMST.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000051#include "llvm/ADT/APInt.h"
52#include "llvm/ADT/ArrayRef.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"
Eugene Zelenkofce43572017-10-21 00:57:46 +000056#include "llvm/ADT/StringRef.h"
Rong Xu33c76c02016-02-10 17:18:30 +000057#include "llvm/ADT/Triple.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000058#include "llvm/ADT/Twine.h"
59#include "llvm/ADT/iterator.h"
60#include "llvm/ADT/iterator_range.h"
Rong Xuf430ae42015-12-09 18:08:16 +000061#include "llvm/Analysis/BlockFrequencyInfo.h"
62#include "llvm/Analysis/BranchProbabilityInfo.h"
63#include "llvm/Analysis/CFG.h"
Chandler Carruth57578aa2019-01-07 07:15:51 +000064#include "llvm/Analysis/IndirectCallVisitor.h"
Xinliang David Licb253ce2017-01-23 18:58:24 +000065#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000066#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Rong Xu6cdf3d82019-02-27 17:24:33 +000067#include "llvm/Analysis/ProfileSummaryInfo.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000068#include "llvm/IR/Attributes.h"
69#include "llvm/IR/BasicBlock.h"
70#include "llvm/IR/CFG.h"
Rong Xued9fec72016-01-21 18:11:44 +000071#include "llvm/IR/CallSite.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000072#include "llvm/IR/Comdat.h"
73#include "llvm/IR/Constant.h"
74#include "llvm/IR/Constants.h"
Rong Xuf430ae42015-12-09 18:08:16 +000075#include "llvm/IR/DiagnosticInfo.h"
Xinliang David Lid289e452017-01-27 19:06:25 +000076#include "llvm/IR/Dominators.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000077#include "llvm/IR/Function.h"
78#include "llvm/IR/GlobalAlias.h"
Rong Xu705f7772016-07-25 18:45:37 +000079#include "llvm/IR/GlobalValue.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000080#include "llvm/IR/GlobalVariable.h"
Rong Xuf430ae42015-12-09 18:08:16 +000081#include "llvm/IR/IRBuilder.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000082#include "llvm/IR/InstVisitor.h"
83#include "llvm/IR/InstrTypes.h"
84#include "llvm/IR/Instruction.h"
Rong Xuf430ae42015-12-09 18:08:16 +000085#include "llvm/IR/Instructions.h"
86#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000087#include "llvm/IR/Intrinsics.h"
88#include "llvm/IR/LLVMContext.h"
Rong Xuf430ae42015-12-09 18:08:16 +000089#include "llvm/IR/MDBuilder.h"
90#include "llvm/IR/Module.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000091#include "llvm/IR/PassManager.h"
92#include "llvm/IR/ProfileSummary.h"
93#include "llvm/IR/Type.h"
94#include "llvm/IR/Value.h"
Rong Xuf430ae42015-12-09 18:08:16 +000095#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000096#include "llvm/ProfileData/InstrProf.h"
Rong Xuf430ae42015-12-09 18:08:16 +000097#include "llvm/ProfileData/InstrProfReader.h"
98#include "llvm/Support/BranchProbability.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000099#include "llvm/Support/Casting.h"
100#include "llvm/Support/CommandLine.h"
Xinliang David Lid289e452017-01-27 19:06:25 +0000101#include "llvm/Support/DOTGraphTraits.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000102#include "llvm/Support/Debug.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000103#include "llvm/Support/Error.h"
104#include "llvm/Support/ErrorHandling.h"
Xinliang David Lid289e452017-01-27 19:06:25 +0000105#include "llvm/Support/GraphWriter.h"
Rong Xuf430ae42015-12-09 18:08:16 +0000106#include "llvm/Support/JamCRC.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +0000107#include "llvm/Support/raw_ostream.h"
Rong Xued9fec72016-01-21 18:11:44 +0000108#include "llvm/Transforms/Instrumentation.h"
Jordan Rupprecht090683b2019-03-04 22:54:44 +0000109#include "llvm/Transforms/Instrumentation/PGOInstrumentation.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;
Easwaran Ramane5b8de22018-01-17 22:24:23 +0000122using ProfileCount = Function::ProfileCount;
Rong Xuf430ae42015-12-09 18:08:16 +0000123
124#define DEBUG_TYPE "pgo-instrumentation"
125
126STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
Xinliang David Li4ca17332016-09-18 18:34:07 +0000127STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
Rong Xu60faea12017-03-16 21:15:48 +0000128STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
Rong Xuf430ae42015-12-09 18:08:16 +0000129STATISTIC(NumOfPGOEdge, "Number of edges.");
130STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
131STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
132STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
133STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
134STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
Rong Xu13b01dc2016-02-10 18:24:45 +0000135STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
Rong Xu6cdf3d82019-02-27 17:24:33 +0000136STATISTIC(NumOfCSPGOInstrument, "Number of edges instrumented in CSPGO.");
137STATISTIC(NumOfCSPGOSelectInsts,
138 "Number of select instruction instrumented in CSPGO.");
139STATISTIC(NumOfCSPGOMemIntrinsics,
140 "Number of mem intrinsics instrumented in CSPGO.");
141STATISTIC(NumOfCSPGOEdge, "Number of edges in CSPGO.");
142STATISTIC(NumOfCSPGOBB, "Number of basic-blocks in CSPGO.");
143STATISTIC(NumOfCSPGOSplit, "Number of critical edge splits in CSPGO.");
144STATISTIC(NumOfCSPGOFunc,
145 "Number of functions having valid profile counts in CSPGO.");
146STATISTIC(NumOfCSPGOMismatch,
147 "Number of functions having mismatch profile in CSPGO.");
148STATISTIC(NumOfCSPGOMissing, "Number of functions without profile in CSPGO.");
Rong Xuf430ae42015-12-09 18:08:16 +0000149
150// Command line option to specify the file to read profile from. This is
151// mainly used for testing.
152static cl::opt<std::string>
153 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
154 cl::value_desc("filename"),
155 cl::desc("Specify the path of profile data file. This is"
156 "mainly for test purpose."));
Richard Smith6c676622018-10-10 23:13:47 +0000157static cl::opt<std::string> PGOTestProfileRemappingFile(
158 "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden,
159 cl::value_desc("filename"),
160 cl::desc("Specify the path of profile remapping file. This is mainly for "
161 "test purpose."));
Rong Xuf430ae42015-12-09 18:08:16 +0000162
Rong Xuecdc98f2016-03-04 22:08:44 +0000163// Command line option to disable value profiling. The default is false:
Rong Xu13b01dc2016-02-10 18:24:45 +0000164// i.e. value profiling is enabled by default. This is for debug purpose.
Rong Xu9e926e82016-02-29 19:16:04 +0000165static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
166 cl::Hidden,
167 cl::desc("Disable Value Profiling"));
Rong Xued9fec72016-01-21 18:11:44 +0000168
Rong Xuecdc98f2016-03-04 22:08:44 +0000169// Command line option to set the maximum number of VP annotations to write to
Rong Xu08afb052016-04-28 17:31:22 +0000170// the metadata for a single indirect call callsite.
171static cl::opt<unsigned> MaxNumAnnotations(
172 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore,
173 cl::desc("Max number of annotations for a single indirect "
174 "call callsite"));
Rong Xuecdc98f2016-03-04 22:08:44 +0000175
Rong Xue60343d2017-03-17 18:07:26 +0000176// Command line option to set the maximum number of value annotations
177// to write to the metadata for a single memop intrinsic.
178static cl::opt<unsigned> MaxNumMemOPAnnotations(
179 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore,
180 cl::desc("Max number of preicise value annotations for a single memop"
181 "intrinsic"));
182
Rong Xu705f7772016-07-25 18:45:37 +0000183// Command line option to control appending FunctionHash to the name of a COMDAT
184// function. This is to avoid the hash mismatch caused by the preinliner.
185static cl::opt<bool> DoComdatRenaming(
Rong Xu20f5df12017-01-11 20:19:41 +0000186 "do-comdat-renaming", cl::init(false), cl::Hidden,
Rong Xu705f7772016-07-25 18:45:37 +0000187 cl::desc("Append function hash to the name of COMDAT function to avoid "
188 "function hash mismatch due to the preinliner"));
189
Rong Xu0698de92016-05-13 17:26:06 +0000190// Command line option to enable/disable the warning about missing profile
191// information.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000192static cl::opt<bool>
193 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
194 cl::desc("Use this option to turn on/off "
195 "warnings about missing profile data for "
196 "functions."));
Rong Xu0698de92016-05-13 17:26:06 +0000197
198// Command line option to enable/disable the warning about a hash mismatch in
199// the profile data.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000200static cl::opt<bool>
201 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
202 cl::desc("Use this option to turn off/on "
203 "warnings about profile cfg mismatch."));
Rong Xu0698de92016-05-13 17:26:06 +0000204
Rong Xu20f5df12017-01-11 20:19:41 +0000205// Command line option to enable/disable the warning about a hash mismatch in
206// the profile data for Comdat functions, which often turns out to be false
207// positive due to the pre-instrumentation inline.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000208static cl::opt<bool>
209 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true),
210 cl::Hidden,
211 cl::desc("The option is used to turn on/off "
212 "warnings about hash mismatch for comdat "
213 "functions."));
Rong Xu20f5df12017-01-11 20:19:41 +0000214
Xinliang David Li4ca17332016-09-18 18:34:07 +0000215// Command line option to enable/disable select instruction instrumentation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000216static cl::opt<bool>
217 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
218 cl::desc("Use this option to turn on/off SELECT "
219 "instruction instrumentation. "));
Xinliang David Licb253ce2017-01-23 18:58:24 +0000220
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000221// Command line option to turn on CFG dot or text dump of raw profile counts
222static cl::opt<PGOViewCountsType> PGOViewRawCounts(
223 "pgo-view-raw-counts", cl::Hidden,
224 cl::desc("A boolean option to show CFG dag or text "
225 "with raw profile counts from "
226 "profile data. See also option "
227 "-pgo-view-counts. To limit graph "
228 "display to only one function, use "
229 "filtering option -view-bfi-func-name."),
230 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
231 clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
232 clEnumValN(PGOVCT_Text, "text", "show in text.")));
Xinliang David Lid289e452017-01-27 19:06:25 +0000233
Rong Xu8e06e802017-03-17 20:51:44 +0000234// Command line option to enable/disable memop intrinsic call.size profiling.
235static cl::opt<bool>
236 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
237 cl::desc("Use this option to turn on/off "
Teresa Johnsoncd2aa0d2017-05-24 17:55:25 +0000238 "memory intrinsic size profiling."));
Rong Xu60faea12017-03-16 21:15:48 +0000239
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000240// Emit branch probability as optimization remarks.
241static cl::opt<bool>
242 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
243 cl::desc("When this option is on, the annotated "
244 "branch probability will be emitted as "
Rong Xu662f38b2018-03-27 18:55:56 +0000245 "optimization remarks: -{Rpass|"
246 "pass-remarks}=pgo-instrumentation"));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000247
Xinliang David Licb253ce2017-01-23 18:58:24 +0000248// Command line option to turn on CFG dot dump after profile annotation.
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000249// Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000250extern cl::opt<PGOViewCountsType> PGOViewCounts;
Xinliang David Licb253ce2017-01-23 18:58:24 +0000251
Xinliang David Li58fcc9b2017-02-02 21:29:17 +0000252// Command line option to specify the name of the function for CFG dump
253// Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
254extern cl::opt<std::string> ViewBlockFreqFuncName;
255
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000256// Return a string describing the branch condition that can be
257// used in static branch probability heuristics:
Eugene Zelenkofce43572017-10-21 00:57:46 +0000258static std::string getBranchCondString(Instruction *TI) {
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000259 BranchInst *BI = dyn_cast<BranchInst>(TI);
260 if (!BI || !BI->isConditional())
261 return std::string();
262
263 Value *Cond = BI->getCondition();
264 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
265 if (!CI)
266 return std::string();
267
268 std::string result;
269 raw_string_ostream OS(result);
270 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
271 CI->getOperand(0)->getType()->print(OS, true);
272
273 Value *RHS = CI->getOperand(1);
274 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
275 if (CV) {
276 if (CV->isZero())
277 OS << "_Zero";
278 else if (CV->isOne())
279 OS << "_One";
Craig Topper79ab6432017-07-06 18:39:47 +0000280 else if (CV->isMinusOne())
Xinliang David Li0a0acbc2017-06-01 18:58:50 +0000281 OS << "_MinusOne";
282 else
283 OS << "_Const";
284 }
285 OS.flush();
286 return result;
287}
288
Eugene Zelenkofce43572017-10-21 00:57:46 +0000289namespace {
290
Xinliang David Li4ca17332016-09-18 18:34:07 +0000291/// The select instruction visitor plays three roles specified
292/// by the mode. In \c VM_counting mode, it simply counts the number of
293/// select instructions. In \c VM_instrument mode, it inserts code to count
294/// the number times TrueValue of select is taken. In \c VM_annotate mode,
295/// it reads the profile data and annotate the select instruction with metadata.
296enum VisitMode { VM_counting, VM_instrument, VM_annotate };
297class PGOUseFunc;
298
299/// Instruction Visitor class to visit select instructions.
300struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
301 Function &F;
302 unsigned NSIs = 0; // Number of select instructions instrumented.
303 VisitMode Mode = VM_counting; // Visiting mode.
304 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
305 unsigned TotalNumCtrs = 0; // Total number of counters
306 GlobalVariable *FuncNameVar = nullptr;
307 uint64_t FuncHash = 0;
308 PGOUseFunc *UseFunc = nullptr;
309
310 SelectInstVisitor(Function &Func) : F(Func) {}
311
312 void countSelects(Function &Func) {
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000313 NSIs = 0;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000314 Mode = VM_counting;
315 visit(Func);
316 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000317
Xinliang David Li4ca17332016-09-18 18:34:07 +0000318 // Visit the IR stream and instrument all select instructions. \p
319 // Ind is a pointer to the counter index variable; \p TotalNC
320 // is the total number of counters; \p FNV is the pointer to the
321 // PGO function name var; \p FHash is the function hash.
322 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
323 GlobalVariable *FNV, uint64_t FHash) {
324 Mode = VM_instrument;
325 CurCtrIdx = Ind;
326 TotalNumCtrs = TotalNC;
327 FuncHash = FHash;
328 FuncNameVar = FNV;
329 visit(Func);
330 }
331
332 // Visit the IR stream and annotate all select instructions.
333 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
334 Mode = VM_annotate;
335 UseFunc = UF;
336 CurCtrIdx = Ind;
337 visit(Func);
338 }
339
340 void instrumentOneSelectInst(SelectInst &SI);
341 void annotateOneSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000342
Xinliang David Li4ca17332016-09-18 18:34:07 +0000343 // Visit \p SI instruction and perform tasks according to visit mode.
344 void visitSelectInst(SelectInst &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000345
Vitaly Bukaca6ecd22017-03-15 23:07:41 +0000346 // Return the number of select instructions. This needs be called after
347 // countSelects().
Xinliang David Li4ca17332016-09-18 18:34:07 +0000348 unsigned getNumOfSelectInsts() const { return NSIs; }
349};
350
Rong Xu60faea12017-03-16 21:15:48 +0000351/// Instruction Visitor class to visit memory intrinsic calls.
352struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> {
353 Function &F;
354 unsigned NMemIs = 0; // Number of memIntrinsics instrumented.
355 VisitMode Mode = VM_counting; // Visiting mode.
356 unsigned CurCtrId = 0; // Current counter index.
357 unsigned TotalNumCtrs = 0; // Total number of counters
358 GlobalVariable *FuncNameVar = nullptr;
359 uint64_t FuncHash = 0;
360 PGOUseFunc *UseFunc = nullptr;
Rong Xue60343d2017-03-17 18:07:26 +0000361 std::vector<Instruction *> Candidates;
Rong Xu60faea12017-03-16 21:15:48 +0000362
363 MemIntrinsicVisitor(Function &Func) : F(Func) {}
364
365 void countMemIntrinsics(Function &Func) {
366 NMemIs = 0;
367 Mode = VM_counting;
368 visit(Func);
369 }
Rong Xue60343d2017-03-17 18:07:26 +0000370
Rong Xu60faea12017-03-16 21:15:48 +0000371 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC,
372 GlobalVariable *FNV, uint64_t FHash) {
373 Mode = VM_instrument;
374 TotalNumCtrs = TotalNC;
375 FuncHash = FHash;
376 FuncNameVar = FNV;
377 visit(Func);
378 }
379
Rong Xue60343d2017-03-17 18:07:26 +0000380 std::vector<Instruction *> findMemIntrinsics(Function &Func) {
381 Candidates.clear();
382 Mode = VM_annotate;
383 visit(Func);
384 return Candidates;
385 }
386
Rong Xu60faea12017-03-16 21:15:48 +0000387 // Visit the IR stream and annotate all mem intrinsic call instructions.
388 void instrumentOneMemIntrinsic(MemIntrinsic &MI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000389
Rong Xu60faea12017-03-16 21:15:48 +0000390 // Visit \p MI instruction and perform tasks according to visit mode.
391 void visitMemIntrinsic(MemIntrinsic &SI);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000392
Rong Xu60faea12017-03-16 21:15:48 +0000393 unsigned getNumOfMemIntrinsics() const { return NMemIs; }
394};
395
Xinliang David Li8aebf442016-05-06 05:49:19 +0000396class PGOInstrumentationGenLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000397public:
398 static char ID;
399
Rong Xu6cdf3d82019-02-27 17:24:33 +0000400 PGOInstrumentationGenLegacyPass(bool IsCS = false)
401 : ModulePass(ID), IsCS(IsCS) {
Xinliang David Li8aebf442016-05-06 05:49:19 +0000402 initializePGOInstrumentationGenLegacyPassPass(
403 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000404 }
405
Mehdi Amini117296c2016-10-01 02:56:57 +0000406 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000407
408private:
Rong Xu6cdf3d82019-02-27 17:24:33 +0000409 // Is this is context-sensitive instrumentation.
410 bool IsCS;
Rong Xuf430ae42015-12-09 18:08:16 +0000411 bool runOnModule(Module &M) override;
412
413 void getAnalysisUsage(AnalysisUsage &AU) const override {
414 AU.addRequired<BlockFrequencyInfoWrapperPass>();
415 }
416};
417
Xinliang David Lid55827f2016-05-07 05:39:12 +0000418class PGOInstrumentationUseLegacyPass : public ModulePass {
Rong Xuf430ae42015-12-09 18:08:16 +0000419public:
420 static char ID;
421
422 // Provide the profile filename as the parameter.
Rong Xu6cdf3d82019-02-27 17:24:33 +0000423 PGOInstrumentationUseLegacyPass(std::string Filename = "", bool IsCS = false)
424 : ModulePass(ID), ProfileFileName(std::move(Filename)), IsCS(IsCS) {
Rong Xuf430ae42015-12-09 18:08:16 +0000425 if (!PGOTestProfileFile.empty())
426 ProfileFileName = PGOTestProfileFile;
Xinliang David Lid55827f2016-05-07 05:39:12 +0000427 initializePGOInstrumentationUseLegacyPassPass(
428 *PassRegistry::getPassRegistry());
Rong Xuf430ae42015-12-09 18:08:16 +0000429 }
430
Mehdi Amini117296c2016-10-01 02:56:57 +0000431 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; }
Rong Xuf430ae42015-12-09 18:08:16 +0000432
433private:
434 std::string ProfileFileName;
Rong Xu6cdf3d82019-02-27 17:24:33 +0000435 // Is this is context-sensitive instrumentation use.
436 bool IsCS;
Rong Xuf430ae42015-12-09 18:08:16 +0000437
Xinliang David Lida195582016-05-10 21:59:52 +0000438 bool runOnModule(Module &M) override;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000439
Rong Xuf430ae42015-12-09 18:08:16 +0000440 void getAnalysisUsage(AnalysisUsage &AU) const override {
Rong Xu6cdf3d82019-02-27 17:24:33 +0000441 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Rong Xuf430ae42015-12-09 18:08:16 +0000442 AU.addRequired<BlockFrequencyInfoWrapperPass>();
443 }
444};
Xinliang David Li4ca17332016-09-18 18:34:07 +0000445
Rong Xu6cdf3d82019-02-27 17:24:33 +0000446class PGOInstrumentationGenCreateVarLegacyPass : public ModulePass {
447public:
448 static char ID;
449 StringRef getPassName() const override {
450 return "PGOInstrumentationGenCreateVarPass";
451 }
452 PGOInstrumentationGenCreateVarLegacyPass(std::string CSInstrName = "")
453 : ModulePass(ID), InstrProfileOutput(CSInstrName) {
454 initializePGOInstrumentationGenCreateVarLegacyPassPass(
455 *PassRegistry::getPassRegistry());
456 }
457
458private:
459 bool runOnModule(Module &M) override {
460 createProfileFileNameVar(M, InstrProfileOutput);
461 createIRLevelProfileFlagVar(M, true);
462 return false;
463 }
464 std::string InstrProfileOutput;
465};
466
Rong Xuf430ae42015-12-09 18:08:16 +0000467} // end anonymous namespace
468
Xinliang David Li8aebf442016-05-06 05:49:19 +0000469char PGOInstrumentationGenLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000470
Xinliang David Li8aebf442016-05-06 05:49:19 +0000471INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000472 "PGO instrumentation.", false, false)
473INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000474INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Xinliang David Li8aebf442016-05-06 05:49:19 +0000475INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen",
Rong Xuf430ae42015-12-09 18:08:16 +0000476 "PGO instrumentation.", false, false)
477
Rong Xu6cdf3d82019-02-27 17:24:33 +0000478ModulePass *llvm::createPGOInstrumentationGenLegacyPass(bool IsCS) {
479 return new PGOInstrumentationGenLegacyPass(IsCS);
Rong Xuf430ae42015-12-09 18:08:16 +0000480}
481
Xinliang David Lid55827f2016-05-07 05:39:12 +0000482char PGOInstrumentationUseLegacyPass::ID = 0;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000483
Xinliang David Lid55827f2016-05-07 05:39:12 +0000484INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000485 "Read PGO instrumentation profile.", false, false)
486INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Xinliang David Lid91057b2017-12-08 19:38:07 +0000487INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Rong Xu6cdf3d82019-02-27 17:24:33 +0000488INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Xinliang David Lid55827f2016-05-07 05:39:12 +0000489INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use",
Rong Xuf430ae42015-12-09 18:08:16 +0000490 "Read PGO instrumentation profile.", false, false)
491
Rong Xu6cdf3d82019-02-27 17:24:33 +0000492ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename,
493 bool IsCS) {
494 return new PGOInstrumentationUseLegacyPass(Filename.str(), IsCS);
495}
496
497char PGOInstrumentationGenCreateVarLegacyPass::ID = 0;
498
499INITIALIZE_PASS(PGOInstrumentationGenCreateVarLegacyPass,
500 "pgo-instr-gen-create-var",
501 "Create PGO instrumentation version variable for CSPGO.", false,
502 false)
503
504ModulePass *
505llvm::createPGOInstrumentationGenCreateVarLegacyPass(StringRef CSInstrName) {
506 return new PGOInstrumentationGenCreateVarLegacyPass(CSInstrName);
Rong Xuf430ae42015-12-09 18:08:16 +0000507}
508
509namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000510
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000511/// An MST based instrumentation for PGO
Rong Xuf430ae42015-12-09 18:08:16 +0000512///
513/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
514/// in the function level.
515struct PGOEdge {
516 // This class implements the CFG edges. Note the CFG can be a multi-graph.
517 // So there might be multiple edges with same SrcBB and DestBB.
518 const BasicBlock *SrcBB;
519 const BasicBlock *DestBB;
520 uint64_t Weight;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000521 bool InMST = false;
522 bool Removed = false;
523 bool IsCritical = false;
524
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000525 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000526 : SrcBB(Src), DestBB(Dest), Weight(W) {}
527
Rong Xuf430ae42015-12-09 18:08:16 +0000528 // Return the information string of an edge.
529 const std::string infoString() const {
530 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
531 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
532 }
533};
534
535// This class stores the auxiliary information for each BB.
536struct BBInfo {
537 BBInfo *Group;
538 uint32_t Index;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000539 uint32_t Rank = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000540
Eugene Zelenkofce43572017-10-21 00:57:46 +0000541 BBInfo(unsigned IX) : Group(this), Index(IX) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000542
543 // Return the information string of this object.
544 const std::string infoString() const {
545 return (Twine("Index=") + Twine(Index)).str();
546 }
547};
548
549// This class implements the CFG edges. Note the CFG can be a multi-graph.
550template <class Edge, class BBInfo> class FuncPGOInstrumentation {
551private:
552 Function &F;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000553
Rong Xu6cdf3d82019-02-27 17:24:33 +0000554 // Is this is context-sensitive instrumentation.
555 bool IsCS;
556
Rong Xu705f7772016-07-25 18:45:37 +0000557 // A map that stores the Comdat group in function F.
558 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
Rong Xuf430ae42015-12-09 18:08:16 +0000559
Eugene Zelenkofce43572017-10-21 00:57:46 +0000560 void computeCFGHash();
561 void renameComdatFunction();
562
Rong Xuf430ae42015-12-09 18:08:16 +0000563public:
Rong Xua3bbf962017-03-15 18:23:39 +0000564 std::vector<std::vector<Instruction *>> ValueSites;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000565 SelectInstVisitor SIVisitor;
Rong Xu60faea12017-03-16 21:15:48 +0000566 MemIntrinsicVisitor MIVisitor;
Rong Xuf430ae42015-12-09 18:08:16 +0000567 std::string FuncName;
568 GlobalVariable *FuncNameVar;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000569
Rong Xuf430ae42015-12-09 18:08:16 +0000570 // CFG hash value for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000571 uint64_t FunctionHash = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000572
573 // The Minimum Spanning Tree of function CFG.
574 CFGMST<Edge, BBInfo> MST;
575
576 // Give an edge, find the BB that will be instrumented.
577 // Return nullptr if there is no BB to be instrumented.
578 BasicBlock *getInstrBB(Edge *E);
579
580 // Return the auxiliary BB information.
581 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
582
Rong Xua5b57452016-12-02 19:10:29 +0000583 // Return the auxiliary BB information if available.
584 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
585
Rong Xuf430ae42015-12-09 18:08:16 +0000586 // Dump edges and BB information.
587 void dumpInfo(std::string Str = "") const {
588 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
Rong Xued9fec72016-01-21 18:11:44 +0000589 Twine(FunctionHash) + "\t" + Str);
Rong Xuf430ae42015-12-09 18:08:16 +0000590 }
591
Rong Xu705f7772016-07-25 18:45:37 +0000592 FuncPGOInstrumentation(
593 Function &Func,
594 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000595 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
Rong Xu6cdf3d82019-02-27 17:24:33 +0000596 BlockFrequencyInfo *BFI = nullptr, bool IsCS = false)
597 : F(Func), IsCS(IsCS), ComdatMembers(ComdatMembers),
598 ValueSites(IPVK_Last + 1), SIVisitor(Func), MIVisitor(Func),
599 MST(F, BPI, BFI) {
Xinliang David Li4ca17332016-09-18 18:34:07 +0000600 // This should be done before CFG hash computation.
601 SIVisitor.countSelects(Func);
Rong Xu60faea12017-03-16 21:15:48 +0000602 MIVisitor.countMemIntrinsics(Func);
Rong Xu6cdf3d82019-02-27 17:24:33 +0000603 if (!IsCS) {
604 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
605 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
606 NumOfPGOBB += MST.BBInfos.size();
607 ValueSites[IPVK_IndirectCallTarget] = findIndirectCalls(Func);
608 } else {
609 NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
610 NumOfCSPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics();
611 NumOfCSPGOBB += MST.BBInfos.size();
612 }
Rong Xue60343d2017-03-17 18:07:26 +0000613 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func);
Xinliang David Li4ca17332016-09-18 18:34:07 +0000614
Rong Xuf430ae42015-12-09 18:08:16 +0000615 FuncName = getPGOFuncName(F);
616 computeCFGHash();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000617 if (!ComdatMembers.empty())
Rong Xu705f7772016-07-25 18:45:37 +0000618 renameComdatFunction();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000619 LLVM_DEBUG(dumpInfo("after CFGMST"));
Rong Xuf430ae42015-12-09 18:08:16 +0000620
Rong Xuf430ae42015-12-09 18:08:16 +0000621 for (auto &E : MST.AllEdges) {
622 if (E->Removed)
623 continue;
Rong Xu6cdf3d82019-02-27 17:24:33 +0000624 IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++;
Rong Xuf430ae42015-12-09 18:08:16 +0000625 if (!E->InMST)
Rong Xu6cdf3d82019-02-27 17:24:33 +0000626 IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++;
Rong Xuf430ae42015-12-09 18:08:16 +0000627 }
628
629 if (CreateGlobalVar)
630 FuncNameVar = createPGOFuncNameVar(F, FuncName);
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000631 }
Xinliang David Lid1197612016-08-01 20:25:06 +0000632
633 // Return the number of profile counters needed for the function.
634 unsigned getNumCounters() {
635 unsigned NumCounters = 0;
636 for (auto &E : this->MST.AllEdges) {
637 if (!E->InMST && !E->Removed)
638 NumCounters++;
639 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000640 return NumCounters + SIVisitor.getNumOfSelectInsts();
Xinliang David Lid1197612016-08-01 20:25:06 +0000641 }
Rong Xuf430ae42015-12-09 18:08:16 +0000642};
643
Eugene Zelenkofce43572017-10-21 00:57:46 +0000644} // end anonymous namespace
645
Rong Xuf430ae42015-12-09 18:08:16 +0000646// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
647// value of each BB in the CFG. The higher 32 bits record the number of edges.
648template <class Edge, class BBInfo>
649void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
650 std::vector<char> Indexes;
651 JamCRC JC;
652 for (auto &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000653 const Instruction *TI = BB.getTerminator();
Rong Xuf430ae42015-12-09 18:08:16 +0000654 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
655 BasicBlock *Succ = TI->getSuccessor(I);
Rong Xua5b57452016-12-02 19:10:29 +0000656 auto BI = findBBInfo(Succ);
657 if (BI == nullptr)
658 continue;
659 uint32_t Index = BI->Index;
Rong Xuf430ae42015-12-09 18:08:16 +0000660 for (int J = 0; J < 4; J++)
661 Indexes.push_back((char)(Index >> (J * 8)));
662 }
663 }
664 JC.update(Indexes);
Rong Xu6cdf3d82019-02-27 17:24:33 +0000665
666 // Hash format for context sensitive profile. Reserve 4 bits for other
667 // information.
Xinliang David Li4ca17332016-09-18 18:34:07 +0000668 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
Rong Xua3bbf962017-03-15 18:23:39 +0000669 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
Rong Xu6cdf3d82019-02-27 17:24:33 +0000670 //(uint64_t)ValueSites[IPVK_MemOPSize].size() << 40 |
Rong Xu705f7772016-07-25 18:45:37 +0000671 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
Rong Xu6cdf3d82019-02-27 17:24:33 +0000672 // Reserve bit 60-63 for other information purpose.
673 FunctionHash &= 0x0FFFFFFFFFFFFFFF;
674 if (IsCS)
675 NamedInstrProfRecord::setCSFlagInHash(FunctionHash);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000676 LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
677 << " CRC = " << JC.getCRC()
678 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
679 << ", Edges = " << MST.AllEdges.size() << ", ICSites = "
680 << ValueSites[IPVK_IndirectCallTarget].size()
681 << ", Hash = " << FunctionHash << "\n";);
Rong Xu705f7772016-07-25 18:45:37 +0000682}
683
684// Check if we can safely rename this Comdat function.
685static bool canRenameComdat(
686 Function &F,
687 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
Rong Xu20f5df12017-01-11 20:19:41 +0000688 if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
Rong Xu705f7772016-07-25 18:45:37 +0000689 return false;
Rong Xu705f7772016-07-25 18:45:37 +0000690
691 // FIXME: Current only handle those Comdat groups that only containing one
692 // function and function aliases.
693 // (1) For a Comdat group containing multiple functions, we need to have a
694 // unique postfix based on the hashes for each function. There is a
695 // non-trivial code refactoring to do this efficiently.
696 // (2) Variables can not be renamed, so we can not rename Comdat function in a
697 // group including global vars.
698 Comdat *C = F.getComdat();
699 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
700 if (dyn_cast<GlobalAlias>(CM.second))
701 continue;
702 Function *FM = dyn_cast<Function>(CM.second);
703 if (FM != &F)
704 return false;
705 }
706 return true;
707}
708
709// Append the CFGHash to the Comdat function name.
710template <class Edge, class BBInfo>
711void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
712 if (!canRenameComdat(F, ComdatMembers))
713 return;
Rong Xu0e79f7d2016-10-06 20:38:13 +0000714 std::string OrigName = F.getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000715 std::string NewFuncName =
716 Twine(F.getName() + "." + Twine(FunctionHash)).str();
717 F.setName(Twine(NewFuncName));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000718 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
Rong Xu705f7772016-07-25 18:45:37 +0000719 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
720 Comdat *NewComdat;
721 Module *M = F.getParent();
722 // For AvailableExternallyLinkage functions, change the linkage to
723 // LinkOnceODR and put them into comdat. This is because after renaming, there
724 // is no backup external copy available for the function.
725 if (!F.hasComdat()) {
726 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
727 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
728 F.setLinkage(GlobalValue::LinkOnceODRLinkage);
729 F.setComdat(NewComdat);
730 return;
731 }
732
733 // This function belongs to a single function Comdat group.
734 Comdat *OrigComdat = F.getComdat();
735 std::string NewComdatName =
736 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
737 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
738 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
739
740 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
741 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) {
742 // For aliases, change the name directly.
743 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F);
Rong Xu0e79f7d2016-10-06 20:38:13 +0000744 std::string OrigGAName = GA->getName().str();
Rong Xu705f7772016-07-25 18:45:37 +0000745 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash)));
Rong Xu0e79f7d2016-10-06 20:38:13 +0000746 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA);
Rong Xu705f7772016-07-25 18:45:37 +0000747 continue;
748 }
749 // Must be a function.
750 Function *CF = dyn_cast<Function>(CM.second);
751 assert(CF);
752 CF->setComdat(NewComdat);
753 }
Rong Xuf430ae42015-12-09 18:08:16 +0000754}
755
756// Given a CFG E to be instrumented, find which BB to place the instrumented
757// code. The function will split the critical edge if necessary.
758template <class Edge, class BBInfo>
759BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
760 if (E->InMST || E->Removed)
761 return nullptr;
762
763 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
764 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
765 // For a fake edge, instrument the real BB.
766 if (SrcBB == nullptr)
767 return DestBB;
768 if (DestBB == nullptr)
769 return SrcBB;
770
771 // Instrument the SrcBB if it has a single successor,
772 // otherwise, the DestBB if this is not a critical edge.
Chandler Carruthedb12a82018-10-15 10:04:59 +0000773 Instruction *TI = SrcBB->getTerminator();
Rong Xuf430ae42015-12-09 18:08:16 +0000774 if (TI->getNumSuccessors() <= 1)
775 return SrcBB;
776 if (!E->IsCritical)
777 return DestBB;
778
779 // For a critical edge, we have to split. Instrument the newly
780 // created BB.
Rong Xu6cdf3d82019-02-27 17:24:33 +0000781 IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000782 LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
783 << " --> " << getBBInfo(DestBB).Index << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +0000784 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
785 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);
786 assert(InstrBB && "Critical edge is not split");
787
788 E->Removed = true;
789 return InstrBB;
790}
791
Rong Xued9fec72016-01-21 18:11:44 +0000792// Visit all edge and instrument the edges not in MST, and do value profiling.
Rong Xuf430ae42015-12-09 18:08:16 +0000793// Critical edges will be split.
Rong Xu705f7772016-07-25 18:45:37 +0000794static void instrumentOneFunc(
Xinliang David Lid91057b2017-12-08 19:38:07 +0000795 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI,
Rong Xu6cdf3d82019-02-27 17:24:33 +0000796 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
797 bool IsCS) {
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000798 // Split indirectbr critical edges here before computing the MST rather than
799 // later in getInstrBB() to avoid invalidating it.
800 SplitIndirectBrCriticalEdges(F, BPI, BFI);
Rong Xu6cdf3d82019-02-27 17:24:33 +0000801
Xinliang David Lid91057b2017-12-08 19:38:07 +0000802 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI,
Rong Xu6cdf3d82019-02-27 17:24:33 +0000803 BFI, IsCS);
Xinliang David Lid1197612016-08-01 20:25:06 +0000804 unsigned NumCounters = FuncInfo.getNumCounters();
805
Rong Xuf430ae42015-12-09 18:08:16 +0000806 uint32_t I = 0;
Rong Xued9fec72016-01-21 18:11:44 +0000807 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
Rong Xuf430ae42015-12-09 18:08:16 +0000808 for (auto &E : FuncInfo.MST.AllEdges) {
809 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get());
810 if (!InstrBB)
811 continue;
812
813 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
814 assert(Builder.GetInsertPoint() != InstrBB->end() &&
815 "Cannot get the Instrumentation point");
Rong Xuf430ae42015-12-09 18:08:16 +0000816 Builder.CreateCall(
817 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000818 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xuf430ae42015-12-09 18:08:16 +0000819 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),
820 Builder.getInt32(I++)});
821 }
Xinliang David Li4ca17332016-09-18 18:34:07 +0000822
823 // Now instrument select instructions:
824 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
825 FuncInfo.FunctionHash);
Xinliang David Lid1197612016-08-01 20:25:06 +0000826 assert(I == NumCounters);
Rong Xued9fec72016-01-21 18:11:44 +0000827
828 if (DisableValueProfiling)
829 return;
830
Chandler Carruth57578aa2019-01-07 07:15:51 +0000831 unsigned NumIndirectCalls = 0;
Rong Xua3bbf962017-03-15 18:23:39 +0000832 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) {
Rong Xued9fec72016-01-21 18:11:44 +0000833 CallSite CS(I);
834 Value *Callee = CS.getCalledValue();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000835 LLVM_DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = "
Chandler Carruth57578aa2019-01-07 07:15:51 +0000836 << NumIndirectCalls << "\n");
Rong Xued9fec72016-01-21 18:11:44 +0000837 IRBuilder<> Builder(I);
838 assert(Builder.GetInsertPoint() != I->getParent()->end() &&
839 "Cannot get the Instrumentation point");
840 Builder.CreateCall(
841 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +0000842 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
Rong Xued9fec72016-01-21 18:11:44 +0000843 Builder.getInt64(FuncInfo.FunctionHash),
844 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()),
Rong Xua3bbf962017-03-15 18:23:39 +0000845 Builder.getInt32(IPVK_IndirectCallTarget),
Chandler Carruth57578aa2019-01-07 07:15:51 +0000846 Builder.getInt32(NumIndirectCalls++)});
Rong Xued9fec72016-01-21 18:11:44 +0000847 }
Chandler Carruth57578aa2019-01-07 07:15:51 +0000848 NumOfPGOICall += NumIndirectCalls;
Rong Xu60faea12017-03-16 21:15:48 +0000849
850 // Now instrument memop intrinsic calls.
851 FuncInfo.MIVisitor.instrumentMemIntrinsics(
852 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash);
Rong Xuf430ae42015-12-09 18:08:16 +0000853}
854
Eugene Zelenkofce43572017-10-21 00:57:46 +0000855namespace {
856
Rong Xuf430ae42015-12-09 18:08:16 +0000857// This class represents a CFG edge in profile use compilation.
858struct PGOUseEdge : public PGOEdge {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000859 bool CountValid = false;
860 uint64_t CountValue = 0;
861
Xinliang David Lifa3f1a12017-12-10 07:39:53 +0000862 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000863 : PGOEdge(Src, Dest, W) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000864
865 // Set edge count value
866 void setEdgeCount(uint64_t Value) {
867 CountValue = Value;
868 CountValid = true;
869 }
870
871 // Return the information string for this object.
872 const std::string infoString() const {
873 if (!CountValid)
874 return PGOEdge::infoString();
Rong Xu9e926e82016-02-29 19:16:04 +0000875 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
876 .str();
Rong Xuf430ae42015-12-09 18:08:16 +0000877 }
878};
879
Eugene Zelenkofce43572017-10-21 00:57:46 +0000880using DirectEdges = SmallVector<PGOUseEdge *, 2>;
Rong Xuf430ae42015-12-09 18:08:16 +0000881
882// This class stores the auxiliary information for each BB.
883struct UseBBInfo : public BBInfo {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000884 uint64_t CountValue = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000885 bool CountValid;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000886 int32_t UnknownCountInEdge = 0;
887 int32_t UnknownCountOutEdge = 0;
Rong Xuf430ae42015-12-09 18:08:16 +0000888 DirectEdges InEdges;
889 DirectEdges OutEdges;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000890
891 UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
892
Rong Xuf430ae42015-12-09 18:08:16 +0000893 UseBBInfo(unsigned IX, uint64_t C)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000894 : BBInfo(IX), CountValue(C), CountValid(true) {}
Rong Xuf430ae42015-12-09 18:08:16 +0000895
896 // Set the profile count value for this BB.
897 void setBBInfoCount(uint64_t Value) {
898 CountValue = Value;
899 CountValid = true;
900 }
901
902 // Return the information string of this object.
903 const std::string infoString() const {
904 if (!CountValid)
905 return BBInfo::infoString();
906 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
907 }
908};
909
Eugene Zelenkofce43572017-10-21 00:57:46 +0000910} // end anonymous namespace
911
Rong Xuf430ae42015-12-09 18:08:16 +0000912// Sum up the count values for all the edges.
913static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
914 uint64_t Total = 0;
915 for (auto &E : Edges) {
916 if (E->Removed)
917 continue;
918 Total += E->CountValue;
919 }
920 return Total;
921}
922
Eugene Zelenkofce43572017-10-21 00:57:46 +0000923namespace {
924
Rong Xuf430ae42015-12-09 18:08:16 +0000925class PGOUseFunc {
Rong Xu6090afd2016-03-28 17:08:56 +0000926public:
Rong Xu705f7772016-07-25 18:45:37 +0000927 PGOUseFunc(Function &Func, Module *Modu,
928 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
Xinliang David Lid91057b2017-12-08 19:38:07 +0000929 BranchProbabilityInfo *BPI = nullptr,
Rong Xu6cdf3d82019-02-27 17:24:33 +0000930 BlockFrequencyInfo *BFIin = nullptr, bool IsCS = false)
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000931 : F(Func), M(Modu), BFI(BFIin),
Rong Xu6cdf3d82019-02-27 17:24:33 +0000932 FuncInfo(Func, ComdatMembers, false, BPI, BFIin, IsCS),
933 FreqAttr(FFA_Normal), IsCS(IsCS) {}
Rong Xu6090afd2016-03-28 17:08:56 +0000934
935 // Read counts for the instrumented BB from profile.
Rong Xufb4bcc42018-11-07 23:51:20 +0000936 bool readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros);
Rong Xu6090afd2016-03-28 17:08:56 +0000937
938 // Populate the counts for all BBs.
939 void populateCounters();
940
941 // Set the branch weights based on the count values.
942 void setBranchWeights();
943
Hiroshi Inoueae179002018-04-14 08:59:00 +0000944 // Annotate the value profile call sites for all value kind.
Rong Xua3bbf962017-03-15 18:23:39 +0000945 void annotateValueSites();
946
947 // Annotate the value profile call sites for one value kind.
948 void annotateValueSites(uint32_t Kind);
Rong Xu6090afd2016-03-28 17:08:56 +0000949
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000950 // Annotate the irreducible loop header weights.
951 void annotateIrrLoopHeaderWeights();
952
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000953 // The hotness of the function from the profile count.
954 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
955
956 // Return the function hotness from the profile.
957 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
958
Rong Xu705f7772016-07-25 18:45:37 +0000959 // Return the function hash.
960 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000961
Easwaran Raman5fe04a12016-05-26 22:57:11 +0000962 // Return the profile record for this function;
963 InstrProfRecord &getProfileRecord() { return ProfileRecord; }
964
Xinliang David Li4ca17332016-09-18 18:34:07 +0000965 // Return the auxiliary BB information.
966 UseBBInfo &getBBInfo(const BasicBlock *BB) const {
967 return FuncInfo.getBBInfo(BB);
968 }
969
Rong Xua5b57452016-12-02 19:10:29 +0000970 // Return the auxiliary BB information if available.
971 UseBBInfo *findBBInfo(const BasicBlock *BB) const {
972 return FuncInfo.findBBInfo(BB);
973 }
974
Xinliang David Lid289e452017-01-27 19:06:25 +0000975 Function &getFunc() const { return F; }
976
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +0000977 void dumpInfo(std::string Str = "") const {
978 FuncInfo.dumpInfo(Str);
979 }
980
Rong Xufb4bcc42018-11-07 23:51:20 +0000981 uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
Rong Xuf430ae42015-12-09 18:08:16 +0000982private:
983 Function &F;
984 Module *M;
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +0000985 BlockFrequencyInfo *BFI;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000986
Rong Xuf430ae42015-12-09 18:08:16 +0000987 // This member stores the shared information with class PGOGenFunc.
988 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
989
Sean Silva9dd4b5c2016-05-28 03:56:25 +0000990 // The maximum count value in the profile. This is only used in PGO use
991 // compilation.
992 uint64_t ProgramMaxCount;
993
Rong Xu33308f92016-10-25 21:47:24 +0000994 // Position of counter that remains to be read.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000995 uint32_t CountPosition = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000996
997 // Total size of the profile count for this function.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000998 uint32_t ProfileCountSize = 0;
Rong Xu33308f92016-10-25 21:47:24 +0000999
Rong Xu13b01dc2016-02-10 18:24:45 +00001000 // ProfileRecord for this function.
1001 InstrProfRecord ProfileRecord;
1002
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001003 // Function hotness info derived from profile.
1004 FuncFreqAttr FreqAttr;
1005
Rong Xu6cdf3d82019-02-27 17:24:33 +00001006 // Is to use the context sensitive profile.
1007 bool IsCS;
1008
Rong Xuf430ae42015-12-09 18:08:16 +00001009 // Find the Instrumented BB and set the value.
1010 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
1011
1012 // Set the edge counter value for the unknown edge -- there should be only
1013 // one unknown edge.
1014 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
1015
1016 // Return FuncName string;
1017 const std::string getFuncName() const { return FuncInfo.FuncName; }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001018
1019 // Set the hot/cold inline hints based on the count values.
1020 // FIXME: This function should be removed once the functionality in
1021 // the inliner is implemented.
1022 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
1023 if (ProgramMaxCount == 0)
1024 return;
1025 // Threshold of the hot functions.
1026 const BranchProbability HotFunctionThreshold(1, 100);
1027 // Threshold of the cold functions.
1028 const BranchProbability ColdFunctionThreshold(2, 10000);
1029 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))
1030 FreqAttr = FFA_Hot;
1031 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))
1032 FreqAttr = FFA_Cold;
1033 }
Rong Xuf430ae42015-12-09 18:08:16 +00001034};
1035
Eugene Zelenkofce43572017-10-21 00:57:46 +00001036} // end anonymous namespace
1037
Rong Xuf430ae42015-12-09 18:08:16 +00001038// Visit all the edges and assign the count value for the instrumented
1039// edges and the BB.
1040void PGOUseFunc::setInstrumentedCounts(
1041 const std::vector<uint64_t> &CountFromProfile) {
Xinliang David Lid1197612016-08-01 20:25:06 +00001042 assert(FuncInfo.getNumCounters() == CountFromProfile.size());
Rong Xuf430ae42015-12-09 18:08:16 +00001043 // Use a worklist as we will update the vector during the iteration.
1044 std::vector<PGOUseEdge *> WorkList;
1045 for (auto &E : FuncInfo.MST.AllEdges)
1046 WorkList.push_back(E.get());
1047
1048 uint32_t I = 0;
1049 for (auto &E : WorkList) {
1050 BasicBlock *InstrBB = FuncInfo.getInstrBB(E);
1051 if (!InstrBB)
1052 continue;
1053 uint64_t CountValue = CountFromProfile[I++];
1054 if (!E->Removed) {
1055 getBBInfo(InstrBB).setBBInfoCount(CountValue);
1056 E->setEdgeCount(CountValue);
1057 continue;
1058 }
1059
1060 // Need to add two new edges.
1061 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
1062 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
1063 // Add new edge of SrcBB->InstrBB.
1064 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);
1065 NewEdge.setEdgeCount(CountValue);
1066 // Add new edge of InstrBB->DestBB.
1067 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);
1068 NewEdge1.setEdgeCount(CountValue);
1069 NewEdge1.InMST = true;
1070 getBBInfo(InstrBB).setBBInfoCount(CountValue);
1071 }
Rong Xu0a2a1312017-03-09 19:08:55 +00001072 ProfileCountSize = CountFromProfile.size();
Rong Xu33308f92016-10-25 21:47:24 +00001073 CountPosition = I;
Rong Xuf430ae42015-12-09 18:08:16 +00001074}
1075
1076// Set the count value for the unknown edge. There should be one and only one
1077// unknown edge in Edges vector.
1078void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
1079 for (auto &E : Edges) {
1080 if (E->CountValid)
1081 continue;
1082 E->setEdgeCount(Value);
1083
1084 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1085 getBBInfo(E->DestBB).UnknownCountInEdge--;
1086 return;
1087 }
1088 llvm_unreachable("Cannot find the unknown count edge");
1089}
1090
1091// Read the profile from ProfileFileName and assign the value to the
1092// instrumented BB and the edges. This function also updates ProgramMaxCount.
1093// Return true if the profile are successfully read, and false on errors.
Rong Xufb4bcc42018-11-07 23:51:20 +00001094bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros) {
Rong Xuf430ae42015-12-09 18:08:16 +00001095 auto &Ctx = M->getContext();
Vedant Kumar9152fd12016-05-19 03:54:45 +00001096 Expected<InstrProfRecord> Result =
Rong Xuf430ae42015-12-09 18:08:16 +00001097 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001098 if (Error E = Result.takeError()) {
1099 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
1100 auto Err = IPE.get();
1101 bool SkipWarning = false;
Rong Xu6cdf3d82019-02-27 17:24:33 +00001102 LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
1103 << FuncInfo.FuncName << ": ");
Vedant Kumar9152fd12016-05-19 03:54:45 +00001104 if (Err == instrprof_error::unknown_function) {
Rong Xu6cdf3d82019-02-27 17:24:33 +00001105 IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++;
Xinliang David Li76a01082016-08-11 05:09:30 +00001106 SkipWarning = !PGOWarnMissing;
Rong Xu6cdf3d82019-02-27 17:24:33 +00001107 LLVM_DEBUG(dbgs() << "unknown function");
Vedant Kumar9152fd12016-05-19 03:54:45 +00001108 } else if (Err == instrprof_error::hash_mismatch ||
1109 Err == instrprof_error::malformed) {
Rong Xu6cdf3d82019-02-27 17:24:33 +00001110 IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++;
Rong Xu20f5df12017-01-11 20:19:41 +00001111 SkipWarning =
1112 NoPGOWarnMismatch ||
1113 (NoPGOWarnMismatchComdat &&
1114 (F.hasComdat() ||
1115 F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
Rong Xu6cdf3d82019-02-27 17:24:33 +00001116 LLVM_DEBUG(dbgs() << "hash mismatch (skip=" << SkipWarning << ")");
Vedant Kumar9152fd12016-05-19 03:54:45 +00001117 }
Rong Xuf430ae42015-12-09 18:08:16 +00001118
Rong Xu6cdf3d82019-02-27 17:24:33 +00001119 LLVM_DEBUG(dbgs() << " IsCS=" << IsCS << "\n");
Vedant Kumar9152fd12016-05-19 03:54:45 +00001120 if (SkipWarning)
1121 return;
1122
Rong Xu6cdf3d82019-02-27 17:24:33 +00001123 std::string Msg = IPE.message() + std::string(" ") + F.getName().str() +
1124 std::string(" Hash = ") +
1125 std::to_string(FuncInfo.FunctionHash);
1126
Vedant Kumar9152fd12016-05-19 03:54:45 +00001127 Ctx.diagnose(
1128 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1129 });
Rong Xuf430ae42015-12-09 18:08:16 +00001130 return false;
1131 }
Rong Xu13b01dc2016-02-10 18:24:45 +00001132 ProfileRecord = std::move(Result.get());
1133 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
Rong Xuf430ae42015-12-09 18:08:16 +00001134
Rong Xu6cdf3d82019-02-27 17:24:33 +00001135 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001136 LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001137 uint64_t ValueSum = 0;
1138 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001139 LLVM_DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001140 ValueSum += CountFromProfile[I];
1141 }
Rong Xufb4bcc42018-11-07 23:51:20 +00001142 AllZeros = (ValueSum == 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001143
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001144 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001145
1146 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1147 getBBInfo(nullptr).UnknownCountInEdge = 2;
1148
1149 setInstrumentedCounts(CountFromProfile);
Rong Xua6ff69f2019-02-28 19:55:07 +00001150 ProgramMaxCount = PGOReader->getMaximumFunctionCount(IsCS);
Rong Xuf430ae42015-12-09 18:08:16 +00001151 return true;
1152}
1153
1154// Populate the counters from instrumented BBs to all BBs.
1155// In the end of this operation, all BBs should have a valid count value.
1156void PGOUseFunc::populateCounters() {
1157 // First set up Count variable for all BBs.
1158 for (auto &E : FuncInfo.MST.AllEdges) {
1159 if (E->Removed)
1160 continue;
1161
1162 const BasicBlock *SrcBB = E->SrcBB;
1163 const BasicBlock *DestBB = E->DestBB;
1164 UseBBInfo &SrcInfo = getBBInfo(SrcBB);
1165 UseBBInfo &DestInfo = getBBInfo(DestBB);
1166 SrcInfo.OutEdges.push_back(E.get());
1167 DestInfo.InEdges.push_back(E.get());
1168 SrcInfo.UnknownCountOutEdge++;
1169 DestInfo.UnknownCountInEdge++;
1170
1171 if (!E->CountValid)
1172 continue;
1173 DestInfo.UnknownCountInEdge--;
1174 SrcInfo.UnknownCountOutEdge--;
1175 }
1176
1177 bool Changes = true;
1178 unsigned NumPasses = 0;
1179 while (Changes) {
1180 NumPasses++;
1181 Changes = false;
1182
1183 // For efficient traversal, it's better to start from the end as most
1184 // of the instrumented edges are at the end.
1185 for (auto &BB : reverse(F)) {
Rong Xua5b57452016-12-02 19:10:29 +00001186 UseBBInfo *Count = findBBInfo(&BB);
1187 if (Count == nullptr)
1188 continue;
1189 if (!Count->CountValid) {
1190 if (Count->UnknownCountOutEdge == 0) {
1191 Count->CountValue = sumEdgeCount(Count->OutEdges);
1192 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001193 Changes = true;
Rong Xua5b57452016-12-02 19:10:29 +00001194 } else if (Count->UnknownCountInEdge == 0) {
1195 Count->CountValue = sumEdgeCount(Count->InEdges);
1196 Count->CountValid = true;
Rong Xuf430ae42015-12-09 18:08:16 +00001197 Changes = true;
1198 }
1199 }
Rong Xua5b57452016-12-02 19:10:29 +00001200 if (Count->CountValid) {
1201 if (Count->UnknownCountOutEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001202 uint64_t Total = 0;
1203 uint64_t OutSum = sumEdgeCount(Count->OutEdges);
1204 // If the one of the successor block can early terminate (no-return),
1205 // we can end up with situation where out edge sum count is larger as
1206 // the source BB's count is collected by a post-dominated block.
1207 if (Count->CountValue > OutSum)
1208 Total = Count->CountValue - OutSum;
Rong Xua5b57452016-12-02 19:10:29 +00001209 setEdgeCount(Count->OutEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001210 Changes = true;
1211 }
Rong Xua5b57452016-12-02 19:10:29 +00001212 if (Count->UnknownCountInEdge == 1) {
Rong Xu51a1e3c2016-12-13 06:41:14 +00001213 uint64_t Total = 0;
1214 uint64_t InSum = sumEdgeCount(Count->InEdges);
1215 if (Count->CountValue > InSum)
1216 Total = Count->CountValue - InSum;
Rong Xua5b57452016-12-02 19:10:29 +00001217 setEdgeCount(Count->InEdges, Total);
Rong Xuf430ae42015-12-09 18:08:16 +00001218 Changes = true;
1219 }
1220 }
1221 }
1222 }
1223
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001224 LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
Sean Silva8c7e1212016-05-28 04:19:45 +00001225#ifndef NDEBUG
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001226 // Assert every BB has a valid counter.
Rong Xua5b57452016-12-02 19:10:29 +00001227 for (auto &BB : F) {
1228 auto BI = findBBInfo(&BB);
1229 if (BI == nullptr)
1230 continue;
1231 assert(BI->CountValid && "BB count is not valid");
1232 }
Sean Silva8c7e1212016-05-28 04:19:45 +00001233#endif
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001234 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001235 F.setEntryCount(ProfileCount(FuncEntryCount, Function::PCT_Real));
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001236 uint64_t FuncMaxCount = FuncEntryCount;
Rong Xua5b57452016-12-02 19:10:29 +00001237 for (auto &BB : F) {
1238 auto BI = findBBInfo(&BB);
1239 if (BI == nullptr)
1240 continue;
1241 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
1242 }
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001243 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001244
Rong Xu33308f92016-10-25 21:47:24 +00001245 // Now annotate select instructions
1246 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
1247 assert(CountPosition == ProfileCountSize);
1248
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001249 LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
Rong Xuf430ae42015-12-09 18:08:16 +00001250}
1251
1252// Assign the scaled count values to the BB with multiple out edges.
1253void PGOUseFunc::setBranchWeights() {
1254 // Generate MD_prof metadata for every branch instruction.
Rong Xu6cdf3d82019-02-27 17:24:33 +00001255 LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F.getName()
1256 << " IsCS=" << IsCS << "\n");
Rong Xuf430ae42015-12-09 18:08:16 +00001257 for (auto &BB : F) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001258 Instruction *TI = BB.getTerminator();
Rong Xuf430ae42015-12-09 18:08:16 +00001259 if (TI->getNumSuccessors() < 2)
1260 continue;
Rong Xu15848e52017-08-23 21:36:02 +00001261 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1262 isa<IndirectBrInst>(TI)))
Rong Xuf430ae42015-12-09 18:08:16 +00001263 continue;
Rong Xu6cdf3d82019-02-27 17:24:33 +00001264
Rong Xuf430ae42015-12-09 18:08:16 +00001265 if (getBBInfo(&BB).CountValue == 0)
1266 continue;
1267
1268 // We have a non-zero Branch BB.
1269 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1270 unsigned Size = BBCountInfo.OutEdges.size();
Xinliang David Li63248ab2016-08-19 06:31:45 +00001271 SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
Rong Xuf430ae42015-12-09 18:08:16 +00001272 uint64_t MaxCount = 0;
1273 for (unsigned s = 0; s < Size; s++) {
1274 const PGOUseEdge *E = BBCountInfo.OutEdges[s];
1275 const BasicBlock *SrcBB = E->SrcBB;
1276 const BasicBlock *DestBB = E->DestBB;
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001277 if (DestBB == nullptr)
Rong Xuf430ae42015-12-09 18:08:16 +00001278 continue;
1279 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1280 uint64_t EdgeCount = E->CountValue;
1281 if (EdgeCount > MaxCount)
1282 MaxCount = EdgeCount;
1283 EdgeCounts[SuccNum] = EdgeCount;
1284 }
Xinliang David Li2c933682016-08-19 05:31:33 +00001285 setProfMetadata(M, TI, EdgeCounts, MaxCount);
Rong Xuf430ae42015-12-09 18:08:16 +00001286 }
1287}
Rong Xu13b01dc2016-02-10 18:24:45 +00001288
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001289static bool isIndirectBrTarget(BasicBlock *BB) {
1290 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1291 if (isa<IndirectBrInst>((*PI)->getTerminator()))
1292 return true;
1293 }
1294 return false;
1295}
1296
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001297void PGOUseFunc::annotateIrrLoopHeaderWeights() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001298 LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001299 // Find irr loop headers
1300 for (auto &BB : F) {
Hiroshi Yamauchic94d4d72017-11-20 21:03:38 +00001301 // As a heuristic also annotate indrectbr targets as they have a high chance
1302 // to become an irreducible loop header after the indirectbr tail
1303 // duplication.
1304 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001305 Instruction *TI = BB.getTerminator();
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001306 const UseBBInfo &BBCountInfo = getBBInfo(&BB);
1307 setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
1308 }
1309 }
1310}
1311
Xinliang David Li4ca17332016-09-18 18:34:07 +00001312void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1313 Module *M = F.getParent();
1314 IRBuilder<> Builder(&SI);
1315 Type *Int64Ty = Builder.getInt64Ty();
1316 Type *I8PtrTy = Builder.getInt8PtrTy();
1317 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
1318 Builder.CreateCall(
1319 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001320 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Rong Xu0a2a1312017-03-09 19:08:55 +00001321 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
1322 Builder.getInt32(*CurCtrIdx), Step});
Xinliang David Li4ca17332016-09-18 18:34:07 +00001323 ++(*CurCtrIdx);
1324}
1325
1326void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1327 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1328 assert(*CurCtrIdx < CountFromProfile.size() &&
1329 "Out of bound access of counters");
1330 uint64_t SCounts[2];
1331 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1332 ++(*CurCtrIdx);
Rong Xua5b57452016-12-02 19:10:29 +00001333 uint64_t TotalCount = 0;
1334 auto BI = UseFunc->findBBInfo(SI.getParent());
1335 if (BI != nullptr)
1336 TotalCount = BI->CountValue;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001337 // False Count
1338 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1339 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
Xinliang David Lic7368282016-09-20 20:20:01 +00001340 if (MaxCount)
1341 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
Xinliang David Li4ca17332016-09-18 18:34:07 +00001342}
1343
1344void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1345 if (!PGOInstrSelect)
1346 return;
1347 // FIXME: do not handle this yet.
1348 if (SI.getCondition()->getType()->isVectorTy())
1349 return;
1350
Xinliang David Li4ca17332016-09-18 18:34:07 +00001351 switch (Mode) {
1352 case VM_counting:
Vitaly Bukaca6ecd22017-03-15 23:07:41 +00001353 NSIs++;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001354 return;
1355 case VM_instrument:
1356 instrumentOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001357 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001358 case VM_annotate:
1359 annotateOneSelectInst(SI);
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001360 return;
Xinliang David Li4ca17332016-09-18 18:34:07 +00001361 }
Simon Pilgrimf33a6b72016-09-18 21:08:35 +00001362
1363 llvm_unreachable("Unknown visiting mode");
Xinliang David Li4ca17332016-09-18 18:34:07 +00001364}
1365
Rong Xu60faea12017-03-16 21:15:48 +00001366void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) {
1367 Module *M = F.getParent();
1368 IRBuilder<> Builder(&MI);
1369 Type *Int64Ty = Builder.getInt64Ty();
1370 Type *I8PtrTy = Builder.getInt8PtrTy();
1371 Value *Length = MI.getLength();
1372 assert(!dyn_cast<ConstantInt>(Length));
1373 Builder.CreateCall(
1374 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
Eugene Zelenkofce43572017-10-21 00:57:46 +00001375 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Ana Pazosf731bde2017-06-19 20:04:33 +00001376 Builder.getInt64(FuncHash), Builder.CreateZExtOrTrunc(Length, Int64Ty),
Rong Xu60faea12017-03-16 21:15:48 +00001377 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)});
1378 ++CurCtrId;
1379}
1380
1381void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) {
1382 if (!PGOInstrMemOP)
1383 return;
1384 Value *Length = MI.getLength();
1385 // Not instrument constant length calls.
1386 if (dyn_cast<ConstantInt>(Length))
1387 return;
1388
1389 switch (Mode) {
1390 case VM_counting:
1391 NMemIs++;
1392 return;
1393 case VM_instrument:
1394 instrumentOneMemIntrinsic(MI);
1395 return;
1396 case VM_annotate:
Rong Xue60343d2017-03-17 18:07:26 +00001397 Candidates.push_back(&MI);
1398 return;
Rong Xu60faea12017-03-16 21:15:48 +00001399 }
1400 llvm_unreachable("Unknown visiting mode");
1401}
1402
Rong Xua3bbf962017-03-15 18:23:39 +00001403// Traverse all valuesites and annotate the instructions for all value kind.
1404void PGOUseFunc::annotateValueSites() {
Rong Xu13b01dc2016-02-10 18:24:45 +00001405 if (DisableValueProfiling)
1406 return;
1407
Rong Xu8e8fe852016-04-01 16:43:30 +00001408 // Create the PGOFuncName meta data.
Rong Xuf8f051c2016-04-22 21:00:17 +00001409 createPGOFuncNameMetadata(F, FuncInfo.FuncName);
Rong Xub5341662016-03-30 18:37:52 +00001410
Rong Xua3bbf962017-03-15 18:23:39 +00001411 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Rong Xue60343d2017-03-17 18:07:26 +00001412 annotateValueSites(Kind);
Rong Xua3bbf962017-03-15 18:23:39 +00001413}
1414
1415// Annotate the instructions for a specific value kind.
1416void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1417 unsigned ValueSiteIndex = 0;
1418 auto &ValueSites = FuncInfo.ValueSites[Kind];
1419 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1420 if (NumValueSites != ValueSites.size()) {
Rong Xu13b01dc2016-02-10 18:24:45 +00001421 auto &Ctx = M->getContext();
Rong Xua3bbf962017-03-15 18:23:39 +00001422 Ctx.diagnose(DiagnosticInfoPGOProfile(
1423 M->getName().data(),
1424 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) +
1425 " in " + F.getName().str(),
1426 DS_Warning));
Rong Xu13b01dc2016-02-10 18:24:45 +00001427 return;
1428 }
1429
Rong Xua3bbf962017-03-15 18:23:39 +00001430 for (auto &I : ValueSites) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001431 LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1432 << "): Index = " << ValueSiteIndex << " out of "
1433 << NumValueSites << "\n");
Rong Xua3bbf962017-03-15 18:23:39 +00001434 annotateValueSite(*M, *I, ProfileRecord,
1435 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
Rong Xue60343d2017-03-17 18:07:26 +00001436 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
1437 : MaxNumAnnotations);
Rong Xua3bbf962017-03-15 18:23:39 +00001438 ValueSiteIndex++;
Rong Xu13b01dc2016-02-10 18:24:45 +00001439 }
1440}
Rong Xuf430ae42015-12-09 18:08:16 +00001441
Rong Xu705f7772016-07-25 18:45:37 +00001442// Collect the set of members for each Comdat in module M and store
1443// in ComdatMembers.
1444static void collectComdatMembers(
1445 Module &M,
1446 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1447 if (!DoComdatRenaming)
1448 return;
1449 for (Function &F : M)
1450 if (Comdat *C = F.getComdat())
1451 ComdatMembers.insert(std::make_pair(C, &F));
1452 for (GlobalVariable &GV : M.globals())
1453 if (Comdat *C = GV.getComdat())
1454 ComdatMembers.insert(std::make_pair(C, &GV));
1455 for (GlobalAlias &GA : M.aliases())
1456 if (Comdat *C = GA.getComdat())
1457 ComdatMembers.insert(std::make_pair(C, &GA));
1458}
1459
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001460static bool InstrumentAllFunctions(
Xinliang David Lid91057b2017-12-08 19:38:07 +00001461 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Rong Xu6cdf3d82019-02-27 17:24:33 +00001462 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS) {
1463 // For the context-sensitve instrumentation, we should have a separated pass
1464 // (before LTO/ThinLTO linking) to create these variables.
1465 if (!IsCS)
1466 createIRLevelProfileFlagVar(M, /* IsCS */ false);
Rong Xu705f7772016-07-25 18:45:37 +00001467 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1468 collectComdatMembers(M, ComdatMembers);
1469
Rong Xuf430ae42015-12-09 18:08:16 +00001470 for (auto &F : M) {
1471 if (F.isDeclaration())
1472 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001473 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001474 auto *BFI = LookupBFI(F);
Rong Xu6cdf3d82019-02-27 17:24:33 +00001475 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers, IsCS);
Rong Xuf430ae42015-12-09 18:08:16 +00001476 }
1477 return true;
1478}
1479
Jordan Rupprecht090683b2019-03-04 22:54:44 +00001480PreservedAnalyses
1481PGOInstrumentationGenCreateVar::run(Module &M, ModuleAnalysisManager &AM) {
1482 createProfileFileNameVar(M, CSInstrName);
1483 createIRLevelProfileFlagVar(M, /* IsCS */ true);
1484 return PreservedAnalyses::all();
1485}
1486
Xinliang David Li8aebf442016-05-06 05:49:19 +00001487bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) {
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001488 if (skipModule(M))
1489 return false;
1490
Xinliang David Lid91057b2017-12-08 19:38:07 +00001491 auto LookupBPI = [this](Function &F) {
1492 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1493 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001494 auto LookupBFI = [this](Function &F) {
1495 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001496 };
Rong Xu6cdf3d82019-02-27 17:24:33 +00001497 return InstrumentAllFunctions(M, LookupBPI, LookupBFI, IsCS);
Xinliang David Li5ad7c822016-05-02 20:33:59 +00001498}
1499
Xinliang David Li8aebf442016-05-06 05:49:19 +00001500PreservedAnalyses PGOInstrumentationGen::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001501 ModuleAnalysisManager &AM) {
Xinliang David Li8aebf442016-05-06 05:49:19 +00001502 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001503 auto LookupBPI = [&FAM](Function &F) {
1504 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1505 };
Xinliang David Li8aebf442016-05-06 05:49:19 +00001506
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001507 auto LookupBFI = [&FAM](Function &F) {
1508 return &FAM.getResult<BlockFrequencyAnalysis>(F);
Xinliang David Li8aebf442016-05-06 05:49:19 +00001509 };
1510
Rong Xu6cdf3d82019-02-27 17:24:33 +00001511 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI, IsCS))
Xinliang David Li8aebf442016-05-06 05:49:19 +00001512 return PreservedAnalyses::all();
1513
1514 return PreservedAnalyses::none();
1515}
1516
Xinliang David Lida195582016-05-10 21:59:52 +00001517static bool annotateAllFunctions(
Richard Smith6c676622018-10-10 23:13:47 +00001518 Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName,
Xinliang David Lid91057b2017-12-08 19:38:07 +00001519 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
Rong Xu6cdf3d82019-02-27 17:24:33 +00001520 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001521 LLVM_DEBUG(dbgs() << "Read in profile counters: ");
Rong Xuf430ae42015-12-09 18:08:16 +00001522 auto &Ctx = M.getContext();
1523 // Read the counter array from file.
Richard Smith6c676622018-10-10 23:13:47 +00001524 auto ReaderOrErr =
1525 IndexedInstrProfReader::create(ProfileFileName, ProfileRemappingFileName);
Vedant Kumar9152fd12016-05-19 03:54:45 +00001526 if (Error E = ReaderOrErr.takeError()) {
1527 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
1528 Ctx.diagnose(
1529 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
1530 });
Rong Xuf430ae42015-12-09 18:08:16 +00001531 return false;
1532 }
1533
Xinliang David Lida195582016-05-10 21:59:52 +00001534 std::unique_ptr<IndexedInstrProfReader> PGOReader =
1535 std::move(ReaderOrErr.get());
Rong Xuf430ae42015-12-09 18:08:16 +00001536 if (!PGOReader) {
1537 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
Xinliang David Lida195582016-05-10 21:59:52 +00001538 StringRef("Cannot get PGOReader")));
Rong Xuf430ae42015-12-09 18:08:16 +00001539 return false;
1540 }
Rong Xua6ff69f2019-02-28 19:55:07 +00001541 if (!PGOReader->hasCSIRLevelProfile() && IsCS)
1542 return false;
Rong Xu6cdf3d82019-02-27 17:24:33 +00001543
Rong Xu33c76c02016-02-10 17:18:30 +00001544 // TODO: might need to change the warning once the clang option is finalized.
1545 if (!PGOReader->isIRLevelProfile()) {
1546 Ctx.diagnose(DiagnosticInfoPGOProfile(
1547 ProfileFileName.data(), "Not an IR level instrumentation profile"));
1548 return false;
1549 }
1550
Rong Xu705f7772016-07-25 18:45:37 +00001551 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1552 collectComdatMembers(M, ComdatMembers);
Rong Xu6090afd2016-03-28 17:08:56 +00001553 std::vector<Function *> HotFunctions;
1554 std::vector<Function *> ColdFunctions;
Rong Xuf430ae42015-12-09 18:08:16 +00001555 for (auto &F : M) {
1556 if (F.isDeclaration())
1557 continue;
Xinliang David Lid91057b2017-12-08 19:38:07 +00001558 auto *BPI = LookupBPI(F);
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001559 auto *BFI = LookupBFI(F);
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +00001560 // Split indirectbr critical edges here before computing the MST rather than
1561 // later in getInstrBB() to avoid invalidating it.
1562 SplitIndirectBrCriticalEdges(F, BPI, BFI);
Rong Xu6cdf3d82019-02-27 17:24:33 +00001563 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI, IsCS);
Rong Xufb4bcc42018-11-07 23:51:20 +00001564 bool AllZeros = false;
1565 if (!Func.readCounters(PGOReader.get(), AllZeros))
Sean Silva2e8f0952016-05-28 04:19:40 +00001566 continue;
Rong Xufb4bcc42018-11-07 23:51:20 +00001567 if (AllZeros) {
1568 F.setEntryCount(ProfileCount(0, Function::PCT_Real));
1569 if (Func.getProgramMaxCount() != 0)
1570 ColdFunctions.push_back(&F);
1571 continue;
1572 }
Sean Silva2e8f0952016-05-28 04:19:40 +00001573 Func.populateCounters();
1574 Func.setBranchWeights();
Rong Xua3bbf962017-03-15 18:23:39 +00001575 Func.annotateValueSites();
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001576 Func.annotateIrrLoopHeaderWeights();
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001577 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
1578 if (FreqAttr == PGOUseFunc::FFA_Cold)
Sean Silva2a730192016-05-28 03:02:50 +00001579 ColdFunctions.push_back(&F);
Sean Silva9dd4b5c2016-05-28 03:56:25 +00001580 else if (FreqAttr == PGOUseFunc::FFA_Hot)
1581 HotFunctions.push_back(&F);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001582 if (PGOViewCounts != PGOVCT_None &&
1583 (ViewBlockFreqFuncName.empty() ||
1584 F.getName().equals(ViewBlockFreqFuncName))) {
Xinliang David Licb253ce2017-01-23 18:58:24 +00001585 LoopInfo LI{DominatorTree(F)};
1586 std::unique_ptr<BranchProbabilityInfo> NewBPI =
1587 llvm::make_unique<BranchProbabilityInfo>(F, LI);
1588 std::unique_ptr<BlockFrequencyInfo> NewBFI =
1589 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001590 if (PGOViewCounts == PGOVCT_Graph)
1591 NewBFI->view();
1592 else if (PGOViewCounts == PGOVCT_Text) {
1593 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
1594 NewBFI->print(dbgs());
1595 }
Xinliang David Licb253ce2017-01-23 18:58:24 +00001596 }
Hiroshi Yamauchia43913c2017-09-13 17:20:38 +00001597 if (PGOViewRawCounts != PGOVCT_None &&
1598 (ViewBlockFreqFuncName.empty() ||
1599 F.getName().equals(ViewBlockFreqFuncName))) {
1600 if (PGOViewRawCounts == PGOVCT_Graph)
1601 if (ViewBlockFreqFuncName.empty())
1602 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1603 else
1604 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
1605 else if (PGOViewRawCounts == PGOVCT_Text) {
1606 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
1607 Func.dumpInfo();
1608 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001609 }
Rong Xuf430ae42015-12-09 18:08:16 +00001610 }
Rong Xua6ff69f2019-02-28 19:55:07 +00001611 M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()),
1612 IsCS ? ProfileSummary::PSK_CSInstr
1613 : ProfileSummary::PSK_Instr);
Rong Xu6cdf3d82019-02-27 17:24:33 +00001614
Rong Xu6090afd2016-03-28 17:08:56 +00001615 // Set function hotness attribute from the profile.
Sean Silva42cc3422016-05-28 04:24:39 +00001616 // We have to apply these attributes at the end because their presence
1617 // can affect the BranchProbabilityInfo of any callers, resulting in an
1618 // inconsistent MST between prof-gen and prof-use.
Rong Xu6090afd2016-03-28 17:08:56 +00001619 for (auto &F : HotFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001620 F->addFnAttr(Attribute::InlineHint);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001621 LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
1622 << "\n");
Rong Xu6090afd2016-03-28 17:08:56 +00001623 }
1624 for (auto &F : ColdFunctions) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001625 F->addFnAttr(Attribute::Cold);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001626 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
1627 << "\n");
Rong Xu6090afd2016-03-28 17:08:56 +00001628 }
Rong Xuf430ae42015-12-09 18:08:16 +00001629 return true;
1630}
Xinliang David Lid55827f2016-05-07 05:39:12 +00001631
Richard Smith6c676622018-10-10 23:13:47 +00001632PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename,
Rong Xu6cdf3d82019-02-27 17:24:33 +00001633 std::string RemappingFilename,
1634 bool IsCS)
Richard Smith6c676622018-10-10 23:13:47 +00001635 : ProfileFileName(std::move(Filename)),
Rong Xu6cdf3d82019-02-27 17:24:33 +00001636 ProfileRemappingFileName(std::move(RemappingFilename)), IsCS(IsCS) {
Xinliang David Lida195582016-05-10 21:59:52 +00001637 if (!PGOTestProfileFile.empty())
1638 ProfileFileName = PGOTestProfileFile;
Richard Smith6c676622018-10-10 23:13:47 +00001639 if (!PGOTestProfileRemappingFile.empty())
1640 ProfileRemappingFileName = PGOTestProfileRemappingFile;
Xinliang David Lida195582016-05-10 21:59:52 +00001641}
1642
1643PreservedAnalyses PGOInstrumentationUse::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001644 ModuleAnalysisManager &AM) {
Xinliang David Lida195582016-05-10 21:59:52 +00001645
1646 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid91057b2017-12-08 19:38:07 +00001647 auto LookupBPI = [&FAM](Function &F) {
1648 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1649 };
Xinliang David Lida195582016-05-10 21:59:52 +00001650
1651 auto LookupBFI = [&FAM](Function &F) {
1652 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1653 };
1654
Richard Smith6c676622018-10-10 23:13:47 +00001655 if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName,
Rong Xu6cdf3d82019-02-27 17:24:33 +00001656 LookupBPI, LookupBFI, IsCS))
Xinliang David Lida195582016-05-10 21:59:52 +00001657 return PreservedAnalyses::all();
1658
1659 return PreservedAnalyses::none();
1660}
1661
Xinliang David Lid55827f2016-05-07 05:39:12 +00001662bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) {
1663 if (skipModule(M))
1664 return false;
1665
Xinliang David Lid91057b2017-12-08 19:38:07 +00001666 auto LookupBPI = [this](Function &F) {
1667 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI();
1668 };
Xinliang David Lidfa21c32016-05-09 21:37:12 +00001669 auto LookupBFI = [this](Function &F) {
1670 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
Xinliang David Lid55827f2016-05-07 05:39:12 +00001671 };
1672
Rong Xu6cdf3d82019-02-27 17:24:33 +00001673 return annotateAllFunctions(M, ProfileFileName, "", LookupBPI, LookupBFI,
1674 IsCS);
Xinliang David Lid55827f2016-05-07 05:39:12 +00001675}
Xinliang David Lid289e452017-01-27 19:06:25 +00001676
Eugene Zelenkofce43572017-10-21 00:57:46 +00001677static std::string getSimpleNodeName(const BasicBlock *Node) {
1678 if (!Node->getName().empty())
1679 return Node->getName();
1680
1681 std::string SimpleNodeName;
1682 raw_string_ostream OS(SimpleNodeName);
1683 Node->printAsOperand(OS, false);
1684 return OS.str();
1685}
1686
1687void llvm::setProfMetadata(Module *M, Instruction *TI,
1688 ArrayRef<uint64_t> EdgeCounts,
1689 uint64_t MaxCount) {
Rong Xu48596b62017-04-04 16:42:20 +00001690 MDBuilder MDB(M->getContext());
1691 assert(MaxCount > 0 && "Bad max count");
1692 uint64_t Scale = calculateCountScale(MaxCount);
1693 SmallVector<unsigned, 4> Weights;
1694 for (const auto &ECI : EdgeCounts)
1695 Weights.push_back(scaleBranchCount(ECI, Scale));
1696
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001697 LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W
1698 : Weights) {
1699 dbgs() << W << " ";
1700 } dbgs() << "\n";);
Eugene Zelenkofce43572017-10-21 00:57:46 +00001701 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001702 if (EmitBranchProbability) {
1703 std::string BrCondStr = getBranchCondString(TI);
1704 if (BrCondStr.empty())
1705 return;
1706
Rong Xu662f38b2018-03-27 18:55:56 +00001707 uint64_t WSum =
1708 std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
1709 [](uint64_t w1, uint64_t w2) { return w1 + w2; });
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001710 uint64_t TotalCount =
Rong Xu662f38b2018-03-27 18:55:56 +00001711 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001712 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
Rong Xu662f38b2018-03-27 18:55:56 +00001713 Scale = calculateCountScale(WSum);
1714 BranchProbability BP(scaleBranchCount(Weights[0], Scale),
1715 scaleBranchCount(WSum, Scale));
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001716 std::string BranchProbStr;
1717 raw_string_ostream OS(BranchProbStr);
1718 OS << BP;
1719 OS << " (total count : " << TotalCount << ")";
1720 OS.flush();
1721 Function *F = TI->getParent()->getParent();
Davide Italiano0c8d26c2017-07-20 20:43:05 +00001722 OptimizationRemarkEmitter ORE(F);
Vivek Pandya95906582017-10-11 17:12:59 +00001723 ORE.emit([&]() {
1724 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
1725 << BrCondStr << " is true with probability : " << BranchProbStr;
1726 });
Xinliang David Li0a0acbc2017-06-01 18:58:50 +00001727 }
Rong Xu48596b62017-04-04 16:42:20 +00001728}
1729
Eugene Zelenkofce43572017-10-21 00:57:46 +00001730namespace llvm {
1731
Hiroshi Yamauchidce9def2017-11-02 22:26:51 +00001732void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
1733 MDBuilder MDB(M->getContext());
1734 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
1735 MDB.createIrrLoopHeaderWeight(Count));
1736}
1737
Xinliang David Lid289e452017-01-27 19:06:25 +00001738template <> struct GraphTraits<PGOUseFunc *> {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001739 using NodeRef = const BasicBlock *;
1740 using ChildIteratorType = succ_const_iterator;
1741 using nodes_iterator = pointer_iterator<Function::const_iterator>;
Xinliang David Lid289e452017-01-27 19:06:25 +00001742
1743 static NodeRef getEntryNode(const PGOUseFunc *G) {
1744 return &G->getFunc().front();
1745 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001746
Xinliang David Lid289e452017-01-27 19:06:25 +00001747 static ChildIteratorType child_begin(const NodeRef N) {
1748 return succ_begin(N);
1749 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001750
Xinliang David Lid289e452017-01-27 19:06:25 +00001751 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001752
Xinliang David Lid289e452017-01-27 19:06:25 +00001753 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
1754 return nodes_iterator(G->getFunc().begin());
1755 }
Eugene Zelenkofce43572017-10-21 00:57:46 +00001756
Xinliang David Lid289e452017-01-27 19:06:25 +00001757 static nodes_iterator nodes_end(const PGOUseFunc *G) {
1758 return nodes_iterator(G->getFunc().end());
1759 }
1760};
1761
1762template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
1763 explicit DOTGraphTraits(bool isSimple = false)
1764 : DefaultDOTGraphTraits(isSimple) {}
1765
1766 static std::string getGraphName(const PGOUseFunc *G) {
1767 return G->getFunc().getName();
1768 }
1769
1770 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
1771 std::string Result;
1772 raw_string_ostream OS(Result);
Xinliang David Li6144a592017-02-03 21:57:51 +00001773
1774 OS << getSimpleNodeName(Node) << ":\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001775 UseBBInfo *BI = Graph->findBBInfo(Node);
Xinliang David Li6144a592017-02-03 21:57:51 +00001776 OS << "Count : ";
Xinliang David Lid289e452017-01-27 19:06:25 +00001777 if (BI && BI->CountValid)
Xinliang David Li6144a592017-02-03 21:57:51 +00001778 OS << BI->CountValue << "\\l";
Xinliang David Lid289e452017-01-27 19:06:25 +00001779 else
Xinliang David Li6144a592017-02-03 21:57:51 +00001780 OS << "Unknown\\l";
1781
1782 if (!PGOInstrSelect)
1783 return Result;
1784
1785 for (auto BI = Node->begin(); BI != Node->end(); ++BI) {
1786 auto *I = &*BI;
1787 if (!isa<SelectInst>(I))
1788 continue;
1789 // Display scaled counts for SELECT instruction:
1790 OS << "SELECT : { T = ";
1791 uint64_t TC, FC;
Xinliang David Lic7db0d02017-02-04 07:40:43 +00001792 bool HasProf = I->extractProfMetadata(TC, FC);
1793 if (!HasProf)
Xinliang David Li6144a592017-02-03 21:57:51 +00001794 OS << "Unknown, F = Unknown }\\l";
1795 else
1796 OS << TC << ", F = " << FC << " }\\l";
1797 }
Xinliang David Lid289e452017-01-27 19:06:25 +00001798 return Result;
1799 }
1800};
Eugene Zelenkofce43572017-10-21 00:57:46 +00001801
1802} // end namespace llvm