blob: c6c3fa41e62818831e30a083906f45073568cd35 [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
Justin Bogneref512b92014-01-06 22:27:43 +000050namespace {
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +000051/// \brief Stable hasher for PGO region counters.
52///
53/// PGOHash produces a stable hash of a given function's control flow.
54///
55/// Changing the output of this hash will invalidate all previously generated
56/// profiles -- i.e., don't do it.
57///
58/// \note When this hash does eventually change (years?), we still need to
59/// support old hashes. We'll need to pull in the version number from the
60/// profile data format and use the matching hash function.
61class PGOHash {
62 uint64_t Working;
63 unsigned Count;
64 llvm::MD5 MD5;
65
66 static const int NumBitsPerType = 6;
67 static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
68 static const unsigned TooBig = 1u << NumBitsPerType;
69
70public:
71 /// \brief Hash values for AST nodes.
72 ///
73 /// Distinct values for AST nodes that have region counters attached.
74 ///
75 /// These values must be stable. All new members must be added at the end,
76 /// and no members should be removed. Changing the enumeration value for an
77 /// AST node will affect the hash of every function that contains that node.
78 enum HashType : unsigned char {
79 None = 0,
80 LabelStmt = 1,
81 WhileStmt,
82 DoStmt,
83 ForStmt,
84 CXXForRangeStmt,
85 ObjCForCollectionStmt,
86 SwitchStmt,
87 CaseStmt,
88 DefaultStmt,
89 IfStmt,
90 CXXTryStmt,
91 CXXCatchStmt,
92 ConditionalOperator,
93 BinaryOperatorLAnd,
94 BinaryOperatorLOr,
95 BinaryConditionalOperator,
96
97 // Keep this last. It's for the static assert that follows.
98 LastHashType
99 };
100 static_assert(LastHashType <= TooBig, "Too many types in HashType");
101
102 // TODO: When this format changes, take in a version number here, and use the
103 // old hash calculation for file formats that used the old hash.
104 PGOHash() : Working(0), Count(0) {}
105 void combine(HashType Type);
106 uint64_t finalize();
107};
108const int PGOHash::NumBitsPerType;
109const unsigned PGOHash::NumTypesPerWord;
110const unsigned PGOHash::TooBig;
111
Justin Bognere4ca4412015-02-23 19:27:00 +0000112/// A RecursiveASTVisitor that fills a map of statements to PGO counters.
113struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
114 /// The next counter value to assign.
115 unsigned NextCounter;
116 /// The function hash.
117 PGOHash Hash;
118 /// The map of statements to counters.
119 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
Justin Bogneref512b92014-01-06 22:27:43 +0000120
Justin Bognere4ca4412015-02-23 19:27:00 +0000121 MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
122 : NextCounter(0), CounterMap(CounterMap) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000123
Justin Bognere4ca4412015-02-23 19:27:00 +0000124 // Blocks and lambdas are handled as separate functions, so we need not
125 // traverse them in the parent context.
126 bool TraverseBlockExpr(BlockExpr *BE) { return true; }
127 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
128 bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
Justin Bogneref512b92014-01-06 22:27:43 +0000129
Justin Bognere4ca4412015-02-23 19:27:00 +0000130 bool VisitDecl(const Decl *D) {
131 switch (D->getKind()) {
132 default:
133 break;
134 case Decl::Function:
135 case Decl::CXXMethod:
136 case Decl::CXXConstructor:
137 case Decl::CXXDestructor:
138 case Decl::CXXConversion:
139 case Decl::ObjCMethod:
140 case Decl::Block:
141 case Decl::Captured:
142 CounterMap[D->getBody()] = NextCounter++;
143 break;
144 }
145 return true;
146 }
147
148 bool VisitStmt(const Stmt *S) {
149 auto Type = getHashType(S);
150 if (Type == PGOHash::None)
Bob Wilsond8931422014-04-11 17:16:13 +0000151 return true;
Bob Wilsond8931422014-04-11 17:16:13 +0000152
Justin Bognere4ca4412015-02-23 19:27:00 +0000153 CounterMap[S] = NextCounter++;
154 Hash.combine(Type);
155 return true;
156 }
157 PGOHash::HashType getHashType(const Stmt *S) {
158 switch (S->getStmtClass()) {
159 default:
160 break;
161 case Stmt::LabelStmtClass:
162 return PGOHash::LabelStmt;
163 case Stmt::WhileStmtClass:
164 return PGOHash::WhileStmt;
165 case Stmt::DoStmtClass:
166 return PGOHash::DoStmt;
167 case Stmt::ForStmtClass:
168 return PGOHash::ForStmt;
169 case Stmt::CXXForRangeStmtClass:
170 return PGOHash::CXXForRangeStmt;
171 case Stmt::ObjCForCollectionStmtClass:
172 return PGOHash::ObjCForCollectionStmt;
173 case Stmt::SwitchStmtClass:
174 return PGOHash::SwitchStmt;
175 case Stmt::CaseStmtClass:
176 return PGOHash::CaseStmt;
177 case Stmt::DefaultStmtClass:
178 return PGOHash::DefaultStmt;
179 case Stmt::IfStmtClass:
180 return PGOHash::IfStmt;
181 case Stmt::CXXTryStmtClass:
182 return PGOHash::CXXTryStmt;
183 case Stmt::CXXCatchStmtClass:
184 return PGOHash::CXXCatchStmt;
185 case Stmt::ConditionalOperatorClass:
186 return PGOHash::ConditionalOperator;
187 case Stmt::BinaryConditionalOperatorClass:
188 return PGOHash::BinaryConditionalOperator;
189 case Stmt::BinaryOperatorClass: {
190 const BinaryOperator *BO = cast<BinaryOperator>(S);
191 if (BO->getOpcode() == BO_LAnd)
192 return PGOHash::BinaryOperatorLAnd;
193 if (BO->getOpcode() == BO_LOr)
194 return PGOHash::BinaryOperatorLOr;
195 break;
196 }
197 }
198 return PGOHash::None;
199 }
200};
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000201
Justin Bognere4ca4412015-02-23 19:27:00 +0000202/// A StmtVisitor that propagates the raw counts through the AST and
203/// records the count at statements where the value may change.
204struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
205 /// PGO state.
206 CodeGenPGO &PGO;
207
208 /// A flag that is set when the current count should be recorded on the
209 /// next statement, such as at the exit of a loop.
210 bool RecordNextStmtCount;
211
Justin Bognera909abf2015-05-02 00:48:27 +0000212 /// The count at the current location in the traversal.
213 uint64_t CurrentCount;
214
Justin Bognere4ca4412015-02-23 19:27:00 +0000215 /// The map of statements to count values.
216 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
217
218 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
219 struct BreakContinue {
220 uint64_t BreakCount;
221 uint64_t ContinueCount;
222 BreakContinue() : BreakCount(0), ContinueCount(0) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000223 };
Justin Bognere4ca4412015-02-23 19:27:00 +0000224 SmallVector<BreakContinue, 8> BreakContinueStack;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000225
Justin Bognere4ca4412015-02-23 19:27:00 +0000226 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
227 CodeGenPGO &PGO)
228 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000229
Justin Bognere4ca4412015-02-23 19:27:00 +0000230 void RecordStmtCount(const Stmt *S) {
231 if (RecordNextStmtCount) {
Justin Bognera909abf2015-05-02 00:48:27 +0000232 CountMap[S] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000233 RecordNextStmtCount = false;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000234 }
Justin Bognere4ca4412015-02-23 19:27:00 +0000235 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000236
Justin Bogner07193cc2015-05-01 23:41:09 +0000237 /// Set and return the current count.
238 uint64_t setCount(uint64_t Count) {
Justin Bognera909abf2015-05-02 00:48:27 +0000239 CurrentCount = Count;
Justin Bogner07193cc2015-05-01 23:41:09 +0000240 return Count;
241 }
242
Justin Bognere4ca4412015-02-23 19:27:00 +0000243 void VisitStmt(const Stmt *S) {
244 RecordStmtCount(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000245 for (const Stmt *Child : S->children())
246 if (Child)
247 this->Visit(Child);
Justin Bognere4ca4412015-02-23 19:27:00 +0000248 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000249
Justin Bognere4ca4412015-02-23 19:27:00 +0000250 void VisitFunctionDecl(const FunctionDecl *D) {
251 // Counter tracks entry to the function body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000252 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
253 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000254 Visit(D->getBody());
255 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000256
Justin Bognere4ca4412015-02-23 19:27:00 +0000257 // Skip lambda expressions. We visit these as FunctionDecls when we're
258 // generating them and aren't interested in the body when generating a
259 // parent context.
260 void VisitLambdaExpr(const LambdaExpr *LE) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000261
Justin Bognere4ca4412015-02-23 19:27:00 +0000262 void VisitCapturedDecl(const CapturedDecl *D) {
263 // Counter tracks entry to the capture body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000264 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
265 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000266 Visit(D->getBody());
267 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000268
Justin Bognere4ca4412015-02-23 19:27:00 +0000269 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
270 // Counter tracks entry to the method body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000271 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
272 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000273 Visit(D->getBody());
274 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000275
Justin Bognere4ca4412015-02-23 19:27:00 +0000276 void VisitBlockDecl(const BlockDecl *D) {
277 // Counter tracks entry to the block body.
Justin Bogner07193cc2015-05-01 23:41:09 +0000278 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
279 CountMap[D->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000280 Visit(D->getBody());
281 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000282
Justin Bognere4ca4412015-02-23 19:27:00 +0000283 void VisitReturnStmt(const ReturnStmt *S) {
284 RecordStmtCount(S);
285 if (S->getRetValue())
286 Visit(S->getRetValue());
Justin Bognera909abf2015-05-02 00:48:27 +0000287 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000288 RecordNextStmtCount = true;
289 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000290
Justin Bognerf959feb2015-04-28 06:31:55 +0000291 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
292 RecordStmtCount(E);
293 if (E->getSubExpr())
294 Visit(E->getSubExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000295 CurrentCount = 0;
Justin Bognerf959feb2015-04-28 06:31:55 +0000296 RecordNextStmtCount = true;
297 }
298
Justin Bognere4ca4412015-02-23 19:27:00 +0000299 void VisitGotoStmt(const GotoStmt *S) {
300 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000301 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000302 RecordNextStmtCount = true;
303 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000304
Justin Bognere4ca4412015-02-23 19:27:00 +0000305 void VisitLabelStmt(const LabelStmt *S) {
306 RecordNextStmtCount = false;
307 // Counter tracks the block following the label.
Justin Bogner07193cc2015-05-01 23:41:09 +0000308 uint64_t BlockCount = setCount(PGO.getRegionCount(S));
309 CountMap[S] = BlockCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000310 Visit(S->getSubStmt());
311 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000312
Justin Bognere4ca4412015-02-23 19:27:00 +0000313 void VisitBreakStmt(const BreakStmt *S) {
314 RecordStmtCount(S);
315 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
Justin Bognera909abf2015-05-02 00:48:27 +0000316 BreakContinueStack.back().BreakCount += CurrentCount;
317 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000318 RecordNextStmtCount = true;
319 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000320
Justin Bognere4ca4412015-02-23 19:27:00 +0000321 void VisitContinueStmt(const ContinueStmt *S) {
322 RecordStmtCount(S);
323 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
Justin Bognera909abf2015-05-02 00:48:27 +0000324 BreakContinueStack.back().ContinueCount += CurrentCount;
325 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000326 RecordNextStmtCount = true;
327 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000328
Justin Bognere4ca4412015-02-23 19:27:00 +0000329 void VisitWhileStmt(const WhileStmt *S) {
330 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000331 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000332
Justin Bognere4ca4412015-02-23 19:27:00 +0000333 BreakContinueStack.push_back(BreakContinue());
334 // Visit the body region first so the break/continue adjustments can be
335 // included when visiting the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000336 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
Justin Bognera909abf2015-05-02 00:48:27 +0000337 CountMap[S->getBody()] = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000338 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000339 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000340
341 // ...then go back and propagate counts through the condition. The count
342 // at the start of the condition is the sum of the incoming edges,
343 // the backedge from the end of the loop body, and the edges from
344 // continue statements.
345 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000346 uint64_t CondCount =
347 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
348 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000349 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000350 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000351 RecordNextStmtCount = true;
352 }
353
354 void VisitDoStmt(const DoStmt *S) {
355 RecordStmtCount(S);
Justin Bogner07193cc2015-05-01 23:41:09 +0000356 uint64_t LoopCount = PGO.getRegionCount(S);
357
Justin Bognere4ca4412015-02-23 19:27:00 +0000358 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000359 // The count doesn't include the fallthrough from the parent scope. Add it.
Justin Bognera909abf2015-05-02 00:48:27 +0000360 uint64_t BodyCount = setCount(LoopCount + CurrentCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000361 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000362 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000363 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000364
365 BreakContinue BC = BreakContinueStack.pop_back_val();
366 // The count at the start of the condition is equal to the count at the
Justin Bogner07193cc2015-05-01 23:41:09 +0000367 // end of the body, plus any continues.
368 uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
369 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000370 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000371 setCount(BC.BreakCount + CondCount - LoopCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000372 RecordNextStmtCount = true;
373 }
374
375 void VisitForStmt(const ForStmt *S) {
376 RecordStmtCount(S);
377 if (S->getInit())
378 Visit(S->getInit());
Justin Bogner07193cc2015-05-01 23:41:09 +0000379
Justin Bognera909abf2015-05-02 00:48:27 +0000380 uint64_t ParentCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000381
Justin Bognere4ca4412015-02-23 19:27:00 +0000382 BreakContinueStack.push_back(BreakContinue());
383 // Visit the body region first. (This is basically the same as a while
384 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000385 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
386 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000387 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000388 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000389 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognere4ca4412015-02-23 19:27:00 +0000390
391 // The increment is essentially part of the body but it needs to include
392 // the count for all the continue statements.
393 if (S->getInc()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000394 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
395 CountMap[S->getInc()] = IncCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000396 Visit(S->getInc());
Justin Bognere4ca4412015-02-23 19:27:00 +0000397 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000398
Justin Bognere4ca4412015-02-23 19:27:00 +0000399 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000400 uint64_t CondCount =
401 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000402 if (S->getCond()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000403 CountMap[S->getCond()] = CondCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000404 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000405 }
Justin Bogner07193cc2015-05-01 23:41:09 +0000406 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000407 RecordNextStmtCount = true;
408 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000409
Justin Bognere4ca4412015-02-23 19:27:00 +0000410 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
411 RecordStmtCount(S);
Justin Bogner2e5d4842015-04-30 22:58:28 +0000412 Visit(S->getLoopVarStmt());
Justin Bognere4ca4412015-02-23 19:27:00 +0000413 Visit(S->getRangeStmt());
Richard Smith01694c32016-03-20 10:33:40 +0000414 Visit(S->getBeginStmt());
415 Visit(S->getEndStmt());
Justin Bogner07193cc2015-05-01 23:41:09 +0000416
Justin Bognera909abf2015-05-02 00:48:27 +0000417 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000418 BreakContinueStack.push_back(BreakContinue());
419 // Visit the body region first. (This is basically the same as a while
420 // loop; see further comments in VisitWhileStmt.)
Justin Bogner07193cc2015-05-01 23:41:09 +0000421 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
422 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000423 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000424 uint64_t BackedgeCount = CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000425 BreakContinue BC = BreakContinueStack.pop_back_val();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000426
Justin Bognere4ca4412015-02-23 19:27:00 +0000427 // The increment is essentially part of the body but it needs to include
428 // the count for all the continue statements.
Justin Bogner07193cc2015-05-01 23:41:09 +0000429 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
430 CountMap[S->getInc()] = IncCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000431 Visit(S->getInc());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000432
Justin Bognere4ca4412015-02-23 19:27:00 +0000433 // ...then go back and propagate counts through the condition.
Justin Bogner07193cc2015-05-01 23:41:09 +0000434 uint64_t CondCount =
435 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
436 CountMap[S->getCond()] = CondCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000437 Visit(S->getCond());
Justin Bogner07193cc2015-05-01 23:41:09 +0000438 setCount(BC.BreakCount + CondCount - BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000439 RecordNextStmtCount = true;
440 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000441
Justin Bognere4ca4412015-02-23 19:27:00 +0000442 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
443 RecordStmtCount(S);
444 Visit(S->getElement());
Justin Bognera909abf2015-05-02 00:48:27 +0000445 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000446 BreakContinueStack.push_back(BreakContinue());
Justin Bogner07193cc2015-05-01 23:41:09 +0000447 // Counter tracks the body of the loop.
448 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
449 CountMap[S->getBody()] = BodyCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000450 Visit(S->getBody());
Justin Bognera909abf2015-05-02 00:48:27 +0000451 uint64_t BackedgeCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000452 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bogner07193cc2015-05-01 23:41:09 +0000453
454 setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
455 BodyCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000456 RecordNextStmtCount = true;
457 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000458
Justin Bognere4ca4412015-02-23 19:27:00 +0000459 void VisitSwitchStmt(const SwitchStmt *S) {
460 RecordStmtCount(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +0000461 if (S->getInit())
462 Visit(S->getInit());
Justin Bognere4ca4412015-02-23 19:27:00 +0000463 Visit(S->getCond());
Justin Bognera909abf2015-05-02 00:48:27 +0000464 CurrentCount = 0;
Justin Bognere4ca4412015-02-23 19:27:00 +0000465 BreakContinueStack.push_back(BreakContinue());
466 Visit(S->getBody());
467 // If the switch is inside a loop, add the continue counts.
468 BreakContinue BC = BreakContinueStack.pop_back_val();
469 if (!BreakContinueStack.empty())
470 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
471 // Counter tracks the exit block of the switch.
Justin Bogner07193cc2015-05-01 23:41:09 +0000472 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000473 RecordNextStmtCount = true;
474 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000475
Justin Bogner07193cc2015-05-01 23:41:09 +0000476 void VisitSwitchCase(const SwitchCase *S) {
Justin Bognere4ca4412015-02-23 19:27:00 +0000477 RecordNextStmtCount = false;
478 // Counter for this particular case. This counts only jumps from the
479 // switch header and does not include fallthrough from the case before
480 // this one.
Justin Bogner07193cc2015-05-01 23:41:09 +0000481 uint64_t CaseCount = PGO.getRegionCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000482 setCount(CurrentCount + CaseCount);
Justin Bogner07193cc2015-05-01 23:41:09 +0000483 // We need the count without fallthrough in the mapping, so it's more useful
484 // for branch probabilities.
485 CountMap[S] = CaseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000486 RecordNextStmtCount = true;
487 Visit(S->getSubStmt());
488 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000489
Justin Bognere4ca4412015-02-23 19:27:00 +0000490 void VisitIfStmt(const IfStmt *S) {
491 RecordStmtCount(S);
Justin Bognera909abf2015-05-02 00:48:27 +0000492 uint64_t ParentCount = CurrentCount;
Vedant Kumar9d2a16b2016-10-14 23:38:16 +0000493 if (S->getInit())
494 Visit(S->getInit());
Justin Bognere4ca4412015-02-23 19:27:00 +0000495 Visit(S->getCond());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000496
Justin Bogner07193cc2015-05-01 23:41:09 +0000497 // Counter tracks the "then" part of an if statement. The count for
498 // the "else" part, if it exists, will be calculated from this counter.
499 uint64_t ThenCount = setCount(PGO.getRegionCount(S));
500 CountMap[S->getThen()] = ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000501 Visit(S->getThen());
Justin Bognera909abf2015-05-02 00:48:27 +0000502 uint64_t OutCount = CurrentCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000503
Justin Bogner07193cc2015-05-01 23:41:09 +0000504 uint64_t ElseCount = ParentCount - ThenCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000505 if (S->getElse()) {
Justin Bogner07193cc2015-05-01 23:41:09 +0000506 setCount(ElseCount);
507 CountMap[S->getElse()] = ElseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000508 Visit(S->getElse());
Justin Bognera909abf2015-05-02 00:48:27 +0000509 OutCount += CurrentCount;
Justin Bogner07193cc2015-05-01 23:41:09 +0000510 } else
511 OutCount += ElseCount;
512 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000513 RecordNextStmtCount = true;
514 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000515
Justin Bognere4ca4412015-02-23 19:27:00 +0000516 void VisitCXXTryStmt(const CXXTryStmt *S) {
517 RecordStmtCount(S);
518 Visit(S->getTryBlock());
519 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
520 Visit(S->getHandler(I));
521 // Counter tracks the continuation block of the try statement.
Justin Bogner07193cc2015-05-01 23:41:09 +0000522 setCount(PGO.getRegionCount(S));
Justin Bognere4ca4412015-02-23 19:27:00 +0000523 RecordNextStmtCount = true;
524 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000525
Justin Bognere4ca4412015-02-23 19:27:00 +0000526 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
527 RecordNextStmtCount = false;
528 // Counter tracks the catch statement's handler block.
Justin Bogner07193cc2015-05-01 23:41:09 +0000529 uint64_t CatchCount = setCount(PGO.getRegionCount(S));
530 CountMap[S] = CatchCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000531 Visit(S->getHandlerBlock());
532 }
533
534 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
535 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000536 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000537 Visit(E->getCond());
538
Justin Bogner07193cc2015-05-01 23:41:09 +0000539 // Counter tracks the "true" part of a conditional operator. The
540 // count in the "false" part will be calculated from this counter.
541 uint64_t TrueCount = setCount(PGO.getRegionCount(E));
542 CountMap[E->getTrueExpr()] = TrueCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000543 Visit(E->getTrueExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000544 uint64_t OutCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000545
Justin Bogner07193cc2015-05-01 23:41:09 +0000546 uint64_t FalseCount = setCount(ParentCount - TrueCount);
547 CountMap[E->getFalseExpr()] = FalseCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000548 Visit(E->getFalseExpr());
Justin Bognera909abf2015-05-02 00:48:27 +0000549 OutCount += CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000550
Justin Bogner07193cc2015-05-01 23:41:09 +0000551 setCount(OutCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000552 RecordNextStmtCount = true;
553 }
554
555 void VisitBinLAnd(const BinaryOperator *E) {
556 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000557 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000558 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000559 // Counter tracks the right hand side of a logical and operator.
560 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
561 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000562 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000563 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000564 RecordNextStmtCount = true;
565 }
566
567 void VisitBinLOr(const BinaryOperator *E) {
568 RecordStmtCount(E);
Justin Bognera909abf2015-05-02 00:48:27 +0000569 uint64_t ParentCount = CurrentCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000570 Visit(E->getLHS());
Justin Bogner07193cc2015-05-01 23:41:09 +0000571 // Counter tracks the right hand side of a logical or operator.
572 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
573 CountMap[E->getRHS()] = RHSCount;
Justin Bognere4ca4412015-02-23 19:27:00 +0000574 Visit(E->getRHS());
Justin Bognera909abf2015-05-02 00:48:27 +0000575 setCount(ParentCount + RHSCount - CurrentCount);
Justin Bognere4ca4412015-02-23 19:27:00 +0000576 RecordNextStmtCount = true;
577 }
578};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000579} // end anonymous namespace
Justin Bogneref512b92014-01-06 22:27:43 +0000580
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000581void PGOHash::combine(HashType Type) {
582 // Check that we never combine 0 and only have six bits.
583 assert(Type && "Hash is invalid: unexpected type 0");
584 assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
585
586 // Pass through MD5 if enough work has built up.
587 if (Count && Count % NumTypesPerWord == 0) {
588 using namespace llvm::support;
589 uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
590 MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
591 Working = 0;
592 }
593
594 // Accumulate the current type.
595 ++Count;
596 Working = Working << NumBitsPerType | Type;
597}
598
599uint64_t PGOHash::finalize() {
600 // Use Working as the hash directly if we never used MD5.
601 if (Count <= NumTypesPerWord)
602 // No need to byte swap here, since none of the math was endian-dependent.
603 // This number will be byte-swapped as required on endianness transitions,
604 // so we will see the same value on the other side.
605 return Working;
606
607 // Check for remaining work in Working.
608 if (Working)
609 MD5.update(Working);
610
611 // Finalize the MD5 and return the hash.
612 llvm::MD5::MD5Result Result;
613 MD5.final(Result);
614 using namespace llvm::support;
615 return endian::read<uint64_t, little, unaligned>(Result);
616}
617
Serge Pavlov3a561452015-12-06 14:32:39 +0000618void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
619 const Decl *D = GD.getDecl();
Rong Xu9837ef52016-02-04 18:39:09 +0000620 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
Justin Bogner837a6f62014-04-18 21:52:00 +0000621 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
622 if (!InstrumentRegions && !PGOReader)
Justin Bogneref512b92014-01-06 22:27:43 +0000623 return;
Justin Bogner3212b182014-04-25 07:20:05 +0000624 if (D->isImplicit())
Justin Bogneref512b92014-01-06 22:27:43 +0000625 return;
Serge Pavlov3a561452015-12-06 14:32:39 +0000626 // Constructors and destructors may be represented by several functions in IR.
627 // If so, instrument only base variant, others are implemented by delegation
628 // to the base one, it would be counted twice otherwise.
629 if (CGM.getTarget().getCXXABI().hasConstructorVariants() &&
630 ((isa<CXXConstructorDecl>(GD.getDecl()) &&
631 GD.getCtorType() != Ctor_Base) ||
632 (isa<CXXDestructorDecl>(GD.getDecl()) &&
633 GD.getDtorType() != Dtor_Base))) {
634 return;
635 }
Alex Lorenzee024992014-08-04 18:41:51 +0000636 CGM.ClearUnusedCoverageMapping(D);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000637 setFuncName(Fn);
Duncan P. N. Exon Smith7c414512014-03-20 22:50:08 +0000638
Justin Bogneref512b92014-01-06 22:27:43 +0000639 mapRegionCounters(D);
Justin Bogner970ac602014-12-08 19:04:51 +0000640 if (CGM.getCodeGenOpts().CoverageMapping)
641 emitCounterRegionMapping(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000642 if (PGOReader) {
Justin Bogner40b8ba12014-06-26 01:45:07 +0000643 SourceManager &SM = CGM.getContext().getSourceManager();
644 loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000645 computeRegionCounts(D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000646 applyFunctionAttributes(PGOReader, Fn);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000647 }
Justin Bogneref512b92014-01-06 22:27:43 +0000648}
649
650void CodeGenPGO::mapRegionCounters(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000651 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000652 MapRegionCounters Walker(*RegionCounterMap);
Justin Bogneref512b92014-01-06 22:27:43 +0000653 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000654 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000655 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000656 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
Bob Wilsonc845c002014-03-06 20:24:27 +0000657 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000658 Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
Justin Bogner81ab90f2014-04-15 00:50:54 +0000659 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
660 Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
Justin Bogner3212b182014-04-25 07:20:05 +0000661 assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
Justin Bogneref512b92014-01-06 22:27:43 +0000662 NumRegionCounters = Walker.NextCounter;
Duncan P. N. Exon Smith4bc77312014-04-16 16:03:27 +0000663 FunctionHash = Walker.Hash.finalize();
Justin Bogneref512b92014-01-06 22:27:43 +0000664}
665
Vedant Kumarc468bb82016-07-11 22:57:44 +0000666bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
Alex Lorenzee024992014-08-04 18:41:51 +0000667 if (SkipCoverageMapping)
Vedant Kumarc468bb82016-07-11 22:57:44 +0000668 return true;
669
670 // Don't map the functions in system headers.
671 const auto &SM = CGM.getContext().getSourceManager();
Alex Lorenzee024992014-08-04 18:41:51 +0000672 auto Loc = D->getBody()->getLocStart();
Vedant Kumarc468bb82016-07-11 22:57:44 +0000673 return SM.isInSystemHeader(Loc);
674}
675
676void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
677 if (skipRegionMappingForDecl(D))
Alex Lorenzee024992014-08-04 18:41:51 +0000678 return;
679
Justin Bogner970ac602014-12-08 19:04:51 +0000680 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000681 llvm::raw_string_ostream OS(CoverageMapping);
682 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
683 CGM.getContext().getSourceManager(),
Justin Bognere5ee6c52014-10-02 16:44:01 +0000684 CGM.getLangOpts(), RegionCounterMap.get());
Alex Lorenzee024992014-08-04 18:41:51 +0000685 MappingGen.emitCounterMapping(D, OS);
686 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000687
688 if (CoverageMapping.empty())
689 return;
690
691 CGM.getCoverageMapping()->addFunctionMappingRecord(
692 FuncNameVar, FuncName, FunctionHash, CoverageMapping);
Alex Lorenzee024992014-08-04 18:41:51 +0000693}
694
695void
Justin Bogner60d852b2015-04-23 00:31:16 +0000696CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
Alex Lorenzee024992014-08-04 18:41:51 +0000697 llvm::GlobalValue::LinkageTypes Linkage) {
Vedant Kumarc468bb82016-07-11 22:57:44 +0000698 if (skipRegionMappingForDecl(D))
Alex Lorenzee024992014-08-04 18:41:51 +0000699 return;
700
Justin Bogner970ac602014-12-08 19:04:51 +0000701 std::string CoverageMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000702 llvm::raw_string_ostream OS(CoverageMapping);
703 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
704 CGM.getContext().getSourceManager(),
705 CGM.getLangOpts());
706 MappingGen.emitEmptyMapping(D, OS);
707 OS.flush();
Justin Bogner970ac602014-12-08 19:04:51 +0000708
709 if (CoverageMapping.empty())
710 return;
711
Justin Bogner60d852b2015-04-23 00:31:16 +0000712 setFuncName(Name, Linkage);
Justin Bogner970ac602014-12-08 19:04:51 +0000713 CGM.getCoverageMapping()->addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +0000714 FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
Alex Lorenzee024992014-08-04 18:41:51 +0000715}
716
Bob Wilsonbf854f02014-02-17 19:21:09 +0000717void CodeGenPGO::computeRegionCounts(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000718 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000719 ComputeRegionCounts Walker(*StmtCountMap, *this);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000720 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
721 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000722 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
723 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000724 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
725 Walker.VisitBlockDecl(BD);
Justin Bogner81ab90f2014-04-15 00:50:54 +0000726 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
727 Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000728}
729
Justin Bogner837a6f62014-04-18 21:52:00 +0000730void
731CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
732 llvm::Function *Fn) {
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000733 if (!haveRegionCounts())
734 return;
735
Hans Wennborgdcfba332015-10-06 23:40:43 +0000736 uint64_t FunctionCount = getRegionCount(nullptr);
Diego Novilloaa8b1cb2015-05-27 21:58:42 +0000737 Fn->setEntryCount(FunctionCount);
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000738}
739
Justin Bogner66242d62015-04-23 23:06:47 +0000740void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S) {
Rong Xu9837ef52016-02-04 18:39:09 +0000741 if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap)
Justin Bogneref512b92014-01-06 22:27:43 +0000742 return;
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000743 if (!Builder.GetInsertBlock())
Justin Bogner203f91e2015-01-09 01:46:40 +0000744 return;
Justin Bogner66242d62015-04-23 23:06:47 +0000745
746 unsigned Counter = (*RegionCounterMap)[S];
Justin Bogner970ac602014-12-08 19:04:51 +0000747 auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
David Blaikie43f9bb72015-05-18 22:14:03 +0000748 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
749 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
Justin Bogner970ac602014-12-08 19:04:51 +0000750 Builder.getInt64(FunctionHash),
751 Builder.getInt32(NumRegionCounters),
David Blaikie43f9bb72015-05-18 22:14:03 +0000752 Builder.getInt32(Counter)});
Justin Bogneref512b92014-01-06 22:27:43 +0000753}
754
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000755// This method either inserts a call to the profile run-time during
756// instrumentation or puts profile data into metadata for PGO use.
757void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
758 llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
759
760 if (!EnableValueProfiling)
761 return;
762
763 if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
764 return;
765
Betul Buyukkurt3da993c2016-03-31 18:41:34 +0000766 if (isa<llvm::Constant>(ValuePtr))
767 return;
768
Rong Xu9837ef52016-02-04 18:39:09 +0000769 bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000770 if (InstrumentValueSites && RegionCounterMap) {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000771 auto BuilderInsertPoint = Builder.saveIP();
772 Builder.SetInsertPoint(ValueSite);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000773 llvm::Value *Args[5] = {
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000774 llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()),
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000775 Builder.getInt64(FunctionHash),
776 Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
777 Builder.getInt32(ValueKind),
778 Builder.getInt32(NumValueSites[ValueKind]++)
779 };
780 Builder.CreateCall(
781 CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
Betul Buyukkurtcb6f5f12016-03-29 20:44:09 +0000782 Builder.restoreIP(BuilderInsertPoint);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000783 return;
784 }
785
786 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
787 if (PGOReader && haveRegionCounts()) {
788 // We record the top most called three functions at each call site.
789 // Profile metadata contains "VP" string identifying this metadata
790 // as value profiling data, then a uint32_t value for the value profiling
791 // kind, a uint64_t value for the total number of times the call is
792 // executed, followed by the function hash and execution count (uint64_t)
793 // pairs for each function.
794 if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
795 return;
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000796
Xinliang David Li5527a9d2016-02-04 19:54:17 +0000797 llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
798 (llvm::InstrProfValueKind)ValueKind,
799 NumValueSites[ValueKind]);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000800
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000801 NumValueSites[ValueKind]++;
802 }
803}
804
Justin Bogner40b8ba12014-06-26 01:45:07 +0000805void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
806 bool IsInMainFile) {
807 CGM.getPGOStats().addVisited(IsInMainFile);
Justin Bogner7f8cf5b2014-12-02 22:38:52 +0000808 RegionCounts.clear();
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000809 llvm::Expected<llvm::InstrProfRecord> RecordExpected =
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000810 PGOReader->getInstrProfRecord(FuncName, FunctionHash);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000811 if (auto E = RecordExpected.takeError()) {
812 auto IPE = llvm::InstrProfError::take(std::move(E));
813 if (IPE == llvm::instrprof_error::unknown_function)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000814 CGM.getPGOStats().addMissing(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000815 else if (IPE == llvm::instrprof_error::hash_mismatch)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000816 CGM.getPGOStats().addMismatched(IsInMainFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000817 else if (IPE == llvm::instrprof_error::malformed)
Justin Bogner9c6818e2014-08-01 22:50:16 +0000818 // TODO: Consider a more specific warning for this case.
819 CGM.getPGOStats().addMismatched(IsInMainFile);
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000820 return;
Justin Bognere2ef2a02014-04-15 21:22:35 +0000821 }
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000822 ProfRecord =
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000823 llvm::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
Betul Buyukkurt518276a2016-01-23 22:50:44 +0000824 RegionCounts = ProfRecord->Counts;
Justin Bogneref512b92014-01-06 22:27:43 +0000825}
826
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000827/// \brief Calculate what to divide by to scale weights.
828///
829/// Given the maximum weight, calculate a divisor that will scale all the
830/// weights to strictly less than UINT32_MAX.
831static uint64_t calculateWeightScale(uint64_t MaxWeight) {
832 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
833}
834
835/// \brief Scale an individual branch weight (and add 1).
836///
837/// Scale a 64-bit weight down to 32-bits using \c Scale.
838///
839/// According to Laplace's Rule of Succession, it is better to compute the
840/// weight based on the count plus 1, so universally add 1 to the value.
841///
842/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
843/// greater than \c Weight.
844static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
845 assert(Scale && "scale by 0?");
846 uint64_t Scaled = Weight / Scale + 1;
847 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
848 return Scaled;
849}
850
Justin Bogner65512642015-05-02 05:00:55 +0000851llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
852 uint64_t FalseCount) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000853 // Check for empty weights.
Justin Bogneref512b92014-01-06 22:27:43 +0000854 if (!TrueCount && !FalseCount)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000855 return nullptr;
Justin Bogneref512b92014-01-06 22:27:43 +0000856
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000857 // Calculate how to scale down to 32-bits.
858 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
859
Justin Bogneref512b92014-01-06 22:27:43 +0000860 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000861 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
862 scaleBranchWeight(FalseCount, Scale));
Justin Bogneref512b92014-01-06 22:27:43 +0000863}
864
Justin Bogner65512642015-05-02 05:00:55 +0000865llvm::MDNode *
866CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000867 // We need at least two elements to create meaningful weights.
868 if (Weights.size() < 2)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000869 return nullptr;
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000870
Justin Bognerf3aefca2014-04-04 02:48:51 +0000871 // Check for empty weights.
872 uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
873 if (MaxWeight == 0)
874 return nullptr;
875
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000876 // Calculate how to scale down to 32-bits.
Justin Bognerf3aefca2014-04-04 02:48:51 +0000877 uint64_t Scale = calculateWeightScale(MaxWeight);
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000878
Justin Bogneref512b92014-01-06 22:27:43 +0000879 SmallVector<uint32_t, 16> ScaledWeights;
880 ScaledWeights.reserve(Weights.size());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000881 for (uint64_t W : Weights)
882 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
883
884 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Justin Bogneref512b92014-01-06 22:27:43 +0000885 return MDHelper.createBranchWeights(ScaledWeights);
886}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000887
Justin Bogner65512642015-05-02 05:00:55 +0000888llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
889 uint64_t LoopCount) {
890 if (!PGO.haveRegionCounts())
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000891 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +0000892 Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
Justin Bogner1c21c282015-04-13 12:23:19 +0000893 assert(CondCount.hasValue() && "missing expected loop condition count");
894 if (*CondCount == 0)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000895 return nullptr;
Justin Bogner65512642015-05-02 05:00:55 +0000896 return createProfileWeights(LoopCount,
897 std::max(*CondCount, LoopCount) - LoopCount);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000898}