blob: e525abe979e356dcb63f27e5832c5535d8eef7ea [file] [log] [blame]
Justin Bogneref512b92014-01-06 22:27:43 +00001//===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
2//
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
Justin Bogneref512b92014-01-06 22:27:43 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Instrumentation-based profile-guided optimization
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenPGO.h"
14#include "CodeGenFunction.h"
Alex Lorenzee024992014-08-04 18:41:51 +000015#include "CoverageMappingGen.h"
Justin Bogneref512b92014-01-06 22:27:43 +000016#include "clang/AST/RecursiveASTVisitor.h"
17#include "clang/AST/StmtVisitor.h"
Justin Bogner970ac602014-12-08 19:04:51 +000018#include "llvm/IR/Intrinsics.h"
Justin Bogneref512b92014-01-06 22:27:43 +000019#include "llvm/IR/MDBuilder.h"
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000020#include "llvm/Support/Endian.h"
Justin Bogneref512b92014-01-06 22:27:43 +000021#include "llvm/Support/FileSystem.h"
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000022#include "llvm/Support/MD5.h"
Justin Bogneref512b92014-01-06 22:27:43 +000023
Zachary Turner8065f0b2017-12-01 00:53:10 +000024static llvm::cl::opt<bool>
25 EnableValueProfiling("enable-value-profiling", llvm::cl::ZeroOrMore,
26 llvm::cl::desc("Enable value profiling"),
27 llvm::cl::Hidden, llvm::cl::init(false));
Betul Buyukkurt518276a2016-01-23 22:50:44 +000028
Justin Bogneref512b92014-01-06 22:27:43 +000029using namespace clang;
30using namespace CodeGen;
31
Alex Lorenzee024992014-08-04 18:41:51 +000032void CodeGenPGO::setFuncName(StringRef Name,
33 llvm::GlobalValue::LinkageTypes Linkage) {
Xinliang David Lia569e242015-12-05 05:37:15 +000034 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
35 FuncName = llvm::getPGOFuncName(
36 Name, Linkage, CGM.getCodeGenOpts().MainFileName,
37 PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
Justin Bogner970ac602014-12-08 19:04:51 +000038
39 // If we're generating a profile, create a variable for the name.
Rong Xu9837ef52016-02-04 18:39:09 +000040 if (CGM.getCodeGenOpts().hasProfileClangInstr())
Xinliang David Li2d7ec5a2015-11-09 00:04:16 +000041 FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
Bob Wilsonda1ebed2014-03-06 04:55:41 +000042}
43
Alex Lorenzee024992014-08-04 18:41:51 +000044void CodeGenPGO::setFuncName(llvm::Function *Fn) {
45 setFuncName(Fn->getName(), Fn->getLinkage());
Rong Xuf932f542016-04-22 21:19:05 +000046 // Create PGOFuncName meta data.
47 llvm::createPGOFuncNameMetadata(*Fn, FuncName);
Alex Lorenzee024992014-08-04 18:41:51 +000048}
49
Vedant Kumar61869712017-11-14 23:56:53 +000050/// The version of the PGO hash algorithm.
51enum PGOHashVersion : unsigned {
52 PGO_HASH_V1,
53 PGO_HASH_V2,
54
55 // Keep this set to the latest hash version.
56 PGO_HASH_LATEST = PGO_HASH_V2
57};
58
Justin Bogneref512b92014-01-06 22:27:43 +000059namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000060/// Stable hasher for PGO region counters.
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000061///
62/// PGOHash produces a stable hash of a given function's control flow.
63///
64/// Changing the output of this hash will invalidate all previously generated
65/// profiles -- i.e., don't do it.
66///
67/// \note When this hash does eventually change (years?), we still need to
68/// support old hashes. We'll need to pull in the version number from the
69/// profile data format and use the matching hash function.
70class PGOHash {
71 uint64_t Working;
72 unsigned Count;
Vedant Kumar61869712017-11-14 23:56:53 +000073 PGOHashVersion HashVersion;
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000074 llvm::MD5 MD5;
75
76 static const int NumBitsPerType = 6;
77 static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
78 static const unsigned TooBig = 1u << NumBitsPerType;
79
80public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000081 /// Hash values for AST nodes.
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000082 ///
83 /// Distinct values for AST nodes that have region counters attached.
84 ///
85 /// These values must be stable. All new members must be added at the end,
86 /// and no members should be removed. Changing the enumeration value for an
87 /// AST node will affect the hash of every function that contains that node.
88 enum HashType : unsigned char {
89 None = 0,
90 LabelStmt = 1,
91 WhileStmt,
92 DoStmt,
93 ForStmt,
94 CXXForRangeStmt,
95 ObjCForCollectionStmt,
96 SwitchStmt,
97 CaseStmt,
98 DefaultStmt,
99 IfStmt,
100 CXXTryStmt,
101 CXXCatchStmt,
102 ConditionalOperator,
103 BinaryOperatorLAnd,
104 BinaryOperatorLOr,
105 BinaryConditionalOperator,
Vedant Kumar61869712017-11-14 23:56:53 +0000106 // The preceding values are available with PGO_HASH_V1.
107
108 EndOfScope,
109 IfThenBranch,
110 IfElseBranch,
111 GotoStmt,
112 IndirectGotoStmt,
113 BreakStmt,
114 ContinueStmt,
115 ReturnStmt,
116 ThrowExpr,
117 UnaryOperatorLNot,
118 BinaryOperatorLT,
119 BinaryOperatorGT,
120 BinaryOperatorLE,
121 BinaryOperatorGE,
122 BinaryOperatorEQ,
123 BinaryOperatorNE,
124 // The preceding values are available with PGO_HASH_V2.
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000125
126 // Keep this last. It's for the static assert that follows.
127 LastHashType
128 };
129 static_assert(LastHashType <= TooBig, "Too many types in HashType");
130
Vedant Kumar61869712017-11-14 23:56:53 +0000131 PGOHash(PGOHashVersion HashVersion)
132 : Working(0), Count(0), HashVersion(HashVersion), MD5() {}
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000133 void combine(HashType Type);
134 uint64_t finalize();
Vedant Kumar61869712017-11-14 23:56:53 +0000135 PGOHashVersion getHashVersion() const { return HashVersion; }
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000136};
137const int PGOHash::NumBitsPerType;
138const unsigned PGOHash::NumTypesPerWord;
139const unsigned PGOHash::TooBig;
140
Vedant Kumar61869712017-11-14 23:56:53 +0000141/// Get the PGO hash version used in the given indexed profile.
142static PGOHashVersion getPGOHashVersion(llvm::IndexedInstrProfReader *PGOReader,
143 CodeGenModule &CGM) {
144 if (PGOReader->getVersion() <= 4)
145 return PGO_HASH_V1;
146 return PGO_HASH_V2;
147}
148
Justin Bognere4ca4412015-02-23 19:27:00 +0000149/// A RecursiveASTVisitor that fills a map of statements to PGO counters.
150struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
Vedant Kumar61869712017-11-14 23:56:53 +0000151 using Base = RecursiveASTVisitor<MapRegionCounters>;
152
Justin Bognere4ca4412015-02-23 19:27:00 +0000153 /// The next counter value to assign.
154 unsigned NextCounter;
155 /// The function hash.
156 PGOHash Hash;
157 /// The map of statements to counters.
158 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
Justin Bogneref512b92014-01-06 22:27:43 +0000159
Vedant Kumar61869712017-11-14 23:56:53 +0000160 MapRegionCounters(PGOHashVersion HashVersion,
161 llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
162 : NextCounter(0), Hash(HashVersion), CounterMap(CounterMap) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000163
Justin Bognere4ca4412015-02-23 19:27:00 +0000164 // Blocks and lambdas are handled as separate functions, so we need not
165 // traverse them in the parent context.
166 bool TraverseBlockExpr(BlockExpr *BE) { return true; }
Sam McCalle60151c2019-01-14 10:31:42 +0000167 bool TraverseLambdaExpr(LambdaExpr *LE) {
168 // Traverse the captures, but not the body.
169 for (const auto &C : zip(LE->captures(), LE->capture_inits()))
170 TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
171 return true;
172 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000173 bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
Justin Bogneref512b92014-01-06 22:27:43 +0000174
Justin Bognere4ca4412015-02-23 19:27:00 +0000175 bool VisitDecl(const Decl *D) {
176 switch (D->getKind()) {
177 default:
178 break;
179 case Decl::Function:
180 case Decl::CXXMethod:
181 case Decl::CXXConstructor:
182 case Decl::CXXDestructor:
183 case Decl::CXXConversion:
184 case Decl::ObjCMethod:
185 case Decl::Block:
186 case Decl::Captured:
187 CounterMap[D->getBody()] = NextCounter++;
188 break;
189 }
190 return true;
191 }
192
Vedant Kumar61869712017-11-14 23:56:53 +0000193 /// If \p S gets a fresh counter, update the counter mappings. Return the
194 /// V1 hash of \p S.
195 PGOHash::HashType updateCounterMappings(Stmt *S) {
196 auto Type = getHashType(PGO_HASH_V1, S);
197 if (Type != PGOHash::None)
198 CounterMap[S] = NextCounter++;
199 return Type;
200 }
Bob Wilsond8931422014-04-11 17:16:13 +0000201
Vedant Kumar61869712017-11-14 23:56:53 +0000202 /// Include \p S in the function hash.
203 bool VisitStmt(Stmt *S) {
204 auto Type = updateCounterMappings(S);
205 if (Hash.getHashVersion() != PGO_HASH_V1)
206 Type = getHashType(Hash.getHashVersion(), S);
207 if (Type != PGOHash::None)
208 Hash.combine(Type);
Justin Bognere4ca4412015-02-23 19:27:00 +0000209 return true;
210 }
Vedant Kumar61869712017-11-14 23:56:53 +0000211
212 bool TraverseIfStmt(IfStmt *If) {
213 // If we used the V1 hash, use the default traversal.
214 if (Hash.getHashVersion() == PGO_HASH_V1)
215 return Base::TraverseIfStmt(If);
216
217 // Otherwise, keep track of which branch we're in while traversing.
218 VisitStmt(If);
219 for (Stmt *CS : If->children()) {
220 if (!CS)
221 continue;
222 if (CS == If->getThen())
223 Hash.combine(PGOHash::IfThenBranch);
224 else if (CS == If->getElse())
225 Hash.combine(PGOHash::IfElseBranch);
226 TraverseStmt(CS);
227 }
228 Hash.combine(PGOHash::EndOfScope);
229 return true;
230 }
231
232// If the statement type \p N is nestable, and its nesting impacts profile
233// stability, define a custom traversal which tracks the end of the statement
234// in the hash (provided we're not using the V1 hash).
235#define DEFINE_NESTABLE_TRAVERSAL(N) \
236 bool Traverse##N(N *S) { \
237 Base::Traverse##N(S); \
238 if (Hash.getHashVersion() != PGO_HASH_V1) \
239 Hash.combine(PGOHash::EndOfScope); \
240 return true; \
241 }
242
243 DEFINE_NESTABLE_TRAVERSAL(WhileStmt)
244 DEFINE_NESTABLE_TRAVERSAL(DoStmt)
245 DEFINE_NESTABLE_TRAVERSAL(ForStmt)
246 DEFINE_NESTABLE_TRAVERSAL(CXXForRangeStmt)
247 DEFINE_NESTABLE_TRAVERSAL(ObjCForCollectionStmt)
248 DEFINE_NESTABLE_TRAVERSAL(CXXTryStmt)
249 DEFINE_NESTABLE_TRAVERSAL(CXXCatchStmt)
250
251 /// Get version \p HashVersion of the PGO hash for \p S.
252 PGOHash::HashType getHashType(PGOHashVersion HashVersion, const Stmt *S) {
Justin Bognere4ca4412015-02-23 19:27:00 +0000253 switch (S->getStmtClass()) {
254 default:
255 break;
256 case Stmt::LabelStmtClass:
257 return PGOHash::LabelStmt;
258 case Stmt::WhileStmtClass:
259 return PGOHash::WhileStmt;
260 case Stmt::DoStmtClass:
261 return PGOHash::DoStmt;
262 case Stmt::ForStmtClass:
263 return PGOHash::ForStmt;
264 case Stmt::CXXForRangeStmtClass:
265 return PGOHash::CXXForRangeStmt;
266 case Stmt::ObjCForCollectionStmtClass:
267 return PGOHash::ObjCForCollectionStmt;
268 case Stmt::SwitchStmtClass:
269 return PGOHash::SwitchStmt;
270 case Stmt::CaseStmtClass:
271 return PGOHash::CaseStmt;
272 case Stmt::DefaultStmtClass:
273 return PGOHash::DefaultStmt;
274 case Stmt::IfStmtClass:
275 return PGOHash::IfStmt;
276 case Stmt::CXXTryStmtClass:
277 return PGOHash::CXXTryStmt;
278 case Stmt::CXXCatchStmtClass:
279 return PGOHash::CXXCatchStmt;
280 case Stmt::ConditionalOperatorClass:
281 return PGOHash::ConditionalOperator;
282 case Stmt::BinaryConditionalOperatorClass:
283 return PGOHash::BinaryConditionalOperator;
284 case Stmt::BinaryOperatorClass: {
285 const BinaryOperator *BO = cast<BinaryOperator>(S);
286 if (BO->getOpcode() == BO_LAnd)
287 return PGOHash::BinaryOperatorLAnd;
288 if (BO->getOpcode() == BO_LOr)
289 return PGOHash::BinaryOperatorLOr;
Vedant Kumar61869712017-11-14 23:56:53 +0000290 if (HashVersion == PGO_HASH_V2) {
291 switch (BO->getOpcode()) {
292 default:
293 break;
294 case BO_LT:
295 return PGOHash::BinaryOperatorLT;
296 case BO_GT:
297 return PGOHash::BinaryOperatorGT;
298 case BO_LE:
299 return PGOHash::BinaryOperatorLE;
300 case BO_GE:
301 return PGOHash::BinaryOperatorGE;
302 case BO_EQ:
303 return PGOHash::BinaryOperatorEQ;
304 case BO_NE:
305 return PGOHash::BinaryOperatorNE;
306 }
307 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000308 break;
309 }
310 }
Vedant Kumar61869712017-11-14 23:56:53 +0000311
312 if (HashVersion == PGO_HASH_V2) {
313 switch (S->getStmtClass()) {
314 default:
315 break;
316 case Stmt::GotoStmtClass:
317 return PGOHash::GotoStmt;
318 case Stmt::IndirectGotoStmtClass:
319 return PGOHash::IndirectGotoStmt;
320 case Stmt::BreakStmtClass:
321 return PGOHash::BreakStmt;
322 case Stmt::ContinueStmtClass:
323 return PGOHash::ContinueStmt;
324 case Stmt::ReturnStmtClass:
325 return PGOHash::ReturnStmt;
326 case Stmt::CXXThrowExprClass:
327 return PGOHash::ThrowExpr;
328 case Stmt::UnaryOperatorClass: {
329 const UnaryOperator *UO = cast<UnaryOperator>(S);
330 if (UO->getOpcode() == UO_LNot)
331 return PGOHash::UnaryOperatorLNot;
332 break;
333 }
334 }
335 }
336
Justin Bognere4ca4412015-02-23 19:27:00 +0000337 return PGOHash::None;
338 }
339};
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000340
Justin Bognere4ca4412015-02-23 19:27:00 +0000341/// A StmtVisitor that propagates the raw counts through the AST and
342/// records the count at statements where the value may change.
343struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
344 /// PGO state.
345 CodeGenPGO &PGO;
346
347 /// A flag that is set when the current count should be recorded on the
348 /// next statement, such as at the exit of a loop.
349 bool RecordNextStmtCount;
350
Justin Bognera909abf2015-05-02 00:48:27 +0000351 /// The count at the current location in the traversal.
352 uint64_t CurrentCount;
353
Justin Bognere4ca4412015-02-23 19:27:00 +0000354 /// The map of statements to count values.
355 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
356
357 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
358 struct BreakContinue {
359 uint64_t BreakCount;
360 uint64_t ContinueCount;
361 BreakContinue() : BreakCount(0), ContinueCount(0) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000362 };
Justin Bognere4ca4412015-02-23 19:27:00 +0000363 SmallVector<BreakContinue, 8> BreakContinueStack;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000364
Justin Bognere4ca4412015-02-23 19:27:00 +0000365 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
366 CodeGenPGO &PGO)
367 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000368
Justin Bognere4ca4412015-02-23 19:27:00 +0000369 void RecordStmtCount(const Stmt *S) {
370 if (RecordNextStmtCount) {
Justin Bognera909abf2015-05-02 00:48:27 +0000371 CountMap[S] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000372 RecordNextStmtCount = false;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000373 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000374 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000375
Justin Bogner07193cc2015-05-01 23:41:09 +0000376 /// Set and return the current count.
377 uint64_t setCount(uint64_t Count) {
Justin Bognera909abf2015-05-02 00:48:27 +0000378 CurrentCount = Count;
Justin Bogner07193cc2015-05-01 23:41:09 +0000379 return Count;
380 }
381
Justin Bognere4ca4412015-02-23 19:27:00 +0000382 void VisitStmt(const Stmt *S) {
383 RecordStmtCount(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000384 for (const Stmt *Child : S->children())
385 if (Child)
386 this->Visit(Child);
Justin Bognere4ca4412015-02-23 19:27:00 +0000387 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000388
Justin Bognere4ca4412015-02-23 19:27:00 +0000389 void VisitFunctionDecl(const FunctionDecl *D) {
390 // Counter tracks entry to the function body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000391 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
392 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000393 Visit(D->getBody());
394 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000395
Justin Bognere4ca4412015-02-23 19:27:00 +0000396 // Skip lambda expressions. We visit these as FunctionDecls when we're
397 // generating them and aren't interested in the body when generating a
398 // parent context.
399 void VisitLambdaExpr(const LambdaExpr *LE) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000400
Justin Bognere4ca4412015-02-23 19:27:00 +0000401 void VisitCapturedDecl(const CapturedDecl *D) {
402 // Counter tracks entry to the capture body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000403 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
404 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000405 Visit(D->getBody());
406 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000407
Justin Bognere4ca4412015-02-23 19:27:00 +0000408 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
409 // Counter tracks entry to the method body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000410 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
411 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000412 Visit(D->getBody());
413 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000414
Justin Bognere4ca4412015-02-23 19:27:00 +0000415 void VisitBlockDecl(const BlockDecl *D) {
416 // Counter tracks entry to the block body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000417 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
418 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000419 Visit(D->getBody());
420 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000421
Justin Bognere4ca4412015-02-23 19:27:00 +0000422 void VisitReturnStmt(const ReturnStmt *S) {
423 RecordStmtCount(S);
424 if (S->getRetValue())
425 Visit(S->getRetValue());
Justin Bognera909abf2015-05-02 00:48:27 +0000426 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000427 RecordNextStmtCount = true;
428 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000429
Justin Bognerf959feb2015-04-28 06:31:55 +0000430 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
431 RecordStmtCount(E);
432 if (E->getSubExpr())
433 Visit(E->getSubExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000434 CurrentCount = 0;
Justin Bognerf959feb2015-04-28 06:31:55 +0000435 RecordNextStmtCount = true;
436 }
437
Justin Bognere4ca4412015-02-23 19:27:00 +0000438 void VisitGotoStmt(const GotoStmt *S) {
439 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000440 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000441 RecordNextStmtCount = true;
442 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000443
Justin Bognere4ca4412015-02-23 19:27:00 +0000444 void VisitLabelStmt(const LabelStmt *S) {
445 RecordNextStmtCount = false;
446 // Counter tracks the block following the label.
Justin Bogner07193cc2015-05-01 23:41:09 +0000447 uint64_t BlockCount = setCount(PGO.getRegionCount(S));
448 CountMap[S] = BlockCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000449 Visit(S->getSubStmt());
450 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000451
Justin Bognere4ca4412015-02-23 19:27:00 +0000452 void VisitBreakStmt(const BreakStmt *S) {
453 RecordStmtCount(S);
454 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
Justin Bognera909abf2015-05-02 00:48:27 +0000455 BreakContinueStack.back().BreakCount += CurrentCount;
456 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000457 RecordNextStmtCount = true;
458 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000459
Justin Bognere4ca4412015-02-23 19:27:00 +0000460 void VisitContinueStmt(const ContinueStmt *S) {
461 RecordStmtCount(S);
462 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
Justin Bognera909abf2015-05-02 00:48:27 +0000463 BreakContinueStack.back().ContinueCount += CurrentCount;
464 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000465 RecordNextStmtCount = true;
466 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000467
Justin Bognere4ca4412015-02-23 19:27:00 +0000468 void VisitWhileStmt(const WhileStmt *S) {
469 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000470 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000471
Justin Bognere4ca4412015-02-23 19:27:00 +0000472 BreakContinueStack.push_back(BreakContinue());
473 // Visit the body region first so the break/continue adjustments can be
474 // included when visiting the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000475 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
Justin Bognera909abf2015-05-02 00:48:27 +0000476 CountMap[S->getBody()] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000477 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000478 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000479
480 // ...then go back and propagate counts through the condition. The count
481 // at the start of the condition is the sum of the incoming edges,
482 // the backedge from the end of the loop body, and the edges from
483 // continue statements.
484 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000485 uint64_t CondCount =
486 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
487 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000488 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000489 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000490 RecordNextStmtCount = true;
491 }
492
493 void VisitDoStmt(const DoStmt *S) {
494 RecordStmtCount(S);
Justin Bogner07193cc2015-05-01 23:41:09 +0000495 uint64_t LoopCount = PGO.getRegionCount(S);
496
Justin Bognere4ca4412015-02-23 19:27:00 +0000497 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000498 // The count doesn't include the fallthrough from the parent scope. Add it.
Justin Bognera909abf2015-05-02 00:48:27 +0000499 uint64_t BodyCount = setCount(LoopCount + CurrentCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000500 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000501 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000502 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000503
504 BreakContinue BC = BreakContinueStack.pop_back_val();
505 // The count at the start of the condition is equal to the count at the
Justin Bogner07193cc2015-05-01 23:41:09 +0000506 // end of the body, plus any continues.
507 uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
508 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000509 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000510 setCount(BC.BreakCount + CondCount - LoopCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000511 RecordNextStmtCount = true;
512 }
513
514 void VisitForStmt(const ForStmt *S) {
515 RecordStmtCount(S);
516 if (S->getInit())
517 Visit(S->getInit());
Justin Bogner07193cc2015-05-01 23:41:09 +0000518
Justin Bognera909abf2015-05-02 00:48:27 +0000519 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000520
Justin Bognere4ca4412015-02-23 19:27:00 +0000521 BreakContinueStack.push_back(BreakContinue());
522 // Visit the body region first. (This is basically the same as a while
523 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000524 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
525 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000526 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000527 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000528 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognere4ca4412015-02-23 19:27:00 +0000529
530 // The increment is essentially part of the body but it needs to include
531 // the count for all the continue statements.
532 if (S->getInc()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000533 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
534 CountMap[S->getInc()] = IncCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000535 Visit(S->getInc());
Justin Bognere4ca4412015-02-23 19:27:00 +0000536 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000537
Justin Bognere4ca4412015-02-23 19:27:00 +0000538 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000539 uint64_t CondCount =
540 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000541 if (S->getCond()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000542 CountMap[S->getCond()] = CondCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000543 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000544 }
Justin Bogner07193cc2015-05-01 23:41:09 +0000545 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000546 RecordNextStmtCount = true;
547 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000548
Justin Bognere4ca4412015-02-23 19:27:00 +0000549 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
550 RecordStmtCount(S);
Richard Smith8baa5002018-09-28 18:44:09 +0000551 if (S->getInit())
552 Visit(S->getInit());
Justin Bogner2e5d4842015-04-30 22:58:28 +0000553 Visit(S->getLoopVarStmt());
Justin Bognere4ca4412015-02-23 19:27:00 +0000554 Visit(S->getRangeStmt());
Richard Smith01694c32016-03-20 10:33:40 +0000555 Visit(S->getBeginStmt());
556 Visit(S->getEndStmt());
Justin Bogner07193cc2015-05-01 23:41:09 +0000557
Justin Bognera909abf2015-05-02 00:48:27 +0000558 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000559 BreakContinueStack.push_back(BreakContinue());
560 // Visit the body region first. (This is basically the same as a while
561 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000562 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
563 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000564 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000565 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000566 BreakContinue BC = BreakContinueStack.pop_back_val();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000567
Justin Bognere4ca4412015-02-23 19:27:00 +0000568 // The increment is essentially part of the body but it needs to include
569 // the count for all the continue statements.
Justin Bogner07193cc2015-05-01 23:41:09 +0000570 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
571 CountMap[S->getInc()] = IncCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000572 Visit(S->getInc());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000573
Justin Bognere4ca4412015-02-23 19:27:00 +0000574 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000575 uint64_t CondCount =
576 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
577 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000578 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000579 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000580 RecordNextStmtCount = true;
581 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000582
Justin Bognere4ca4412015-02-23 19:27:00 +0000583 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
584 RecordStmtCount(S);
585 Visit(S->getElement());
Justin Bognera909abf2015-05-02 00:48:27 +0000586 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000587 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000588 // Counter tracks the body of the loop.
589 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
590 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000591 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000592 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000593 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000594
595 setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
596 BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000597 RecordNextStmtCount = true;
598 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000599
Justin Bognere4ca4412015-02-23 19:27:00 +0000600 void VisitSwitchStmt(const SwitchStmt *S) {
601 RecordStmtCount(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +0000602 if (S->getInit())
603 Visit(S->getInit());
Justin Bognere4ca4412015-02-23 19:27:00 +0000604 Visit(S->getCond());
Justin Bognera909abf2015-05-02 00:48:27 +0000605 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000606 BreakContinueStack.push_back(BreakContinue());
607 Visit(S->getBody());
608 // If the switch is inside a loop, add the continue counts.
609 BreakContinue BC = BreakContinueStack.pop_back_val();
610 if (!BreakContinueStack.empty())
611 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
612 // Counter tracks the exit block of the switch.
Justin Bogner07193cc2015-05-01 23:41:09 +0000613 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000614 RecordNextStmtCount = true;
615 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000616
Justin Bogner07193cc2015-05-01 23:41:09 +0000617 void VisitSwitchCase(const SwitchCase *S) {
Justin Bognere4ca4412015-02-23 19:27:00 +0000618 RecordNextStmtCount = false;
619 // Counter for this particular case. This counts only jumps from the
620 // switch header and does not include fallthrough from the case before
621 // this one.
Justin Bogner07193cc2015-05-01 23:41:09 +0000622 uint64_t CaseCount = PGO.getRegionCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000623 setCount(CurrentCount + CaseCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000624 // We need the count without fallthrough in the mapping, so it's more useful
625 // for branch probabilities.
626 CountMap[S] = CaseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000627 RecordNextStmtCount = true;
628 Visit(S->getSubStmt());
629 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000630
Justin Bognere4ca4412015-02-23 19:27:00 +0000631 void VisitIfStmt(const IfStmt *S) {
632 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000633 uint64_t ParentCount = CurrentCount;
Vedant Kumar9d2a16b2016-10-14 23:38:16 +0000634 if (S->getInit())
635 Visit(S->getInit());
Justin Bognere4ca4412015-02-23 19:27:00 +0000636 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000637
Justin Bogner07193cc2015-05-01 23:41:09 +0000638 // Counter tracks the "then" part of an if statement. The count for
639 // the "else" part, if it exists, will be calculated from this counter.
640 uint64_t ThenCount = setCount(PGO.getRegionCount(S));
641 CountMap[S->getThen()] = ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000642 Visit(S->getThen());
Justin Bognera909abf2015-05-02 00:48:27 +0000643 uint64_t OutCount = CurrentCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000644
Justin Bogner07193cc2015-05-01 23:41:09 +0000645 uint64_t ElseCount = ParentCount - ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000646 if (S->getElse()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000647 setCount(ElseCount);
648 CountMap[S->getElse()] = ElseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000649 Visit(S->getElse());
Justin Bognera909abf2015-05-02 00:48:27 +0000650 OutCount += CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000651 } else
652 OutCount += ElseCount;
653 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000654 RecordNextStmtCount = true;
655 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000656
Justin Bognere4ca4412015-02-23 19:27:00 +0000657 void VisitCXXTryStmt(const CXXTryStmt *S) {
658 RecordStmtCount(S);
659 Visit(S->getTryBlock());
660 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
661 Visit(S->getHandler(I));
662 // Counter tracks the continuation block of the try statement.
Justin Bogner07193cc2015-05-01 23:41:09 +0000663 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000664 RecordNextStmtCount = true;
665 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000666
Justin Bognere4ca4412015-02-23 19:27:00 +0000667 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
668 RecordNextStmtCount = false;
669 // Counter tracks the catch statement's handler block.
Justin Bogner07193cc2015-05-01 23:41:09 +0000670 uint64_t CatchCount = setCount(PGO.getRegionCount(S));
671 CountMap[S] = CatchCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000672 Visit(S->getHandlerBlock());
673 }
674
675 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
676 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000677 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000678 Visit(E->getCond());
679
Justin Bogner07193cc2015-05-01 23:41:09 +0000680 // Counter tracks the "true" part of a conditional operator. The
681 // count in the "false" part will be calculated from this counter.
682 uint64_t TrueCount = setCount(PGO.getRegionCount(E));
683 CountMap[E->getTrueExpr()] = TrueCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000684 Visit(E->getTrueExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000685 uint64_t OutCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000686
Justin Bogner07193cc2015-05-01 23:41:09 +0000687 uint64_t FalseCount = setCount(ParentCount - TrueCount);
688 CountMap[E->getFalseExpr()] = FalseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000689 Visit(E->getFalseExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000690 OutCount += CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000691
Justin Bogner07193cc2015-05-01 23:41:09 +0000692 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000693 RecordNextStmtCount = true;
694 }
695
696 void VisitBinLAnd(const BinaryOperator *E) {
697 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000698 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000699 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000700 // Counter tracks the right hand side of a logical and operator.
701 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
702 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000703 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000704 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000705 RecordNextStmtCount = true;
706 }
707
708 void VisitBinLOr(const BinaryOperator *E) {
709 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000710 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000711 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000712 // Counter tracks the right hand side of a logical or operator.
713 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
714 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000715 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000716 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000717 RecordNextStmtCount = true;
718 }
719};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000720} // end anonymous namespace
Justin Bogneref512b92014-01-06 22:27:43 +0000721
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000722void PGOHash::combine(HashType Type) {
723 // Check that we never combine 0 and only have six bits.
724 assert(Type && "Hash is invalid: unexpected type 0");
725 assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
726
727 // Pass through MD5 if enough work has built up.
728 if (Count && Count % NumTypesPerWord == 0) {
729 using namespace llvm::support;
730 uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
731 MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
732 Working = 0;
733 }
734
735 // Accumulate the current type.
736 ++Count;
737 Working = Working << NumBitsPerType | Type;
738}
739
740uint64_t PGOHash::finalize() {
741 // Use Working as the hash directly if we never used MD5.
742 if (Count <= NumTypesPerWord)
743 // No need to byte swap here, since none of the math was endian-dependent.
744 // This number will be byte-swapped as required on endianness transitions,
745 // so we will see the same value on the other side.
746 return Working;
747
748 // Check for remaining work in Working.
749 if (Working)
750 MD5.update(Working);
751
752 // Finalize the MD5 and return the hash.
753 llvm::MD5::MD5Result Result;
754 MD5.final(Result);
755 using namespace llvm::support;
Zachary Turner82a0c972017-03-20 23:33:18 +0000756 return Result.low();
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000757}
758
Serge Pavlov3a561452015-12-06 14:32:39 +0000759void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
760 const Decl *D = GD.getDecl();
Vedant Kumar33d0a1c2017-06-30 21:02:14 +0000761 if (!D->hasBody())
762 return;
763
Rong Xu9837ef52016-02-04 18:39:09 +0000764 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
Justin Bogner837a6f62014-04-18 21:52:00 +0000765 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
766 if (!InstrumentRegions && !PGOReader)
Justin Bogneref512b92014-01-06 22:27:43 +0000767 return;
Justin Bogner3212b182014-04-25 07:20:05 +0000768 if (D->isImplicit())
Justin Bogneref512b92014-01-06 22:27:43 +0000769 return;
Serge Pavlov3a561452015-12-06 14:32:39 +0000770 // Constructors and destructors may be represented by several functions in IR.
771 // If so, instrument only base variant, others are implemented by delegation
772 // to the base one, it would be counted twice otherwise.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000773 if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Vedant Kumar7f809b22017-02-24 01:15:19 +0000774 if (const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
775 if (GD.getCtorType() != Ctor_Base &&
776 CodeGenFunction::IsConstructorDelegationValid(CCD))
777 return;
Serge Pavlov3a561452015-12-06 14:32:39 +0000778 }
Reid Klecknerf9ef9f82019-02-26 20:42:52 +0000779 if (isa<CXXDestructorDecl>(D) && GD.getDtorType() != Dtor_Base)
780 return;
781
Alex Lorenzee024992014-08-04 18:41:51 +0000782 CGM.ClearUnusedCoverageMapping(D);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000783 setFuncName(Fn);
Duncan P. N. Exon Smith7c414512014-03-20 22:50:08 +0000784
Justin Bogneref512b92014-01-06 22:27:43 +0000785 mapRegionCounters(D);
Justin Bogner970ac602014-12-08 19:04:51 +0000786 if (CGM.getCodeGenOpts().CoverageMapping)
787 emitCounterRegionMapping(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000788 if (PGOReader) {
Justin Bogner40b8ba12014-06-26 01:45:07 +0000789 SourceManager &SM = CGM.getContext().getSourceManager();
790 loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000791 computeRegionCounts(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000792 applyFunctionAttributes(PGOReader, Fn);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000793 }
Justin Bogneref512b92014-01-06 22:27:43 +0000794}
795
796void CodeGenPGO::mapRegionCounters(const Decl *D) {
Vedant Kumar61869712017-11-14 23:56:53 +0000797 // Use the latest hash version when inserting instrumentation, but use the
798 // version in the indexed profile if we're reading PGO data.
799 PGOHashVersion HashVersion = PGO_HASH_LATEST;
800 if (auto *PGOReader = CGM.getPGOReader())
801 HashVersion = getPGOHashVersion(PGOReader, CGM);
802
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000803 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
Vedant Kumar61869712017-11-14 23:56:53 +0000804 MapRegionCounters Walker(HashVersion, *RegionCounterMap);
Justin Bogneref512b92014-01-06 22:27:43 +0000805 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000806 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000807 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000808 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
Bob Wilsonc845c002014-03-06 20:24:27 +0000809 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000810 Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
Justin Bogner81ab90f2014-04-15 00:50:54 +0000811 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
812 Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
Justin Bogner3212b182014-04-25 07:20:05 +0000813 assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
Justin Bogneref512b92014-01-06 22:27:43 +0000814 NumRegionCounters = Walker.NextCounter;
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000815 FunctionHash = Walker.Hash.finalize();
Justin Bogneref512b92014-01-06 22:27:43 +0000816}
817
Vedant Kumarc468bb82016-07-11 22:57:44 +0000818bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
Vedant Kumarbc370f02017-04-24 20:52:04 +0000819 if (!D->getBody())
820 return true;
821
Vedant Kumarc468bb82016-07-11 22:57:44 +0000822 // Don't map the functions in system headers.
823 const auto &SM = CGM.getContext().getSourceManager();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000824 auto Loc = D->getBody()->getBeginLoc();
Vedant Kumarc468bb82016-07-11 22:57:44 +0000825 return SM.isInSystemHeader(Loc);
826}
827
828void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
829 if (skipRegionMappingForDecl(D))
Alex Lorenzee024992014-08-04 18:41:51 +0000830 return;
831
Justin Bogner970ac602014-12-08 19:04:51 +0000832 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000833 llvm::raw_string_ostream OS(CoverageMapping);
834 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
835 CGM.getContext().getSourceManager(),
Justin Bognere5ee6c52014-10-02 16:44:01 +0000836 CGM.getLangOpts(), RegionCounterMap.get());
Alex Lorenzee024992014-08-04 18:41:51 +0000837 MappingGen.emitCounterMapping(D, OS);
838 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000839
840 if (CoverageMapping.empty())
841 return;
842
843 CGM.getCoverageMapping()->addFunctionMappingRecord(
844 FuncNameVar, FuncName, FunctionHash, CoverageMapping);
Alex Lorenzee024992014-08-04 18:41:51 +0000845}
846
847void
Justin Bogner60d852b2015-04-23 00:31:16 +0000848CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
Alex Lorenzee024992014-08-04 18:41:51 +0000849 llvm::GlobalValue::LinkageTypes Linkage) {
Vedant Kumarc468bb82016-07-11 22:57:44 +0000850 if (skipRegionMappingForDecl(D))
Alex Lorenzee024992014-08-04 18:41:51 +0000851 return;
852
Justin Bogner970ac602014-12-08 19:04:51 +0000853 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000854 llvm::raw_string_ostream OS(CoverageMapping);
855 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
856 CGM.getContext().getSourceManager(),
857 CGM.getLangOpts());
858 MappingGen.emitEmptyMapping(D, OS);
859 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000860
861 if (CoverageMapping.empty())
862 return;
863
Justin Bogner60d852b2015-04-23 00:31:16 +0000864 setFuncName(Name, Linkage);
Justin Bogner970ac602014-12-08 19:04:51 +0000865 CGM.getCoverageMapping()->addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +0000866 FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
Alex Lorenzee024992014-08-04 18:41:51 +0000867}
868
Bob Wilsonbf854f02014-02-17 19:21:09 +0000869void CodeGenPGO::computeRegionCounts(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000870 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000871 ComputeRegionCounts Walker(*StmtCountMap, *this);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000872 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
873 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000874 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
875 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000876 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
877 Walker.VisitBlockDecl(BD);
Justin Bogner81ab90f2014-04-15 00:50:54 +0000878 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
879 Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000880}
881
Justin Bogner837a6f62014-04-18 21:52:00 +0000882void
883CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
884 llvm::Function *Fn) {
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000885 if (!haveRegionCounts())
886 return;
887
Hans Wennborgdcfba332015-10-06 23:40:43 +0000888 uint64_t FunctionCount = getRegionCount(nullptr);
Diego Novilloaa8b1cb2015-05-27 21:58:42 +0000889 Fn->setEntryCount(FunctionCount);
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000890}
891
Vedant Kumar502bbfa2017-02-25 06:35:45 +0000892void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S,
893 llvm::Value *StepV) {
Rong Xu9837ef52016-02-04 18:39:09 +0000894 if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap)
Justin Bogneref512b92014-01-06 22:27:43 +0000895 return;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000896 if (!Builder.GetInsertBlock())
Justin Bogner203f91e2015-01-09 01:46:40 +0000897 return;
Justin Bogner66242d62015-04-23 23:06:47 +0000898
899 unsigned Counter = (*RegionCounterMap)[S];
Justin Bogner970ac602014-12-08 19:04:51 +0000900 auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Vedant Kumar502bbfa2017-02-25 06:35:45 +0000901
902 llvm::Value *Args[] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
903 Builder.getInt64(FunctionHash),
904 Builder.getInt32(NumRegionCounters),
905 Builder.getInt32(Counter), StepV};
906 if (!StepV)
907 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
908 makeArrayRef(Args, 4));
909 else
910 Builder.CreateCall(
911 CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step),
912 makeArrayRef(Args));
Justin Bogneref512b92014-01-06 22:27:43 +0000913}
914
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000915// This method either inserts a call to the profile run-time during
916// instrumentation or puts profile data into metadata for PGO use.
917void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
918 llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
919
920 if (!EnableValueProfiling)
921 return;
922
923 if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
924 return;
925
Betul Buyukkurt3da993c2016-03-31 18:41:34 +0000926 if (isa<llvm::Constant>(ValuePtr))
927 return;
928
Rong Xu9837ef52016-02-04 18:39:09 +0000929 bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000930 if (InstrumentValueSites && RegionCounterMap) {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000931 auto BuilderInsertPoint = Builder.saveIP();
932 Builder.SetInsertPoint(ValueSite);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000933 llvm::Value *Args[5] = {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000934 llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()),
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000935 Builder.getInt64(FunctionHash),
936 Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
937 Builder.getInt32(ValueKind),
938 Builder.getInt32(NumValueSites[ValueKind]++)
939 };
940 Builder.CreateCall(
941 CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000942 Builder.restoreIP(BuilderInsertPoint);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000943 return;
944 }
945
946 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
947 if (PGOReader && haveRegionCounts()) {
948 // We record the top most called three functions at each call site.
949 // Profile metadata contains "VP" string identifying this metadata
950 // as value profiling data, then a uint32_t value for the value profiling
951 // kind, a uint64_t value for the total number of times the call is
952 // executed, followed by the function hash and execution count (uint64_t)
953 // pairs for each function.
954 if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
955 return;
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000956
Xinliang David Li5527a9d2016-02-04 19:54:17 +0000957 llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
958 (llvm::InstrProfValueKind)ValueKind,
959 NumValueSites[ValueKind]);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000960
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000961 NumValueSites[ValueKind]++;
962 }
963}
964
Justin Bogner40b8ba12014-06-26 01:45:07 +0000965void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
966 bool IsInMainFile) {
967 CGM.getPGOStats().addVisited(IsInMainFile);
Justin Bogner7f8cf5b2014-12-02 22:38:52 +0000968 RegionCounts.clear();
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000969 llvm::Expected<llvm::InstrProfRecord> RecordExpected =
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000970 PGOReader->getInstrProfRecord(FuncName, FunctionHash);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000971 if (auto E = RecordExpected.takeError()) {
972 auto IPE = llvm::InstrProfError::take(std::move(E));
973 if (IPE == llvm::instrprof_error::unknown_function)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000974 CGM.getPGOStats().addMissing(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000975 else if (IPE == llvm::instrprof_error::hash_mismatch)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000976 CGM.getPGOStats().addMismatched(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000977 else if (IPE == llvm::instrprof_error::malformed)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000978 // TODO: Consider a more specific warning for this case.
979 CGM.getPGOStats().addMismatched(IsInMainFile);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000980 return;
Justin Bognere2ef2a02014-04-15 21:22:35 +0000981 }
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000982 ProfRecord =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000983 std::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000984 RegionCounts = ProfRecord->Counts;
Justin Bogneref512b92014-01-06 22:27:43 +0000985}
986
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000987/// Calculate what to divide by to scale weights.
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000988///
989/// Given the maximum weight, calculate a divisor that will scale all the
990/// weights to strictly less than UINT32_MAX.
991static uint64_t calculateWeightScale(uint64_t MaxWeight) {
992 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
993}
994
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000995/// Scale an individual branch weight (and add 1).
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000996///
997/// Scale a 64-bit weight down to 32-bits using \c Scale.
998///
999/// According to Laplace's Rule of Succession, it is better to compute the
1000/// weight based on the count plus 1, so universally add 1 to the value.
1001///
1002/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
1003/// greater than \c Weight.
1004static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
1005 assert(Scale && "scale by 0?");
1006 uint64_t Scaled = Weight / Scale + 1;
1007 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
1008 return Scaled;
1009}
1010
Justin Bogner65512642015-05-02 05:00:55 +00001011llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
1012 uint64_t FalseCount) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001013 // Check for empty weights.
Justin Bogneref512b92014-01-06 22:27:43 +00001014 if (!TrueCount && !FalseCount)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001015 return nullptr;
Justin Bogneref512b92014-01-06 22:27:43 +00001016
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001017 // Calculate how to scale down to 32-bits.
1018 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
1019
Justin Bogneref512b92014-01-06 22:27:43 +00001020 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001021 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
1022 scaleBranchWeight(FalseCount, Scale));
Justin Bogneref512b92014-01-06 22:27:43 +00001023}
1024
Justin Bogner65512642015-05-02 05:00:55 +00001025llvm::MDNode *
1026CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001027 // We need at least two elements to create meaningful weights.
1028 if (Weights.size() < 2)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001029 return nullptr;
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001030
Justin Bognerf3aefca2014-04-04 02:48:51 +00001031 // Check for empty weights.
1032 uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
1033 if (MaxWeight == 0)
1034 return nullptr;
1035
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001036 // Calculate how to scale down to 32-bits.
Justin Bognerf3aefca2014-04-04 02:48:51 +00001037 uint64_t Scale = calculateWeightScale(MaxWeight);
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001038
Justin Bogneref512b92014-01-06 22:27:43 +00001039 SmallVector<uint32_t, 16> ScaledWeights;
1040 ScaledWeights.reserve(Weights.size());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001041 for (uint64_t W : Weights)
1042 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
1043
1044 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Justin Bogneref512b92014-01-06 22:27:43 +00001045 return MDHelper.createBranchWeights(ScaledWeights);
1046}
Bob Wilsonbf854f02014-02-17 19:21:09 +00001047
Justin Bogner65512642015-05-02 05:00:55 +00001048llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
1049 uint64_t LoopCount) {
1050 if (!PGO.haveRegionCounts())
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001051 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +00001052 Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
Justin Bogner1c21c282015-04-13 12:23:19 +00001053 assert(CondCount.hasValue() && "missing expected loop condition count");
1054 if (*CondCount == 0)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001055 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +00001056 return createProfileWeights(LoopCount,
1057 std::max(*CondCount, LoopCount) - LoopCount);
Bob Wilsonbf854f02014-02-17 19:21:09 +00001058}