blob: 6a4b4df88ae509b8bdaee8a987b9c8a2e92bdaa7 [file] [log] [blame]
Justin Bogneref512b92014-01-06 22:27:43 +00001//===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Instrumentation-based profile-guided optimization
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenPGO.h"
15#include "CodeGenFunction.h"
Alex Lorenzee024992014-08-04 18:41:51 +000016#include "CoverageMappingGen.h"
Justin Bogneref512b92014-01-06 22:27:43 +000017#include "clang/AST/RecursiveASTVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Justin Bogner970ac602014-12-08 19:04:51 +000019#include "llvm/IR/Intrinsics.h"
Justin Bogneref512b92014-01-06 22:27:43 +000020#include "llvm/IR/MDBuilder.h"
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000021#include "llvm/Support/Endian.h"
Justin Bogneref512b92014-01-06 22:27:43 +000022#include "llvm/Support/FileSystem.h"
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000023#include "llvm/Support/MD5.h"
Justin Bogneref512b92014-01-06 22:27:43 +000024
Betul Buyukkurt518276a2016-01-23 22:50:44 +000025static llvm::cl::opt<bool> EnableValueProfiling(
26 "enable-value-profiling", llvm::cl::ZeroOrMore,
27 llvm::cl::desc("Enable value profiling"), llvm::cl::init(false));
28
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 {
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000060/// \brief Stable hasher for PGO region counters.
61///
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:
81 /// \brief Hash values for AST nodes.
82 ///
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; }
167 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
168 bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
Justin Bogneref512b92014-01-06 22:27:43 +0000169
Justin Bognere4ca4412015-02-23 19:27:00 +0000170 bool VisitDecl(const Decl *D) {
171 switch (D->getKind()) {
172 default:
173 break;
174 case Decl::Function:
175 case Decl::CXXMethod:
176 case Decl::CXXConstructor:
177 case Decl::CXXDestructor:
178 case Decl::CXXConversion:
179 case Decl::ObjCMethod:
180 case Decl::Block:
181 case Decl::Captured:
182 CounterMap[D->getBody()] = NextCounter++;
183 break;
184 }
185 return true;
186 }
187
Vedant Kumar61869712017-11-14 23:56:53 +0000188 /// If \p S gets a fresh counter, update the counter mappings. Return the
189 /// V1 hash of \p S.
190 PGOHash::HashType updateCounterMappings(Stmt *S) {
191 auto Type = getHashType(PGO_HASH_V1, S);
192 if (Type != PGOHash::None)
193 CounterMap[S] = NextCounter++;
194 return Type;
195 }
Bob Wilsond8931422014-04-11 17:16:13 +0000196
Vedant Kumar61869712017-11-14 23:56:53 +0000197 /// Include \p S in the function hash.
198 bool VisitStmt(Stmt *S) {
199 auto Type = updateCounterMappings(S);
200 if (Hash.getHashVersion() != PGO_HASH_V1)
201 Type = getHashType(Hash.getHashVersion(), S);
202 if (Type != PGOHash::None)
203 Hash.combine(Type);
Justin Bognere4ca4412015-02-23 19:27:00 +0000204 return true;
205 }
Vedant Kumar61869712017-11-14 23:56:53 +0000206
207 bool TraverseIfStmt(IfStmt *If) {
208 // If we used the V1 hash, use the default traversal.
209 if (Hash.getHashVersion() == PGO_HASH_V1)
210 return Base::TraverseIfStmt(If);
211
212 // Otherwise, keep track of which branch we're in while traversing.
213 VisitStmt(If);
214 for (Stmt *CS : If->children()) {
215 if (!CS)
216 continue;
217 if (CS == If->getThen())
218 Hash.combine(PGOHash::IfThenBranch);
219 else if (CS == If->getElse())
220 Hash.combine(PGOHash::IfElseBranch);
221 TraverseStmt(CS);
222 }
223 Hash.combine(PGOHash::EndOfScope);
224 return true;
225 }
226
227// If the statement type \p N is nestable, and its nesting impacts profile
228// stability, define a custom traversal which tracks the end of the statement
229// in the hash (provided we're not using the V1 hash).
230#define DEFINE_NESTABLE_TRAVERSAL(N) \
231 bool Traverse##N(N *S) { \
232 Base::Traverse##N(S); \
233 if (Hash.getHashVersion() != PGO_HASH_V1) \
234 Hash.combine(PGOHash::EndOfScope); \
235 return true; \
236 }
237
238 DEFINE_NESTABLE_TRAVERSAL(WhileStmt)
239 DEFINE_NESTABLE_TRAVERSAL(DoStmt)
240 DEFINE_NESTABLE_TRAVERSAL(ForStmt)
241 DEFINE_NESTABLE_TRAVERSAL(CXXForRangeStmt)
242 DEFINE_NESTABLE_TRAVERSAL(ObjCForCollectionStmt)
243 DEFINE_NESTABLE_TRAVERSAL(CXXTryStmt)
244 DEFINE_NESTABLE_TRAVERSAL(CXXCatchStmt)
245
246 /// Get version \p HashVersion of the PGO hash for \p S.
247 PGOHash::HashType getHashType(PGOHashVersion HashVersion, const Stmt *S) {
Justin Bognere4ca4412015-02-23 19:27:00 +0000248 switch (S->getStmtClass()) {
249 default:
250 break;
251 case Stmt::LabelStmtClass:
252 return PGOHash::LabelStmt;
253 case Stmt::WhileStmtClass:
254 return PGOHash::WhileStmt;
255 case Stmt::DoStmtClass:
256 return PGOHash::DoStmt;
257 case Stmt::ForStmtClass:
258 return PGOHash::ForStmt;
259 case Stmt::CXXForRangeStmtClass:
260 return PGOHash::CXXForRangeStmt;
261 case Stmt::ObjCForCollectionStmtClass:
262 return PGOHash::ObjCForCollectionStmt;
263 case Stmt::SwitchStmtClass:
264 return PGOHash::SwitchStmt;
265 case Stmt::CaseStmtClass:
266 return PGOHash::CaseStmt;
267 case Stmt::DefaultStmtClass:
268 return PGOHash::DefaultStmt;
269 case Stmt::IfStmtClass:
270 return PGOHash::IfStmt;
271 case Stmt::CXXTryStmtClass:
272 return PGOHash::CXXTryStmt;
273 case Stmt::CXXCatchStmtClass:
274 return PGOHash::CXXCatchStmt;
275 case Stmt::ConditionalOperatorClass:
276 return PGOHash::ConditionalOperator;
277 case Stmt::BinaryConditionalOperatorClass:
278 return PGOHash::BinaryConditionalOperator;
279 case Stmt::BinaryOperatorClass: {
280 const BinaryOperator *BO = cast<BinaryOperator>(S);
281 if (BO->getOpcode() == BO_LAnd)
282 return PGOHash::BinaryOperatorLAnd;
283 if (BO->getOpcode() == BO_LOr)
284 return PGOHash::BinaryOperatorLOr;
Vedant Kumar61869712017-11-14 23:56:53 +0000285 if (HashVersion == PGO_HASH_V2) {
286 switch (BO->getOpcode()) {
287 default:
288 break;
289 case BO_LT:
290 return PGOHash::BinaryOperatorLT;
291 case BO_GT:
292 return PGOHash::BinaryOperatorGT;
293 case BO_LE:
294 return PGOHash::BinaryOperatorLE;
295 case BO_GE:
296 return PGOHash::BinaryOperatorGE;
297 case BO_EQ:
298 return PGOHash::BinaryOperatorEQ;
299 case BO_NE:
300 return PGOHash::BinaryOperatorNE;
301 }
302 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000303 break;
304 }
305 }
Vedant Kumar61869712017-11-14 23:56:53 +0000306
307 if (HashVersion == PGO_HASH_V2) {
308 switch (S->getStmtClass()) {
309 default:
310 break;
311 case Stmt::GotoStmtClass:
312 return PGOHash::GotoStmt;
313 case Stmt::IndirectGotoStmtClass:
314 return PGOHash::IndirectGotoStmt;
315 case Stmt::BreakStmtClass:
316 return PGOHash::BreakStmt;
317 case Stmt::ContinueStmtClass:
318 return PGOHash::ContinueStmt;
319 case Stmt::ReturnStmtClass:
320 return PGOHash::ReturnStmt;
321 case Stmt::CXXThrowExprClass:
322 return PGOHash::ThrowExpr;
323 case Stmt::UnaryOperatorClass: {
324 const UnaryOperator *UO = cast<UnaryOperator>(S);
325 if (UO->getOpcode() == UO_LNot)
326 return PGOHash::UnaryOperatorLNot;
327 break;
328 }
329 }
330 }
331
Justin Bognere4ca4412015-02-23 19:27:00 +0000332 return PGOHash::None;
333 }
334};
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000335
Justin Bognere4ca4412015-02-23 19:27:00 +0000336/// A StmtVisitor that propagates the raw counts through the AST and
337/// records the count at statements where the value may change.
338struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
339 /// PGO state.
340 CodeGenPGO &PGO;
341
342 /// A flag that is set when the current count should be recorded on the
343 /// next statement, such as at the exit of a loop.
344 bool RecordNextStmtCount;
345
Justin Bognera909abf2015-05-02 00:48:27 +0000346 /// The count at the current location in the traversal.
347 uint64_t CurrentCount;
348
Justin Bognere4ca4412015-02-23 19:27:00 +0000349 /// The map of statements to count values.
350 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
351
352 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
353 struct BreakContinue {
354 uint64_t BreakCount;
355 uint64_t ContinueCount;
356 BreakContinue() : BreakCount(0), ContinueCount(0) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000357 };
Justin Bognere4ca4412015-02-23 19:27:00 +0000358 SmallVector<BreakContinue, 8> BreakContinueStack;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000359
Justin Bognere4ca4412015-02-23 19:27:00 +0000360 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
361 CodeGenPGO &PGO)
362 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000363
Justin Bognere4ca4412015-02-23 19:27:00 +0000364 void RecordStmtCount(const Stmt *S) {
365 if (RecordNextStmtCount) {
Justin Bognera909abf2015-05-02 00:48:27 +0000366 CountMap[S] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000367 RecordNextStmtCount = false;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000368 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000369 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000370
Justin Bogner07193cc2015-05-01 23:41:09 +0000371 /// Set and return the current count.
372 uint64_t setCount(uint64_t Count) {
Justin Bognera909abf2015-05-02 00:48:27 +0000373 CurrentCount = Count;
Justin Bogner07193cc2015-05-01 23:41:09 +0000374 return Count;
375 }
376
Justin Bognere4ca4412015-02-23 19:27:00 +0000377 void VisitStmt(const Stmt *S) {
378 RecordStmtCount(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000379 for (const Stmt *Child : S->children())
380 if (Child)
381 this->Visit(Child);
Justin Bognere4ca4412015-02-23 19:27:00 +0000382 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000383
Justin Bognere4ca4412015-02-23 19:27:00 +0000384 void VisitFunctionDecl(const FunctionDecl *D) {
385 // Counter tracks entry to the function body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000386 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
387 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000388 Visit(D->getBody());
389 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000390
Justin Bognere4ca4412015-02-23 19:27:00 +0000391 // Skip lambda expressions. We visit these as FunctionDecls when we're
392 // generating them and aren't interested in the body when generating a
393 // parent context.
394 void VisitLambdaExpr(const LambdaExpr *LE) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000395
Justin Bognere4ca4412015-02-23 19:27:00 +0000396 void VisitCapturedDecl(const CapturedDecl *D) {
397 // Counter tracks entry to the capture body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000398 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
399 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000400 Visit(D->getBody());
401 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000402
Justin Bognere4ca4412015-02-23 19:27:00 +0000403 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
404 // Counter tracks entry to the method body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000405 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
406 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000407 Visit(D->getBody());
408 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000409
Justin Bognere4ca4412015-02-23 19:27:00 +0000410 void VisitBlockDecl(const BlockDecl *D) {
411 // Counter tracks entry to the block body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000412 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
413 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000414 Visit(D->getBody());
415 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000416
Justin Bognere4ca4412015-02-23 19:27:00 +0000417 void VisitReturnStmt(const ReturnStmt *S) {
418 RecordStmtCount(S);
419 if (S->getRetValue())
420 Visit(S->getRetValue());
Justin Bognera909abf2015-05-02 00:48:27 +0000421 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000422 RecordNextStmtCount = true;
423 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000424
Justin Bognerf959feb2015-04-28 06:31:55 +0000425 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
426 RecordStmtCount(E);
427 if (E->getSubExpr())
428 Visit(E->getSubExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000429 CurrentCount = 0;
Justin Bognerf959feb2015-04-28 06:31:55 +0000430 RecordNextStmtCount = true;
431 }
432
Justin Bognere4ca4412015-02-23 19:27:00 +0000433 void VisitGotoStmt(const GotoStmt *S) {
434 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000435 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000436 RecordNextStmtCount = true;
437 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000438
Justin Bognere4ca4412015-02-23 19:27:00 +0000439 void VisitLabelStmt(const LabelStmt *S) {
440 RecordNextStmtCount = false;
441 // Counter tracks the block following the label.
Justin Bogner07193cc2015-05-01 23:41:09 +0000442 uint64_t BlockCount = setCount(PGO.getRegionCount(S));
443 CountMap[S] = BlockCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000444 Visit(S->getSubStmt());
445 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000446
Justin Bognere4ca4412015-02-23 19:27:00 +0000447 void VisitBreakStmt(const BreakStmt *S) {
448 RecordStmtCount(S);
449 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
Justin Bognera909abf2015-05-02 00:48:27 +0000450 BreakContinueStack.back().BreakCount += CurrentCount;
451 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000452 RecordNextStmtCount = true;
453 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000454
Justin Bognere4ca4412015-02-23 19:27:00 +0000455 void VisitContinueStmt(const ContinueStmt *S) {
456 RecordStmtCount(S);
457 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
Justin Bognera909abf2015-05-02 00:48:27 +0000458 BreakContinueStack.back().ContinueCount += CurrentCount;
459 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000460 RecordNextStmtCount = true;
461 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000462
Justin Bognere4ca4412015-02-23 19:27:00 +0000463 void VisitWhileStmt(const WhileStmt *S) {
464 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000465 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000466
Justin Bognere4ca4412015-02-23 19:27:00 +0000467 BreakContinueStack.push_back(BreakContinue());
468 // Visit the body region first so the break/continue adjustments can be
469 // included when visiting the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000470 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
Justin Bognera909abf2015-05-02 00:48:27 +0000471 CountMap[S->getBody()] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000472 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000473 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000474
475 // ...then go back and propagate counts through the condition. The count
476 // at the start of the condition is the sum of the incoming edges,
477 // the backedge from the end of the loop body, and the edges from
478 // continue statements.
479 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000480 uint64_t CondCount =
481 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
482 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000483 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000484 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000485 RecordNextStmtCount = true;
486 }
487
488 void VisitDoStmt(const DoStmt *S) {
489 RecordStmtCount(S);
Justin Bogner07193cc2015-05-01 23:41:09 +0000490 uint64_t LoopCount = PGO.getRegionCount(S);
491
Justin Bognere4ca4412015-02-23 19:27:00 +0000492 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000493 // The count doesn't include the fallthrough from the parent scope. Add it.
Justin Bognera909abf2015-05-02 00:48:27 +0000494 uint64_t BodyCount = setCount(LoopCount + CurrentCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000495 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000496 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000497 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000498
499 BreakContinue BC = BreakContinueStack.pop_back_val();
500 // The count at the start of the condition is equal to the count at the
Justin Bogner07193cc2015-05-01 23:41:09 +0000501 // end of the body, plus any continues.
502 uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
503 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000504 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000505 setCount(BC.BreakCount + CondCount - LoopCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000506 RecordNextStmtCount = true;
507 }
508
509 void VisitForStmt(const ForStmt *S) {
510 RecordStmtCount(S);
511 if (S->getInit())
512 Visit(S->getInit());
Justin Bogner07193cc2015-05-01 23:41:09 +0000513
Justin Bognera909abf2015-05-02 00:48:27 +0000514 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000515
Justin Bognere4ca4412015-02-23 19:27:00 +0000516 BreakContinueStack.push_back(BreakContinue());
517 // Visit the body region first. (This is basically the same as a while
518 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000519 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
520 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000521 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000522 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000523 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognere4ca4412015-02-23 19:27:00 +0000524
525 // The increment is essentially part of the body but it needs to include
526 // the count for all the continue statements.
527 if (S->getInc()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000528 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
529 CountMap[S->getInc()] = IncCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000530 Visit(S->getInc());
Justin Bognere4ca4412015-02-23 19:27:00 +0000531 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000532
Justin Bognere4ca4412015-02-23 19:27:00 +0000533 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000534 uint64_t CondCount =
535 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000536 if (S->getCond()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000537 CountMap[S->getCond()] = CondCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000538 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000539 }
Justin Bogner07193cc2015-05-01 23:41:09 +0000540 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000541 RecordNextStmtCount = true;
542 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000543
Justin Bognere4ca4412015-02-23 19:27:00 +0000544 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
545 RecordStmtCount(S);
Justin Bogner2e5d4842015-04-30 22:58:28 +0000546 Visit(S->getLoopVarStmt());
Justin Bognere4ca4412015-02-23 19:27:00 +0000547 Visit(S->getRangeStmt());
Richard Smith01694c32016-03-20 10:33:40 +0000548 Visit(S->getBeginStmt());
549 Visit(S->getEndStmt());
Justin Bogner07193cc2015-05-01 23:41:09 +0000550
Justin Bognera909abf2015-05-02 00:48:27 +0000551 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000552 BreakContinueStack.push_back(BreakContinue());
553 // Visit the body region first. (This is basically the same as a while
554 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000555 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
556 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000557 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000558 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000559 BreakContinue BC = BreakContinueStack.pop_back_val();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000560
Justin Bognere4ca4412015-02-23 19:27:00 +0000561 // The increment is essentially part of the body but it needs to include
562 // the count for all the continue statements.
Justin Bogner07193cc2015-05-01 23:41:09 +0000563 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
564 CountMap[S->getInc()] = IncCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000565 Visit(S->getInc());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000566
Justin Bognere4ca4412015-02-23 19:27:00 +0000567 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000568 uint64_t CondCount =
569 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
570 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000571 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000572 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000573 RecordNextStmtCount = true;
574 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000575
Justin Bognere4ca4412015-02-23 19:27:00 +0000576 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
577 RecordStmtCount(S);
578 Visit(S->getElement());
Justin Bognera909abf2015-05-02 00:48:27 +0000579 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000580 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000581 // Counter tracks the body of the loop.
582 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
583 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000584 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000585 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000586 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000587
588 setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
589 BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000590 RecordNextStmtCount = true;
591 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000592
Justin Bognere4ca4412015-02-23 19:27:00 +0000593 void VisitSwitchStmt(const SwitchStmt *S) {
594 RecordStmtCount(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +0000595 if (S->getInit())
596 Visit(S->getInit());
Justin Bognere4ca4412015-02-23 19:27:00 +0000597 Visit(S->getCond());
Justin Bognera909abf2015-05-02 00:48:27 +0000598 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000599 BreakContinueStack.push_back(BreakContinue());
600 Visit(S->getBody());
601 // If the switch is inside a loop, add the continue counts.
602 BreakContinue BC = BreakContinueStack.pop_back_val();
603 if (!BreakContinueStack.empty())
604 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
605 // Counter tracks the exit block of the switch.
Justin Bogner07193cc2015-05-01 23:41:09 +0000606 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000607 RecordNextStmtCount = true;
608 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000609
Justin Bogner07193cc2015-05-01 23:41:09 +0000610 void VisitSwitchCase(const SwitchCase *S) {
Justin Bognere4ca4412015-02-23 19:27:00 +0000611 RecordNextStmtCount = false;
612 // Counter for this particular case. This counts only jumps from the
613 // switch header and does not include fallthrough from the case before
614 // this one.
Justin Bogner07193cc2015-05-01 23:41:09 +0000615 uint64_t CaseCount = PGO.getRegionCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000616 setCount(CurrentCount + CaseCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000617 // We need the count without fallthrough in the mapping, so it's more useful
618 // for branch probabilities.
619 CountMap[S] = CaseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000620 RecordNextStmtCount = true;
621 Visit(S->getSubStmt());
622 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000623
Justin Bognere4ca4412015-02-23 19:27:00 +0000624 void VisitIfStmt(const IfStmt *S) {
625 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000626 uint64_t ParentCount = CurrentCount;
Vedant Kumar9d2a16b2016-10-14 23:38:16 +0000627 if (S->getInit())
628 Visit(S->getInit());
Justin Bognere4ca4412015-02-23 19:27:00 +0000629 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000630
Justin Bogner07193cc2015-05-01 23:41:09 +0000631 // Counter tracks the "then" part of an if statement. The count for
632 // the "else" part, if it exists, will be calculated from this counter.
633 uint64_t ThenCount = setCount(PGO.getRegionCount(S));
634 CountMap[S->getThen()] = ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000635 Visit(S->getThen());
Justin Bognera909abf2015-05-02 00:48:27 +0000636 uint64_t OutCount = CurrentCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000637
Justin Bogner07193cc2015-05-01 23:41:09 +0000638 uint64_t ElseCount = ParentCount - ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000639 if (S->getElse()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000640 setCount(ElseCount);
641 CountMap[S->getElse()] = ElseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000642 Visit(S->getElse());
Justin Bognera909abf2015-05-02 00:48:27 +0000643 OutCount += CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000644 } else
645 OutCount += ElseCount;
646 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000647 RecordNextStmtCount = true;
648 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000649
Justin Bognere4ca4412015-02-23 19:27:00 +0000650 void VisitCXXTryStmt(const CXXTryStmt *S) {
651 RecordStmtCount(S);
652 Visit(S->getTryBlock());
653 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
654 Visit(S->getHandler(I));
655 // Counter tracks the continuation block of the try statement.
Justin Bogner07193cc2015-05-01 23:41:09 +0000656 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000657 RecordNextStmtCount = true;
658 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000659
Justin Bognere4ca4412015-02-23 19:27:00 +0000660 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
661 RecordNextStmtCount = false;
662 // Counter tracks the catch statement's handler block.
Justin Bogner07193cc2015-05-01 23:41:09 +0000663 uint64_t CatchCount = setCount(PGO.getRegionCount(S));
664 CountMap[S] = CatchCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000665 Visit(S->getHandlerBlock());
666 }
667
668 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
669 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000670 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000671 Visit(E->getCond());
672
Justin Bogner07193cc2015-05-01 23:41:09 +0000673 // Counter tracks the "true" part of a conditional operator. The
674 // count in the "false" part will be calculated from this counter.
675 uint64_t TrueCount = setCount(PGO.getRegionCount(E));
676 CountMap[E->getTrueExpr()] = TrueCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000677 Visit(E->getTrueExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000678 uint64_t OutCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000679
Justin Bogner07193cc2015-05-01 23:41:09 +0000680 uint64_t FalseCount = setCount(ParentCount - TrueCount);
681 CountMap[E->getFalseExpr()] = FalseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000682 Visit(E->getFalseExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000683 OutCount += CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000684
Justin Bogner07193cc2015-05-01 23:41:09 +0000685 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000686 RecordNextStmtCount = true;
687 }
688
689 void VisitBinLAnd(const BinaryOperator *E) {
690 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000691 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000692 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000693 // Counter tracks the right hand side of a logical and operator.
694 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
695 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000696 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000697 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000698 RecordNextStmtCount = true;
699 }
700
701 void VisitBinLOr(const BinaryOperator *E) {
702 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000703 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000704 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000705 // Counter tracks the right hand side of a logical or operator.
706 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
707 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000708 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000709 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000710 RecordNextStmtCount = true;
711 }
712};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000713} // end anonymous namespace
Justin Bogneref512b92014-01-06 22:27:43 +0000714
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000715void PGOHash::combine(HashType Type) {
716 // Check that we never combine 0 and only have six bits.
717 assert(Type && "Hash is invalid: unexpected type 0");
718 assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
719
720 // Pass through MD5 if enough work has built up.
721 if (Count && Count % NumTypesPerWord == 0) {
722 using namespace llvm::support;
723 uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
724 MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
725 Working = 0;
726 }
727
728 // Accumulate the current type.
729 ++Count;
730 Working = Working << NumBitsPerType | Type;
731}
732
733uint64_t PGOHash::finalize() {
734 // Use Working as the hash directly if we never used MD5.
735 if (Count <= NumTypesPerWord)
736 // No need to byte swap here, since none of the math was endian-dependent.
737 // This number will be byte-swapped as required on endianness transitions,
738 // so we will see the same value on the other side.
739 return Working;
740
741 // Check for remaining work in Working.
742 if (Working)
743 MD5.update(Working);
744
745 // Finalize the MD5 and return the hash.
746 llvm::MD5::MD5Result Result;
747 MD5.final(Result);
748 using namespace llvm::support;
Zachary Turner82a0c972017-03-20 23:33:18 +0000749 return Result.low();
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000750}
751
Serge Pavlov3a561452015-12-06 14:32:39 +0000752void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
753 const Decl *D = GD.getDecl();
Vedant Kumar33d0a1c2017-06-30 21:02:14 +0000754 if (!D->hasBody())
755 return;
756
Rong Xu9837ef52016-02-04 18:39:09 +0000757 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
Justin Bogner837a6f62014-04-18 21:52:00 +0000758 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
759 if (!InstrumentRegions && !PGOReader)
Justin Bogneref512b92014-01-06 22:27:43 +0000760 return;
Justin Bogner3212b182014-04-25 07:20:05 +0000761 if (D->isImplicit())
Justin Bogneref512b92014-01-06 22:27:43 +0000762 return;
Serge Pavlov3a561452015-12-06 14:32:39 +0000763 // Constructors and destructors may be represented by several functions in IR.
764 // If so, instrument only base variant, others are implemented by delegation
765 // to the base one, it would be counted twice otherwise.
Vedant Kumar7f809b22017-02-24 01:15:19 +0000766 if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
767 if (isa<CXXDestructorDecl>(D) && GD.getDtorType() != Dtor_Base)
768 return;
769
770 if (const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
771 if (GD.getCtorType() != Ctor_Base &&
772 CodeGenFunction::IsConstructorDelegationValid(CCD))
773 return;
Serge Pavlov3a561452015-12-06 14:32:39 +0000774 }
Alex Lorenzee024992014-08-04 18:41:51 +0000775 CGM.ClearUnusedCoverageMapping(D);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000776 setFuncName(Fn);
Duncan P. N. Exon Smith7c414512014-03-20 22:50:08 +0000777
Justin Bogneref512b92014-01-06 22:27:43 +0000778 mapRegionCounters(D);
Justin Bogner970ac602014-12-08 19:04:51 +0000779 if (CGM.getCodeGenOpts().CoverageMapping)
780 emitCounterRegionMapping(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000781 if (PGOReader) {
Justin Bogner40b8ba12014-06-26 01:45:07 +0000782 SourceManager &SM = CGM.getContext().getSourceManager();
783 loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000784 computeRegionCounts(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000785 applyFunctionAttributes(PGOReader, Fn);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000786 }
Justin Bogneref512b92014-01-06 22:27:43 +0000787}
788
789void CodeGenPGO::mapRegionCounters(const Decl *D) {
Vedant Kumar61869712017-11-14 23:56:53 +0000790 // Use the latest hash version when inserting instrumentation, but use the
791 // version in the indexed profile if we're reading PGO data.
792 PGOHashVersion HashVersion = PGO_HASH_LATEST;
793 if (auto *PGOReader = CGM.getPGOReader())
794 HashVersion = getPGOHashVersion(PGOReader, CGM);
795
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000796 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
Vedant Kumar61869712017-11-14 23:56:53 +0000797 MapRegionCounters Walker(HashVersion, *RegionCounterMap);
Justin Bogneref512b92014-01-06 22:27:43 +0000798 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000799 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000800 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000801 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
Bob Wilsonc845c002014-03-06 20:24:27 +0000802 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000803 Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
Justin Bogner81ab90f2014-04-15 00:50:54 +0000804 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
805 Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
Justin Bogner3212b182014-04-25 07:20:05 +0000806 assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
Justin Bogneref512b92014-01-06 22:27:43 +0000807 NumRegionCounters = Walker.NextCounter;
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000808 FunctionHash = Walker.Hash.finalize();
Justin Bogneref512b92014-01-06 22:27:43 +0000809}
810
Vedant Kumarc468bb82016-07-11 22:57:44 +0000811bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
Vedant Kumarbc370f02017-04-24 20:52:04 +0000812 if (!D->getBody())
813 return true;
814
Vedant Kumarc468bb82016-07-11 22:57:44 +0000815 // Don't map the functions in system headers.
816 const auto &SM = CGM.getContext().getSourceManager();
Alex Lorenzee024992014-08-04 18:41:51 +0000817 auto Loc = D->getBody()->getLocStart();
Vedant Kumarc468bb82016-07-11 22:57:44 +0000818 return SM.isInSystemHeader(Loc);
819}
820
821void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
822 if (skipRegionMappingForDecl(D))
Alex Lorenzee024992014-08-04 18:41:51 +0000823 return;
824
Justin Bogner970ac602014-12-08 19:04:51 +0000825 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000826 llvm::raw_string_ostream OS(CoverageMapping);
827 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
828 CGM.getContext().getSourceManager(),
Justin Bognere5ee6c52014-10-02 16:44:01 +0000829 CGM.getLangOpts(), RegionCounterMap.get());
Alex Lorenzee024992014-08-04 18:41:51 +0000830 MappingGen.emitCounterMapping(D, OS);
831 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000832
833 if (CoverageMapping.empty())
834 return;
835
836 CGM.getCoverageMapping()->addFunctionMappingRecord(
837 FuncNameVar, FuncName, FunctionHash, CoverageMapping);
Alex Lorenzee024992014-08-04 18:41:51 +0000838}
839
840void
Justin Bogner60d852b2015-04-23 00:31:16 +0000841CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
Alex Lorenzee024992014-08-04 18:41:51 +0000842 llvm::GlobalValue::LinkageTypes Linkage) {
Vedant Kumarc468bb82016-07-11 22:57:44 +0000843 if (skipRegionMappingForDecl(D))
Alex Lorenzee024992014-08-04 18:41:51 +0000844 return;
845
Justin Bogner970ac602014-12-08 19:04:51 +0000846 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000847 llvm::raw_string_ostream OS(CoverageMapping);
848 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
849 CGM.getContext().getSourceManager(),
850 CGM.getLangOpts());
851 MappingGen.emitEmptyMapping(D, OS);
852 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000853
854 if (CoverageMapping.empty())
855 return;
856
Justin Bogner60d852b2015-04-23 00:31:16 +0000857 setFuncName(Name, Linkage);
Justin Bogner970ac602014-12-08 19:04:51 +0000858 CGM.getCoverageMapping()->addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +0000859 FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
Alex Lorenzee024992014-08-04 18:41:51 +0000860}
861
Bob Wilsonbf854f02014-02-17 19:21:09 +0000862void CodeGenPGO::computeRegionCounts(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000863 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000864 ComputeRegionCounts Walker(*StmtCountMap, *this);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000865 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
866 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000867 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
868 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000869 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
870 Walker.VisitBlockDecl(BD);
Justin Bogner81ab90f2014-04-15 00:50:54 +0000871 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
872 Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000873}
874
Justin Bogner837a6f62014-04-18 21:52:00 +0000875void
876CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
877 llvm::Function *Fn) {
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000878 if (!haveRegionCounts())
879 return;
880
Hans Wennborgdcfba332015-10-06 23:40:43 +0000881 uint64_t FunctionCount = getRegionCount(nullptr);
Diego Novilloaa8b1cb2015-05-27 21:58:42 +0000882 Fn->setEntryCount(FunctionCount);
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000883}
884
Vedant Kumar502bbfa2017-02-25 06:35:45 +0000885void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S,
886 llvm::Value *StepV) {
Rong Xu9837ef52016-02-04 18:39:09 +0000887 if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap)
Justin Bogneref512b92014-01-06 22:27:43 +0000888 return;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000889 if (!Builder.GetInsertBlock())
Justin Bogner203f91e2015-01-09 01:46:40 +0000890 return;
Justin Bogner66242d62015-04-23 23:06:47 +0000891
892 unsigned Counter = (*RegionCounterMap)[S];
Justin Bogner970ac602014-12-08 19:04:51 +0000893 auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Vedant Kumar502bbfa2017-02-25 06:35:45 +0000894
895 llvm::Value *Args[] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
896 Builder.getInt64(FunctionHash),
897 Builder.getInt32(NumRegionCounters),
898 Builder.getInt32(Counter), StepV};
899 if (!StepV)
900 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
901 makeArrayRef(Args, 4));
902 else
903 Builder.CreateCall(
904 CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step),
905 makeArrayRef(Args));
Justin Bogneref512b92014-01-06 22:27:43 +0000906}
907
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000908// This method either inserts a call to the profile run-time during
909// instrumentation or puts profile data into metadata for PGO use.
910void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
911 llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
912
913 if (!EnableValueProfiling)
914 return;
915
916 if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
917 return;
918
Betul Buyukkurt3da993c2016-03-31 18:41:34 +0000919 if (isa<llvm::Constant>(ValuePtr))
920 return;
921
Rong Xu9837ef52016-02-04 18:39:09 +0000922 bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000923 if (InstrumentValueSites && RegionCounterMap) {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000924 auto BuilderInsertPoint = Builder.saveIP();
925 Builder.SetInsertPoint(ValueSite);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000926 llvm::Value *Args[5] = {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000927 llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()),
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000928 Builder.getInt64(FunctionHash),
929 Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
930 Builder.getInt32(ValueKind),
931 Builder.getInt32(NumValueSites[ValueKind]++)
932 };
933 Builder.CreateCall(
934 CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000935 Builder.restoreIP(BuilderInsertPoint);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000936 return;
937 }
938
939 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
940 if (PGOReader && haveRegionCounts()) {
941 // We record the top most called three functions at each call site.
942 // Profile metadata contains "VP" string identifying this metadata
943 // as value profiling data, then a uint32_t value for the value profiling
944 // kind, a uint64_t value for the total number of times the call is
945 // executed, followed by the function hash and execution count (uint64_t)
946 // pairs for each function.
947 if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
948 return;
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000949
Xinliang David Li5527a9d2016-02-04 19:54:17 +0000950 llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
951 (llvm::InstrProfValueKind)ValueKind,
952 NumValueSites[ValueKind]);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000953
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000954 NumValueSites[ValueKind]++;
955 }
956}
957
Justin Bogner40b8ba12014-06-26 01:45:07 +0000958void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
959 bool IsInMainFile) {
960 CGM.getPGOStats().addVisited(IsInMainFile);
Justin Bogner7f8cf5b2014-12-02 22:38:52 +0000961 RegionCounts.clear();
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000962 llvm::Expected<llvm::InstrProfRecord> RecordExpected =
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000963 PGOReader->getInstrProfRecord(FuncName, FunctionHash);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000964 if (auto E = RecordExpected.takeError()) {
965 auto IPE = llvm::InstrProfError::take(std::move(E));
966 if (IPE == llvm::instrprof_error::unknown_function)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000967 CGM.getPGOStats().addMissing(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000968 else if (IPE == llvm::instrprof_error::hash_mismatch)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000969 CGM.getPGOStats().addMismatched(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000970 else if (IPE == llvm::instrprof_error::malformed)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000971 // TODO: Consider a more specific warning for this case.
972 CGM.getPGOStats().addMismatched(IsInMainFile);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000973 return;
Justin Bognere2ef2a02014-04-15 21:22:35 +0000974 }
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000975 ProfRecord =
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000976 llvm::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000977 RegionCounts = ProfRecord->Counts;
Justin Bogneref512b92014-01-06 22:27:43 +0000978}
979
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000980/// \brief Calculate what to divide by to scale weights.
981///
982/// Given the maximum weight, calculate a divisor that will scale all the
983/// weights to strictly less than UINT32_MAX.
984static uint64_t calculateWeightScale(uint64_t MaxWeight) {
985 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
986}
987
988/// \brief Scale an individual branch weight (and add 1).
989///
990/// Scale a 64-bit weight down to 32-bits using \c Scale.
991///
992/// According to Laplace's Rule of Succession, it is better to compute the
993/// weight based on the count plus 1, so universally add 1 to the value.
994///
995/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
996/// greater than \c Weight.
997static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
998 assert(Scale && "scale by 0?");
999 uint64_t Scaled = Weight / Scale + 1;
1000 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
1001 return Scaled;
1002}
1003
Justin Bogner65512642015-05-02 05:00:55 +00001004llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
1005 uint64_t FalseCount) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001006 // Check for empty weights.
Justin Bogneref512b92014-01-06 22:27:43 +00001007 if (!TrueCount && !FalseCount)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001008 return nullptr;
Justin Bogneref512b92014-01-06 22:27:43 +00001009
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001010 // Calculate how to scale down to 32-bits.
1011 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
1012
Justin Bogneref512b92014-01-06 22:27:43 +00001013 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001014 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
1015 scaleBranchWeight(FalseCount, Scale));
Justin Bogneref512b92014-01-06 22:27:43 +00001016}
1017
Justin Bogner65512642015-05-02 05:00:55 +00001018llvm::MDNode *
1019CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001020 // We need at least two elements to create meaningful weights.
1021 if (Weights.size() < 2)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001022 return nullptr;
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001023
Justin Bognerf3aefca2014-04-04 02:48:51 +00001024 // Check for empty weights.
1025 uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
1026 if (MaxWeight == 0)
1027 return nullptr;
1028
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001029 // Calculate how to scale down to 32-bits.
Justin Bognerf3aefca2014-04-04 02:48:51 +00001030 uint64_t Scale = calculateWeightScale(MaxWeight);
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001031
Justin Bogneref512b92014-01-06 22:27:43 +00001032 SmallVector<uint32_t, 16> ScaledWeights;
1033 ScaledWeights.reserve(Weights.size());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001034 for (uint64_t W : Weights)
1035 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
1036
1037 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Justin Bogneref512b92014-01-06 22:27:43 +00001038 return MDHelper.createBranchWeights(ScaledWeights);
1039}
Bob Wilsonbf854f02014-02-17 19:21:09 +00001040
Justin Bogner65512642015-05-02 05:00:55 +00001041llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
1042 uint64_t LoopCount) {
1043 if (!PGO.haveRegionCounts())
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001044 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +00001045 Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
Justin Bogner1c21c282015-04-13 12:23:19 +00001046 assert(CondCount.hasValue() && "missing expected loop condition count");
1047 if (*CondCount == 0)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001048 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +00001049 return createProfileWeights(LoopCount,
1050 std::max(*CondCount, LoopCount) - LoopCount);
Bob Wilsonbf854f02014-02-17 19:21:09 +00001051}