1*67e74705SXin Li //===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // Instrumentation-based profile-guided optimization
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li
14*67e74705SXin Li #include "CodeGenPGO.h"
15*67e74705SXin Li #include "CodeGenFunction.h"
16*67e74705SXin Li #include "CoverageMappingGen.h"
17*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
18*67e74705SXin Li #include "clang/AST/StmtVisitor.h"
19*67e74705SXin Li #include "llvm/IR/Intrinsics.h"
20*67e74705SXin Li #include "llvm/IR/MDBuilder.h"
21*67e74705SXin Li #include "llvm/Support/Endian.h"
22*67e74705SXin Li #include "llvm/Support/FileSystem.h"
23*67e74705SXin Li #include "llvm/Support/MD5.h"
24*67e74705SXin Li
25*67e74705SXin Li static llvm::cl::opt<bool> EnableValueProfiling(
26*67e74705SXin Li "enable-value-profiling", llvm::cl::ZeroOrMore,
27*67e74705SXin Li llvm::cl::desc("Enable value profiling"), llvm::cl::init(false));
28*67e74705SXin Li
29*67e74705SXin Li using namespace clang;
30*67e74705SXin Li using namespace CodeGen;
31*67e74705SXin Li
setFuncName(StringRef Name,llvm::GlobalValue::LinkageTypes Linkage)32*67e74705SXin Li void CodeGenPGO::setFuncName(StringRef Name,
33*67e74705SXin Li llvm::GlobalValue::LinkageTypes Linkage) {
34*67e74705SXin Li llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
35*67e74705SXin Li FuncName = llvm::getPGOFuncName(
36*67e74705SXin Li Name, Linkage, CGM.getCodeGenOpts().MainFileName,
37*67e74705SXin Li PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
38*67e74705SXin Li
39*67e74705SXin Li // If we're generating a profile, create a variable for the name.
40*67e74705SXin Li if (CGM.getCodeGenOpts().hasProfileClangInstr())
41*67e74705SXin Li FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
42*67e74705SXin Li }
43*67e74705SXin Li
setFuncName(llvm::Function * Fn)44*67e74705SXin Li void CodeGenPGO::setFuncName(llvm::Function *Fn) {
45*67e74705SXin Li setFuncName(Fn->getName(), Fn->getLinkage());
46*67e74705SXin Li // Create PGOFuncName meta data.
47*67e74705SXin Li llvm::createPGOFuncNameMetadata(*Fn, FuncName);
48*67e74705SXin Li }
49*67e74705SXin Li
50*67e74705SXin Li namespace {
51*67e74705SXin Li /// \brief Stable hasher for PGO region counters.
52*67e74705SXin Li ///
53*67e74705SXin Li /// PGOHash produces a stable hash of a given function's control flow.
54*67e74705SXin Li ///
55*67e74705SXin Li /// Changing the output of this hash will invalidate all previously generated
56*67e74705SXin Li /// profiles -- i.e., don't do it.
57*67e74705SXin Li ///
58*67e74705SXin Li /// \note When this hash does eventually change (years?), we still need to
59*67e74705SXin Li /// support old hashes. We'll need to pull in the version number from the
60*67e74705SXin Li /// profile data format and use the matching hash function.
61*67e74705SXin Li class PGOHash {
62*67e74705SXin Li uint64_t Working;
63*67e74705SXin Li unsigned Count;
64*67e74705SXin Li llvm::MD5 MD5;
65*67e74705SXin Li
66*67e74705SXin Li static const int NumBitsPerType = 6;
67*67e74705SXin Li static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
68*67e74705SXin Li static const unsigned TooBig = 1u << NumBitsPerType;
69*67e74705SXin Li
70*67e74705SXin Li public:
71*67e74705SXin Li /// \brief Hash values for AST nodes.
72*67e74705SXin Li ///
73*67e74705SXin Li /// Distinct values for AST nodes that have region counters attached.
74*67e74705SXin Li ///
75*67e74705SXin Li /// These values must be stable. All new members must be added at the end,
76*67e74705SXin Li /// and no members should be removed. Changing the enumeration value for an
77*67e74705SXin Li /// AST node will affect the hash of every function that contains that node.
78*67e74705SXin Li enum HashType : unsigned char {
79*67e74705SXin Li None = 0,
80*67e74705SXin Li LabelStmt = 1,
81*67e74705SXin Li WhileStmt,
82*67e74705SXin Li DoStmt,
83*67e74705SXin Li ForStmt,
84*67e74705SXin Li CXXForRangeStmt,
85*67e74705SXin Li ObjCForCollectionStmt,
86*67e74705SXin Li SwitchStmt,
87*67e74705SXin Li CaseStmt,
88*67e74705SXin Li DefaultStmt,
89*67e74705SXin Li IfStmt,
90*67e74705SXin Li CXXTryStmt,
91*67e74705SXin Li CXXCatchStmt,
92*67e74705SXin Li ConditionalOperator,
93*67e74705SXin Li BinaryOperatorLAnd,
94*67e74705SXin Li BinaryOperatorLOr,
95*67e74705SXin Li BinaryConditionalOperator,
96*67e74705SXin Li
97*67e74705SXin Li // Keep this last. It's for the static assert that follows.
98*67e74705SXin Li LastHashType
99*67e74705SXin Li };
100*67e74705SXin Li static_assert(LastHashType <= TooBig, "Too many types in HashType");
101*67e74705SXin Li
102*67e74705SXin Li // TODO: When this format changes, take in a version number here, and use the
103*67e74705SXin Li // old hash calculation for file formats that used the old hash.
PGOHash()104*67e74705SXin Li PGOHash() : Working(0), Count(0) {}
105*67e74705SXin Li void combine(HashType Type);
106*67e74705SXin Li uint64_t finalize();
107*67e74705SXin Li };
108*67e74705SXin Li const int PGOHash::NumBitsPerType;
109*67e74705SXin Li const unsigned PGOHash::NumTypesPerWord;
110*67e74705SXin Li const unsigned PGOHash::TooBig;
111*67e74705SXin Li
112*67e74705SXin Li /// A RecursiveASTVisitor that fills a map of statements to PGO counters.
113*67e74705SXin Li struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
114*67e74705SXin Li /// The next counter value to assign.
115*67e74705SXin Li unsigned NextCounter;
116*67e74705SXin Li /// The function hash.
117*67e74705SXin Li PGOHash Hash;
118*67e74705SXin Li /// The map of statements to counters.
119*67e74705SXin Li llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
120*67e74705SXin Li
MapRegionCounters__anonafb508d10111::MapRegionCounters121*67e74705SXin Li MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
122*67e74705SXin Li : NextCounter(0), CounterMap(CounterMap) {}
123*67e74705SXin Li
124*67e74705SXin Li // Blocks and lambdas are handled as separate functions, so we need not
125*67e74705SXin Li // traverse them in the parent context.
TraverseBlockExpr__anonafb508d10111::MapRegionCounters126*67e74705SXin Li bool TraverseBlockExpr(BlockExpr *BE) { return true; }
TraverseLambdaBody__anonafb508d10111::MapRegionCounters127*67e74705SXin Li bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
TraverseCapturedStmt__anonafb508d10111::MapRegionCounters128*67e74705SXin Li bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
129*67e74705SXin Li
VisitDecl__anonafb508d10111::MapRegionCounters130*67e74705SXin Li bool VisitDecl(const Decl *D) {
131*67e74705SXin Li switch (D->getKind()) {
132*67e74705SXin Li default:
133*67e74705SXin Li break;
134*67e74705SXin Li case Decl::Function:
135*67e74705SXin Li case Decl::CXXMethod:
136*67e74705SXin Li case Decl::CXXConstructor:
137*67e74705SXin Li case Decl::CXXDestructor:
138*67e74705SXin Li case Decl::CXXConversion:
139*67e74705SXin Li case Decl::ObjCMethod:
140*67e74705SXin Li case Decl::Block:
141*67e74705SXin Li case Decl::Captured:
142*67e74705SXin Li CounterMap[D->getBody()] = NextCounter++;
143*67e74705SXin Li break;
144*67e74705SXin Li }
145*67e74705SXin Li return true;
146*67e74705SXin Li }
147*67e74705SXin Li
VisitStmt__anonafb508d10111::MapRegionCounters148*67e74705SXin Li bool VisitStmt(const Stmt *S) {
149*67e74705SXin Li auto Type = getHashType(S);
150*67e74705SXin Li if (Type == PGOHash::None)
151*67e74705SXin Li return true;
152*67e74705SXin Li
153*67e74705SXin Li CounterMap[S] = NextCounter++;
154*67e74705SXin Li Hash.combine(Type);
155*67e74705SXin Li return true;
156*67e74705SXin Li }
getHashType__anonafb508d10111::MapRegionCounters157*67e74705SXin Li PGOHash::HashType getHashType(const Stmt *S) {
158*67e74705SXin Li switch (S->getStmtClass()) {
159*67e74705SXin Li default:
160*67e74705SXin Li break;
161*67e74705SXin Li case Stmt::LabelStmtClass:
162*67e74705SXin Li return PGOHash::LabelStmt;
163*67e74705SXin Li case Stmt::WhileStmtClass:
164*67e74705SXin Li return PGOHash::WhileStmt;
165*67e74705SXin Li case Stmt::DoStmtClass:
166*67e74705SXin Li return PGOHash::DoStmt;
167*67e74705SXin Li case Stmt::ForStmtClass:
168*67e74705SXin Li return PGOHash::ForStmt;
169*67e74705SXin Li case Stmt::CXXForRangeStmtClass:
170*67e74705SXin Li return PGOHash::CXXForRangeStmt;
171*67e74705SXin Li case Stmt::ObjCForCollectionStmtClass:
172*67e74705SXin Li return PGOHash::ObjCForCollectionStmt;
173*67e74705SXin Li case Stmt::SwitchStmtClass:
174*67e74705SXin Li return PGOHash::SwitchStmt;
175*67e74705SXin Li case Stmt::CaseStmtClass:
176*67e74705SXin Li return PGOHash::CaseStmt;
177*67e74705SXin Li case Stmt::DefaultStmtClass:
178*67e74705SXin Li return PGOHash::DefaultStmt;
179*67e74705SXin Li case Stmt::IfStmtClass:
180*67e74705SXin Li return PGOHash::IfStmt;
181*67e74705SXin Li case Stmt::CXXTryStmtClass:
182*67e74705SXin Li return PGOHash::CXXTryStmt;
183*67e74705SXin Li case Stmt::CXXCatchStmtClass:
184*67e74705SXin Li return PGOHash::CXXCatchStmt;
185*67e74705SXin Li case Stmt::ConditionalOperatorClass:
186*67e74705SXin Li return PGOHash::ConditionalOperator;
187*67e74705SXin Li case Stmt::BinaryConditionalOperatorClass:
188*67e74705SXin Li return PGOHash::BinaryConditionalOperator;
189*67e74705SXin Li case Stmt::BinaryOperatorClass: {
190*67e74705SXin Li const BinaryOperator *BO = cast<BinaryOperator>(S);
191*67e74705SXin Li if (BO->getOpcode() == BO_LAnd)
192*67e74705SXin Li return PGOHash::BinaryOperatorLAnd;
193*67e74705SXin Li if (BO->getOpcode() == BO_LOr)
194*67e74705SXin Li return PGOHash::BinaryOperatorLOr;
195*67e74705SXin Li break;
196*67e74705SXin Li }
197*67e74705SXin Li }
198*67e74705SXin Li return PGOHash::None;
199*67e74705SXin Li }
200*67e74705SXin Li };
201*67e74705SXin Li
202*67e74705SXin Li /// A StmtVisitor that propagates the raw counts through the AST and
203*67e74705SXin Li /// records the count at statements where the value may change.
204*67e74705SXin Li struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
205*67e74705SXin Li /// PGO state.
206*67e74705SXin Li CodeGenPGO &PGO;
207*67e74705SXin Li
208*67e74705SXin Li /// A flag that is set when the current count should be recorded on the
209*67e74705SXin Li /// next statement, such as at the exit of a loop.
210*67e74705SXin Li bool RecordNextStmtCount;
211*67e74705SXin Li
212*67e74705SXin Li /// The count at the current location in the traversal.
213*67e74705SXin Li uint64_t CurrentCount;
214*67e74705SXin Li
215*67e74705SXin Li /// The map of statements to count values.
216*67e74705SXin Li llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
217*67e74705SXin Li
218*67e74705SXin Li /// BreakContinueStack - Keep counts of breaks and continues inside loops.
219*67e74705SXin Li struct BreakContinue {
220*67e74705SXin Li uint64_t BreakCount;
221*67e74705SXin Li uint64_t ContinueCount;
BreakContinue__anonafb508d10111::ComputeRegionCounts::BreakContinue222*67e74705SXin Li BreakContinue() : BreakCount(0), ContinueCount(0) {}
223*67e74705SXin Li };
224*67e74705SXin Li SmallVector<BreakContinue, 8> BreakContinueStack;
225*67e74705SXin Li
ComputeRegionCounts__anonafb508d10111::ComputeRegionCounts226*67e74705SXin Li ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
227*67e74705SXin Li CodeGenPGO &PGO)
228*67e74705SXin Li : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
229*67e74705SXin Li
RecordStmtCount__anonafb508d10111::ComputeRegionCounts230*67e74705SXin Li void RecordStmtCount(const Stmt *S) {
231*67e74705SXin Li if (RecordNextStmtCount) {
232*67e74705SXin Li CountMap[S] = CurrentCount;
233*67e74705SXin Li RecordNextStmtCount = false;
234*67e74705SXin Li }
235*67e74705SXin Li }
236*67e74705SXin Li
237*67e74705SXin Li /// Set and return the current count.
setCount__anonafb508d10111::ComputeRegionCounts238*67e74705SXin Li uint64_t setCount(uint64_t Count) {
239*67e74705SXin Li CurrentCount = Count;
240*67e74705SXin Li return Count;
241*67e74705SXin Li }
242*67e74705SXin Li
VisitStmt__anonafb508d10111::ComputeRegionCounts243*67e74705SXin Li void VisitStmt(const Stmt *S) {
244*67e74705SXin Li RecordStmtCount(S);
245*67e74705SXin Li for (const Stmt *Child : S->children())
246*67e74705SXin Li if (Child)
247*67e74705SXin Li this->Visit(Child);
248*67e74705SXin Li }
249*67e74705SXin Li
VisitFunctionDecl__anonafb508d10111::ComputeRegionCounts250*67e74705SXin Li void VisitFunctionDecl(const FunctionDecl *D) {
251*67e74705SXin Li // Counter tracks entry to the function body.
252*67e74705SXin Li uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
253*67e74705SXin Li CountMap[D->getBody()] = BodyCount;
254*67e74705SXin Li Visit(D->getBody());
255*67e74705SXin Li }
256*67e74705SXin Li
257*67e74705SXin Li // Skip lambda expressions. We visit these as FunctionDecls when we're
258*67e74705SXin Li // generating them and aren't interested in the body when generating a
259*67e74705SXin Li // parent context.
VisitLambdaExpr__anonafb508d10111::ComputeRegionCounts260*67e74705SXin Li void VisitLambdaExpr(const LambdaExpr *LE) {}
261*67e74705SXin Li
VisitCapturedDecl__anonafb508d10111::ComputeRegionCounts262*67e74705SXin Li void VisitCapturedDecl(const CapturedDecl *D) {
263*67e74705SXin Li // Counter tracks entry to the capture body.
264*67e74705SXin Li uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
265*67e74705SXin Li CountMap[D->getBody()] = BodyCount;
266*67e74705SXin Li Visit(D->getBody());
267*67e74705SXin Li }
268*67e74705SXin Li
VisitObjCMethodDecl__anonafb508d10111::ComputeRegionCounts269*67e74705SXin Li void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
270*67e74705SXin Li // Counter tracks entry to the method body.
271*67e74705SXin Li uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
272*67e74705SXin Li CountMap[D->getBody()] = BodyCount;
273*67e74705SXin Li Visit(D->getBody());
274*67e74705SXin Li }
275*67e74705SXin Li
VisitBlockDecl__anonafb508d10111::ComputeRegionCounts276*67e74705SXin Li void VisitBlockDecl(const BlockDecl *D) {
277*67e74705SXin Li // Counter tracks entry to the block body.
278*67e74705SXin Li uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
279*67e74705SXin Li CountMap[D->getBody()] = BodyCount;
280*67e74705SXin Li Visit(D->getBody());
281*67e74705SXin Li }
282*67e74705SXin Li
VisitReturnStmt__anonafb508d10111::ComputeRegionCounts283*67e74705SXin Li void VisitReturnStmt(const ReturnStmt *S) {
284*67e74705SXin Li RecordStmtCount(S);
285*67e74705SXin Li if (S->getRetValue())
286*67e74705SXin Li Visit(S->getRetValue());
287*67e74705SXin Li CurrentCount = 0;
288*67e74705SXin Li RecordNextStmtCount = true;
289*67e74705SXin Li }
290*67e74705SXin Li
VisitCXXThrowExpr__anonafb508d10111::ComputeRegionCounts291*67e74705SXin Li void VisitCXXThrowExpr(const CXXThrowExpr *E) {
292*67e74705SXin Li RecordStmtCount(E);
293*67e74705SXin Li if (E->getSubExpr())
294*67e74705SXin Li Visit(E->getSubExpr());
295*67e74705SXin Li CurrentCount = 0;
296*67e74705SXin Li RecordNextStmtCount = true;
297*67e74705SXin Li }
298*67e74705SXin Li
VisitGotoStmt__anonafb508d10111::ComputeRegionCounts299*67e74705SXin Li void VisitGotoStmt(const GotoStmt *S) {
300*67e74705SXin Li RecordStmtCount(S);
301*67e74705SXin Li CurrentCount = 0;
302*67e74705SXin Li RecordNextStmtCount = true;
303*67e74705SXin Li }
304*67e74705SXin Li
VisitLabelStmt__anonafb508d10111::ComputeRegionCounts305*67e74705SXin Li void VisitLabelStmt(const LabelStmt *S) {
306*67e74705SXin Li RecordNextStmtCount = false;
307*67e74705SXin Li // Counter tracks the block following the label.
308*67e74705SXin Li uint64_t BlockCount = setCount(PGO.getRegionCount(S));
309*67e74705SXin Li CountMap[S] = BlockCount;
310*67e74705SXin Li Visit(S->getSubStmt());
311*67e74705SXin Li }
312*67e74705SXin Li
VisitBreakStmt__anonafb508d10111::ComputeRegionCounts313*67e74705SXin Li void VisitBreakStmt(const BreakStmt *S) {
314*67e74705SXin Li RecordStmtCount(S);
315*67e74705SXin Li assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
316*67e74705SXin Li BreakContinueStack.back().BreakCount += CurrentCount;
317*67e74705SXin Li CurrentCount = 0;
318*67e74705SXin Li RecordNextStmtCount = true;
319*67e74705SXin Li }
320*67e74705SXin Li
VisitContinueStmt__anonafb508d10111::ComputeRegionCounts321*67e74705SXin Li void VisitContinueStmt(const ContinueStmt *S) {
322*67e74705SXin Li RecordStmtCount(S);
323*67e74705SXin Li assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
324*67e74705SXin Li BreakContinueStack.back().ContinueCount += CurrentCount;
325*67e74705SXin Li CurrentCount = 0;
326*67e74705SXin Li RecordNextStmtCount = true;
327*67e74705SXin Li }
328*67e74705SXin Li
VisitWhileStmt__anonafb508d10111::ComputeRegionCounts329*67e74705SXin Li void VisitWhileStmt(const WhileStmt *S) {
330*67e74705SXin Li RecordStmtCount(S);
331*67e74705SXin Li uint64_t ParentCount = CurrentCount;
332*67e74705SXin Li
333*67e74705SXin Li BreakContinueStack.push_back(BreakContinue());
334*67e74705SXin Li // Visit the body region first so the break/continue adjustments can be
335*67e74705SXin Li // included when visiting the condition.
336*67e74705SXin Li uint64_t BodyCount = setCount(PGO.getRegionCount(S));
337*67e74705SXin Li CountMap[S->getBody()] = CurrentCount;
338*67e74705SXin Li Visit(S->getBody());
339*67e74705SXin Li uint64_t BackedgeCount = CurrentCount;
340*67e74705SXin Li
341*67e74705SXin Li // ...then go back and propagate counts through the condition. The count
342*67e74705SXin Li // at the start of the condition is the sum of the incoming edges,
343*67e74705SXin Li // the backedge from the end of the loop body, and the edges from
344*67e74705SXin Li // continue statements.
345*67e74705SXin Li BreakContinue BC = BreakContinueStack.pop_back_val();
346*67e74705SXin Li uint64_t CondCount =
347*67e74705SXin Li setCount(ParentCount + BackedgeCount + BC.ContinueCount);
348*67e74705SXin Li CountMap[S->getCond()] = CondCount;
349*67e74705SXin Li Visit(S->getCond());
350*67e74705SXin Li setCount(BC.BreakCount + CondCount - BodyCount);
351*67e74705SXin Li RecordNextStmtCount = true;
352*67e74705SXin Li }
353*67e74705SXin Li
VisitDoStmt__anonafb508d10111::ComputeRegionCounts354*67e74705SXin Li void VisitDoStmt(const DoStmt *S) {
355*67e74705SXin Li RecordStmtCount(S);
356*67e74705SXin Li uint64_t LoopCount = PGO.getRegionCount(S);
357*67e74705SXin Li
358*67e74705SXin Li BreakContinueStack.push_back(BreakContinue());
359*67e74705SXin Li // The count doesn't include the fallthrough from the parent scope. Add it.
360*67e74705SXin Li uint64_t BodyCount = setCount(LoopCount + CurrentCount);
361*67e74705SXin Li CountMap[S->getBody()] = BodyCount;
362*67e74705SXin Li Visit(S->getBody());
363*67e74705SXin Li uint64_t BackedgeCount = CurrentCount;
364*67e74705SXin Li
365*67e74705SXin Li BreakContinue BC = BreakContinueStack.pop_back_val();
366*67e74705SXin Li // The count at the start of the condition is equal to the count at the
367*67e74705SXin Li // end of the body, plus any continues.
368*67e74705SXin Li uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
369*67e74705SXin Li CountMap[S->getCond()] = CondCount;
370*67e74705SXin Li Visit(S->getCond());
371*67e74705SXin Li setCount(BC.BreakCount + CondCount - LoopCount);
372*67e74705SXin Li RecordNextStmtCount = true;
373*67e74705SXin Li }
374*67e74705SXin Li
VisitForStmt__anonafb508d10111::ComputeRegionCounts375*67e74705SXin Li void VisitForStmt(const ForStmt *S) {
376*67e74705SXin Li RecordStmtCount(S);
377*67e74705SXin Li if (S->getInit())
378*67e74705SXin Li Visit(S->getInit());
379*67e74705SXin Li
380*67e74705SXin Li uint64_t ParentCount = CurrentCount;
381*67e74705SXin Li
382*67e74705SXin Li BreakContinueStack.push_back(BreakContinue());
383*67e74705SXin Li // Visit the body region first. (This is basically the same as a while
384*67e74705SXin Li // loop; see further comments in VisitWhileStmt.)
385*67e74705SXin Li uint64_t BodyCount = setCount(PGO.getRegionCount(S));
386*67e74705SXin Li CountMap[S->getBody()] = BodyCount;
387*67e74705SXin Li Visit(S->getBody());
388*67e74705SXin Li uint64_t BackedgeCount = CurrentCount;
389*67e74705SXin Li BreakContinue BC = BreakContinueStack.pop_back_val();
390*67e74705SXin Li
391*67e74705SXin Li // The increment is essentially part of the body but it needs to include
392*67e74705SXin Li // the count for all the continue statements.
393*67e74705SXin Li if (S->getInc()) {
394*67e74705SXin Li uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
395*67e74705SXin Li CountMap[S->getInc()] = IncCount;
396*67e74705SXin Li Visit(S->getInc());
397*67e74705SXin Li }
398*67e74705SXin Li
399*67e74705SXin Li // ...then go back and propagate counts through the condition.
400*67e74705SXin Li uint64_t CondCount =
401*67e74705SXin Li setCount(ParentCount + BackedgeCount + BC.ContinueCount);
402*67e74705SXin Li if (S->getCond()) {
403*67e74705SXin Li CountMap[S->getCond()] = CondCount;
404*67e74705SXin Li Visit(S->getCond());
405*67e74705SXin Li }
406*67e74705SXin Li setCount(BC.BreakCount + CondCount - BodyCount);
407*67e74705SXin Li RecordNextStmtCount = true;
408*67e74705SXin Li }
409*67e74705SXin Li
VisitCXXForRangeStmt__anonafb508d10111::ComputeRegionCounts410*67e74705SXin Li void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
411*67e74705SXin Li RecordStmtCount(S);
412*67e74705SXin Li Visit(S->getLoopVarStmt());
413*67e74705SXin Li Visit(S->getRangeStmt());
414*67e74705SXin Li Visit(S->getBeginStmt());
415*67e74705SXin Li Visit(S->getEndStmt());
416*67e74705SXin Li
417*67e74705SXin Li uint64_t ParentCount = CurrentCount;
418*67e74705SXin Li BreakContinueStack.push_back(BreakContinue());
419*67e74705SXin Li // Visit the body region first. (This is basically the same as a while
420*67e74705SXin Li // loop; see further comments in VisitWhileStmt.)
421*67e74705SXin Li uint64_t BodyCount = setCount(PGO.getRegionCount(S));
422*67e74705SXin Li CountMap[S->getBody()] = BodyCount;
423*67e74705SXin Li Visit(S->getBody());
424*67e74705SXin Li uint64_t BackedgeCount = CurrentCount;
425*67e74705SXin Li BreakContinue BC = BreakContinueStack.pop_back_val();
426*67e74705SXin Li
427*67e74705SXin Li // The increment is essentially part of the body but it needs to include
428*67e74705SXin Li // the count for all the continue statements.
429*67e74705SXin Li uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
430*67e74705SXin Li CountMap[S->getInc()] = IncCount;
431*67e74705SXin Li Visit(S->getInc());
432*67e74705SXin Li
433*67e74705SXin Li // ...then go back and propagate counts through the condition.
434*67e74705SXin Li uint64_t CondCount =
435*67e74705SXin Li setCount(ParentCount + BackedgeCount + BC.ContinueCount);
436*67e74705SXin Li CountMap[S->getCond()] = CondCount;
437*67e74705SXin Li Visit(S->getCond());
438*67e74705SXin Li setCount(BC.BreakCount + CondCount - BodyCount);
439*67e74705SXin Li RecordNextStmtCount = true;
440*67e74705SXin Li }
441*67e74705SXin Li
VisitObjCForCollectionStmt__anonafb508d10111::ComputeRegionCounts442*67e74705SXin Li void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
443*67e74705SXin Li RecordStmtCount(S);
444*67e74705SXin Li Visit(S->getElement());
445*67e74705SXin Li uint64_t ParentCount = CurrentCount;
446*67e74705SXin Li BreakContinueStack.push_back(BreakContinue());
447*67e74705SXin Li // Counter tracks the body of the loop.
448*67e74705SXin Li uint64_t BodyCount = setCount(PGO.getRegionCount(S));
449*67e74705SXin Li CountMap[S->getBody()] = BodyCount;
450*67e74705SXin Li Visit(S->getBody());
451*67e74705SXin Li uint64_t BackedgeCount = CurrentCount;
452*67e74705SXin Li BreakContinue BC = BreakContinueStack.pop_back_val();
453*67e74705SXin Li
454*67e74705SXin Li setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
455*67e74705SXin Li BodyCount);
456*67e74705SXin Li RecordNextStmtCount = true;
457*67e74705SXin Li }
458*67e74705SXin Li
VisitSwitchStmt__anonafb508d10111::ComputeRegionCounts459*67e74705SXin Li void VisitSwitchStmt(const SwitchStmt *S) {
460*67e74705SXin Li RecordStmtCount(S);
461*67e74705SXin Li Visit(S->getCond());
462*67e74705SXin Li CurrentCount = 0;
463*67e74705SXin Li BreakContinueStack.push_back(BreakContinue());
464*67e74705SXin Li Visit(S->getBody());
465*67e74705SXin Li // If the switch is inside a loop, add the continue counts.
466*67e74705SXin Li BreakContinue BC = BreakContinueStack.pop_back_val();
467*67e74705SXin Li if (!BreakContinueStack.empty())
468*67e74705SXin Li BreakContinueStack.back().ContinueCount += BC.ContinueCount;
469*67e74705SXin Li // Counter tracks the exit block of the switch.
470*67e74705SXin Li setCount(PGO.getRegionCount(S));
471*67e74705SXin Li RecordNextStmtCount = true;
472*67e74705SXin Li }
473*67e74705SXin Li
VisitSwitchCase__anonafb508d10111::ComputeRegionCounts474*67e74705SXin Li void VisitSwitchCase(const SwitchCase *S) {
475*67e74705SXin Li RecordNextStmtCount = false;
476*67e74705SXin Li // Counter for this particular case. This counts only jumps from the
477*67e74705SXin Li // switch header and does not include fallthrough from the case before
478*67e74705SXin Li // this one.
479*67e74705SXin Li uint64_t CaseCount = PGO.getRegionCount(S);
480*67e74705SXin Li setCount(CurrentCount + CaseCount);
481*67e74705SXin Li // We need the count without fallthrough in the mapping, so it's more useful
482*67e74705SXin Li // for branch probabilities.
483*67e74705SXin Li CountMap[S] = CaseCount;
484*67e74705SXin Li RecordNextStmtCount = true;
485*67e74705SXin Li Visit(S->getSubStmt());
486*67e74705SXin Li }
487*67e74705SXin Li
VisitIfStmt__anonafb508d10111::ComputeRegionCounts488*67e74705SXin Li void VisitIfStmt(const IfStmt *S) {
489*67e74705SXin Li RecordStmtCount(S);
490*67e74705SXin Li uint64_t ParentCount = CurrentCount;
491*67e74705SXin Li Visit(S->getCond());
492*67e74705SXin Li
493*67e74705SXin Li // Counter tracks the "then" part of an if statement. The count for
494*67e74705SXin Li // the "else" part, if it exists, will be calculated from this counter.
495*67e74705SXin Li uint64_t ThenCount = setCount(PGO.getRegionCount(S));
496*67e74705SXin Li CountMap[S->getThen()] = ThenCount;
497*67e74705SXin Li Visit(S->getThen());
498*67e74705SXin Li uint64_t OutCount = CurrentCount;
499*67e74705SXin Li
500*67e74705SXin Li uint64_t ElseCount = ParentCount - ThenCount;
501*67e74705SXin Li if (S->getElse()) {
502*67e74705SXin Li setCount(ElseCount);
503*67e74705SXin Li CountMap[S->getElse()] = ElseCount;
504*67e74705SXin Li Visit(S->getElse());
505*67e74705SXin Li OutCount += CurrentCount;
506*67e74705SXin Li } else
507*67e74705SXin Li OutCount += ElseCount;
508*67e74705SXin Li setCount(OutCount);
509*67e74705SXin Li RecordNextStmtCount = true;
510*67e74705SXin Li }
511*67e74705SXin Li
VisitCXXTryStmt__anonafb508d10111::ComputeRegionCounts512*67e74705SXin Li void VisitCXXTryStmt(const CXXTryStmt *S) {
513*67e74705SXin Li RecordStmtCount(S);
514*67e74705SXin Li Visit(S->getTryBlock());
515*67e74705SXin Li for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
516*67e74705SXin Li Visit(S->getHandler(I));
517*67e74705SXin Li // Counter tracks the continuation block of the try statement.
518*67e74705SXin Li setCount(PGO.getRegionCount(S));
519*67e74705SXin Li RecordNextStmtCount = true;
520*67e74705SXin Li }
521*67e74705SXin Li
VisitCXXCatchStmt__anonafb508d10111::ComputeRegionCounts522*67e74705SXin Li void VisitCXXCatchStmt(const CXXCatchStmt *S) {
523*67e74705SXin Li RecordNextStmtCount = false;
524*67e74705SXin Li // Counter tracks the catch statement's handler block.
525*67e74705SXin Li uint64_t CatchCount = setCount(PGO.getRegionCount(S));
526*67e74705SXin Li CountMap[S] = CatchCount;
527*67e74705SXin Li Visit(S->getHandlerBlock());
528*67e74705SXin Li }
529*67e74705SXin Li
VisitAbstractConditionalOperator__anonafb508d10111::ComputeRegionCounts530*67e74705SXin Li void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
531*67e74705SXin Li RecordStmtCount(E);
532*67e74705SXin Li uint64_t ParentCount = CurrentCount;
533*67e74705SXin Li Visit(E->getCond());
534*67e74705SXin Li
535*67e74705SXin Li // Counter tracks the "true" part of a conditional operator. The
536*67e74705SXin Li // count in the "false" part will be calculated from this counter.
537*67e74705SXin Li uint64_t TrueCount = setCount(PGO.getRegionCount(E));
538*67e74705SXin Li CountMap[E->getTrueExpr()] = TrueCount;
539*67e74705SXin Li Visit(E->getTrueExpr());
540*67e74705SXin Li uint64_t OutCount = CurrentCount;
541*67e74705SXin Li
542*67e74705SXin Li uint64_t FalseCount = setCount(ParentCount - TrueCount);
543*67e74705SXin Li CountMap[E->getFalseExpr()] = FalseCount;
544*67e74705SXin Li Visit(E->getFalseExpr());
545*67e74705SXin Li OutCount += CurrentCount;
546*67e74705SXin Li
547*67e74705SXin Li setCount(OutCount);
548*67e74705SXin Li RecordNextStmtCount = true;
549*67e74705SXin Li }
550*67e74705SXin Li
VisitBinLAnd__anonafb508d10111::ComputeRegionCounts551*67e74705SXin Li void VisitBinLAnd(const BinaryOperator *E) {
552*67e74705SXin Li RecordStmtCount(E);
553*67e74705SXin Li uint64_t ParentCount = CurrentCount;
554*67e74705SXin Li Visit(E->getLHS());
555*67e74705SXin Li // Counter tracks the right hand side of a logical and operator.
556*67e74705SXin Li uint64_t RHSCount = setCount(PGO.getRegionCount(E));
557*67e74705SXin Li CountMap[E->getRHS()] = RHSCount;
558*67e74705SXin Li Visit(E->getRHS());
559*67e74705SXin Li setCount(ParentCount + RHSCount - CurrentCount);
560*67e74705SXin Li RecordNextStmtCount = true;
561*67e74705SXin Li }
562*67e74705SXin Li
VisitBinLOr__anonafb508d10111::ComputeRegionCounts563*67e74705SXin Li void VisitBinLOr(const BinaryOperator *E) {
564*67e74705SXin Li RecordStmtCount(E);
565*67e74705SXin Li uint64_t ParentCount = CurrentCount;
566*67e74705SXin Li Visit(E->getLHS());
567*67e74705SXin Li // Counter tracks the right hand side of a logical or operator.
568*67e74705SXin Li uint64_t RHSCount = setCount(PGO.getRegionCount(E));
569*67e74705SXin Li CountMap[E->getRHS()] = RHSCount;
570*67e74705SXin Li Visit(E->getRHS());
571*67e74705SXin Li setCount(ParentCount + RHSCount - CurrentCount);
572*67e74705SXin Li RecordNextStmtCount = true;
573*67e74705SXin Li }
574*67e74705SXin Li };
575*67e74705SXin Li } // end anonymous namespace
576*67e74705SXin Li
combine(HashType Type)577*67e74705SXin Li void PGOHash::combine(HashType Type) {
578*67e74705SXin Li // Check that we never combine 0 and only have six bits.
579*67e74705SXin Li assert(Type && "Hash is invalid: unexpected type 0");
580*67e74705SXin Li assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
581*67e74705SXin Li
582*67e74705SXin Li // Pass through MD5 if enough work has built up.
583*67e74705SXin Li if (Count && Count % NumTypesPerWord == 0) {
584*67e74705SXin Li using namespace llvm::support;
585*67e74705SXin Li uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
586*67e74705SXin Li MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
587*67e74705SXin Li Working = 0;
588*67e74705SXin Li }
589*67e74705SXin Li
590*67e74705SXin Li // Accumulate the current type.
591*67e74705SXin Li ++Count;
592*67e74705SXin Li Working = Working << NumBitsPerType | Type;
593*67e74705SXin Li }
594*67e74705SXin Li
finalize()595*67e74705SXin Li uint64_t PGOHash::finalize() {
596*67e74705SXin Li // Use Working as the hash directly if we never used MD5.
597*67e74705SXin Li if (Count <= NumTypesPerWord)
598*67e74705SXin Li // No need to byte swap here, since none of the math was endian-dependent.
599*67e74705SXin Li // This number will be byte-swapped as required on endianness transitions,
600*67e74705SXin Li // so we will see the same value on the other side.
601*67e74705SXin Li return Working;
602*67e74705SXin Li
603*67e74705SXin Li // Check for remaining work in Working.
604*67e74705SXin Li if (Working)
605*67e74705SXin Li MD5.update(Working);
606*67e74705SXin Li
607*67e74705SXin Li // Finalize the MD5 and return the hash.
608*67e74705SXin Li llvm::MD5::MD5Result Result;
609*67e74705SXin Li MD5.final(Result);
610*67e74705SXin Li using namespace llvm::support;
611*67e74705SXin Li return endian::read<uint64_t, little, unaligned>(Result);
612*67e74705SXin Li }
613*67e74705SXin Li
assignRegionCounters(GlobalDecl GD,llvm::Function * Fn)614*67e74705SXin Li void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
615*67e74705SXin Li const Decl *D = GD.getDecl();
616*67e74705SXin Li bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
617*67e74705SXin Li llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
618*67e74705SXin Li if (!InstrumentRegions && !PGOReader)
619*67e74705SXin Li return;
620*67e74705SXin Li if (D->isImplicit())
621*67e74705SXin Li return;
622*67e74705SXin Li // Constructors and destructors may be represented by several functions in IR.
623*67e74705SXin Li // If so, instrument only base variant, others are implemented by delegation
624*67e74705SXin Li // to the base one, it would be counted twice otherwise.
625*67e74705SXin Li if (CGM.getTarget().getCXXABI().hasConstructorVariants() &&
626*67e74705SXin Li ((isa<CXXConstructorDecl>(GD.getDecl()) &&
627*67e74705SXin Li GD.getCtorType() != Ctor_Base) ||
628*67e74705SXin Li (isa<CXXDestructorDecl>(GD.getDecl()) &&
629*67e74705SXin Li GD.getDtorType() != Dtor_Base))) {
630*67e74705SXin Li return;
631*67e74705SXin Li }
632*67e74705SXin Li CGM.ClearUnusedCoverageMapping(D);
633*67e74705SXin Li setFuncName(Fn);
634*67e74705SXin Li
635*67e74705SXin Li mapRegionCounters(D);
636*67e74705SXin Li if (CGM.getCodeGenOpts().CoverageMapping)
637*67e74705SXin Li emitCounterRegionMapping(D);
638*67e74705SXin Li if (PGOReader) {
639*67e74705SXin Li SourceManager &SM = CGM.getContext().getSourceManager();
640*67e74705SXin Li loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
641*67e74705SXin Li computeRegionCounts(D);
642*67e74705SXin Li applyFunctionAttributes(PGOReader, Fn);
643*67e74705SXin Li }
644*67e74705SXin Li }
645*67e74705SXin Li
mapRegionCounters(const Decl * D)646*67e74705SXin Li void CodeGenPGO::mapRegionCounters(const Decl *D) {
647*67e74705SXin Li RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
648*67e74705SXin Li MapRegionCounters Walker(*RegionCounterMap);
649*67e74705SXin Li if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
650*67e74705SXin Li Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
651*67e74705SXin Li else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
652*67e74705SXin Li Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
653*67e74705SXin Li else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
654*67e74705SXin Li Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
655*67e74705SXin Li else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
656*67e74705SXin Li Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
657*67e74705SXin Li assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
658*67e74705SXin Li NumRegionCounters = Walker.NextCounter;
659*67e74705SXin Li FunctionHash = Walker.Hash.finalize();
660*67e74705SXin Li }
661*67e74705SXin Li
skipRegionMappingForDecl(const Decl * D)662*67e74705SXin Li bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
663*67e74705SXin Li if (SkipCoverageMapping)
664*67e74705SXin Li return true;
665*67e74705SXin Li
666*67e74705SXin Li // Don't map the functions in system headers.
667*67e74705SXin Li const auto &SM = CGM.getContext().getSourceManager();
668*67e74705SXin Li auto Loc = D->getBody()->getLocStart();
669*67e74705SXin Li return SM.isInSystemHeader(Loc);
670*67e74705SXin Li }
671*67e74705SXin Li
emitCounterRegionMapping(const Decl * D)672*67e74705SXin Li void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
673*67e74705SXin Li if (skipRegionMappingForDecl(D))
674*67e74705SXin Li return;
675*67e74705SXin Li
676*67e74705SXin Li std::string CoverageMapping;
677*67e74705SXin Li llvm::raw_string_ostream OS(CoverageMapping);
678*67e74705SXin Li CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
679*67e74705SXin Li CGM.getContext().getSourceManager(),
680*67e74705SXin Li CGM.getLangOpts(), RegionCounterMap.get());
681*67e74705SXin Li MappingGen.emitCounterMapping(D, OS);
682*67e74705SXin Li OS.flush();
683*67e74705SXin Li
684*67e74705SXin Li if (CoverageMapping.empty())
685*67e74705SXin Li return;
686*67e74705SXin Li
687*67e74705SXin Li CGM.getCoverageMapping()->addFunctionMappingRecord(
688*67e74705SXin Li FuncNameVar, FuncName, FunctionHash, CoverageMapping);
689*67e74705SXin Li }
690*67e74705SXin Li
691*67e74705SXin Li void
emitEmptyCounterMapping(const Decl * D,StringRef Name,llvm::GlobalValue::LinkageTypes Linkage)692*67e74705SXin Li CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
693*67e74705SXin Li llvm::GlobalValue::LinkageTypes Linkage) {
694*67e74705SXin Li if (skipRegionMappingForDecl(D))
695*67e74705SXin Li return;
696*67e74705SXin Li
697*67e74705SXin Li std::string CoverageMapping;
698*67e74705SXin Li llvm::raw_string_ostream OS(CoverageMapping);
699*67e74705SXin Li CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
700*67e74705SXin Li CGM.getContext().getSourceManager(),
701*67e74705SXin Li CGM.getLangOpts());
702*67e74705SXin Li MappingGen.emitEmptyMapping(D, OS);
703*67e74705SXin Li OS.flush();
704*67e74705SXin Li
705*67e74705SXin Li if (CoverageMapping.empty())
706*67e74705SXin Li return;
707*67e74705SXin Li
708*67e74705SXin Li setFuncName(Name, Linkage);
709*67e74705SXin Li CGM.getCoverageMapping()->addFunctionMappingRecord(
710*67e74705SXin Li FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
711*67e74705SXin Li }
712*67e74705SXin Li
computeRegionCounts(const Decl * D)713*67e74705SXin Li void CodeGenPGO::computeRegionCounts(const Decl *D) {
714*67e74705SXin Li StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
715*67e74705SXin Li ComputeRegionCounts Walker(*StmtCountMap, *this);
716*67e74705SXin Li if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
717*67e74705SXin Li Walker.VisitFunctionDecl(FD);
718*67e74705SXin Li else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
719*67e74705SXin Li Walker.VisitObjCMethodDecl(MD);
720*67e74705SXin Li else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
721*67e74705SXin Li Walker.VisitBlockDecl(BD);
722*67e74705SXin Li else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
723*67e74705SXin Li Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
724*67e74705SXin Li }
725*67e74705SXin Li
726*67e74705SXin Li void
applyFunctionAttributes(llvm::IndexedInstrProfReader * PGOReader,llvm::Function * Fn)727*67e74705SXin Li CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
728*67e74705SXin Li llvm::Function *Fn) {
729*67e74705SXin Li if (!haveRegionCounts())
730*67e74705SXin Li return;
731*67e74705SXin Li
732*67e74705SXin Li uint64_t FunctionCount = getRegionCount(nullptr);
733*67e74705SXin Li Fn->setEntryCount(FunctionCount);
734*67e74705SXin Li }
735*67e74705SXin Li
emitCounterIncrement(CGBuilderTy & Builder,const Stmt * S)736*67e74705SXin Li void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S) {
737*67e74705SXin Li if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap)
738*67e74705SXin Li return;
739*67e74705SXin Li if (!Builder.GetInsertBlock())
740*67e74705SXin Li return;
741*67e74705SXin Li
742*67e74705SXin Li unsigned Counter = (*RegionCounterMap)[S];
743*67e74705SXin Li auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
744*67e74705SXin Li Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
745*67e74705SXin Li {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
746*67e74705SXin Li Builder.getInt64(FunctionHash),
747*67e74705SXin Li Builder.getInt32(NumRegionCounters),
748*67e74705SXin Li Builder.getInt32(Counter)});
749*67e74705SXin Li }
750*67e74705SXin Li
751*67e74705SXin Li // This method either inserts a call to the profile run-time during
752*67e74705SXin Li // instrumentation or puts profile data into metadata for PGO use.
valueProfile(CGBuilderTy & Builder,uint32_t ValueKind,llvm::Instruction * ValueSite,llvm::Value * ValuePtr)753*67e74705SXin Li void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
754*67e74705SXin Li llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
755*67e74705SXin Li
756*67e74705SXin Li if (!EnableValueProfiling)
757*67e74705SXin Li return;
758*67e74705SXin Li
759*67e74705SXin Li if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
760*67e74705SXin Li return;
761*67e74705SXin Li
762*67e74705SXin Li if (isa<llvm::Constant>(ValuePtr))
763*67e74705SXin Li return;
764*67e74705SXin Li
765*67e74705SXin Li bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
766*67e74705SXin Li if (InstrumentValueSites && RegionCounterMap) {
767*67e74705SXin Li auto BuilderInsertPoint = Builder.saveIP();
768*67e74705SXin Li Builder.SetInsertPoint(ValueSite);
769*67e74705SXin Li llvm::Value *Args[5] = {
770*67e74705SXin Li llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()),
771*67e74705SXin Li Builder.getInt64(FunctionHash),
772*67e74705SXin Li Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
773*67e74705SXin Li Builder.getInt32(ValueKind),
774*67e74705SXin Li Builder.getInt32(NumValueSites[ValueKind]++)
775*67e74705SXin Li };
776*67e74705SXin Li Builder.CreateCall(
777*67e74705SXin Li CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
778*67e74705SXin Li Builder.restoreIP(BuilderInsertPoint);
779*67e74705SXin Li return;
780*67e74705SXin Li }
781*67e74705SXin Li
782*67e74705SXin Li llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
783*67e74705SXin Li if (PGOReader && haveRegionCounts()) {
784*67e74705SXin Li // We record the top most called three functions at each call site.
785*67e74705SXin Li // Profile metadata contains "VP" string identifying this metadata
786*67e74705SXin Li // as value profiling data, then a uint32_t value for the value profiling
787*67e74705SXin Li // kind, a uint64_t value for the total number of times the call is
788*67e74705SXin Li // executed, followed by the function hash and execution count (uint64_t)
789*67e74705SXin Li // pairs for each function.
790*67e74705SXin Li if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
791*67e74705SXin Li return;
792*67e74705SXin Li
793*67e74705SXin Li llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
794*67e74705SXin Li (llvm::InstrProfValueKind)ValueKind,
795*67e74705SXin Li NumValueSites[ValueKind]);
796*67e74705SXin Li
797*67e74705SXin Li NumValueSites[ValueKind]++;
798*67e74705SXin Li }
799*67e74705SXin Li }
800*67e74705SXin Li
loadRegionCounts(llvm::IndexedInstrProfReader * PGOReader,bool IsInMainFile)801*67e74705SXin Li void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
802*67e74705SXin Li bool IsInMainFile) {
803*67e74705SXin Li CGM.getPGOStats().addVisited(IsInMainFile);
804*67e74705SXin Li RegionCounts.clear();
805*67e74705SXin Li llvm::Expected<llvm::InstrProfRecord> RecordExpected =
806*67e74705SXin Li PGOReader->getInstrProfRecord(FuncName, FunctionHash);
807*67e74705SXin Li if (auto E = RecordExpected.takeError()) {
808*67e74705SXin Li auto IPE = llvm::InstrProfError::take(std::move(E));
809*67e74705SXin Li if (IPE == llvm::instrprof_error::unknown_function)
810*67e74705SXin Li CGM.getPGOStats().addMissing(IsInMainFile);
811*67e74705SXin Li else if (IPE == llvm::instrprof_error::hash_mismatch)
812*67e74705SXin Li CGM.getPGOStats().addMismatched(IsInMainFile);
813*67e74705SXin Li else if (IPE == llvm::instrprof_error::malformed)
814*67e74705SXin Li // TODO: Consider a more specific warning for this case.
815*67e74705SXin Li CGM.getPGOStats().addMismatched(IsInMainFile);
816*67e74705SXin Li return;
817*67e74705SXin Li }
818*67e74705SXin Li ProfRecord =
819*67e74705SXin Li llvm::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
820*67e74705SXin Li RegionCounts = ProfRecord->Counts;
821*67e74705SXin Li }
822*67e74705SXin Li
823*67e74705SXin Li /// \brief Calculate what to divide by to scale weights.
824*67e74705SXin Li ///
825*67e74705SXin Li /// Given the maximum weight, calculate a divisor that will scale all the
826*67e74705SXin Li /// weights to strictly less than UINT32_MAX.
calculateWeightScale(uint64_t MaxWeight)827*67e74705SXin Li static uint64_t calculateWeightScale(uint64_t MaxWeight) {
828*67e74705SXin Li return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
829*67e74705SXin Li }
830*67e74705SXin Li
831*67e74705SXin Li /// \brief Scale an individual branch weight (and add 1).
832*67e74705SXin Li ///
833*67e74705SXin Li /// Scale a 64-bit weight down to 32-bits using \c Scale.
834*67e74705SXin Li ///
835*67e74705SXin Li /// According to Laplace's Rule of Succession, it is better to compute the
836*67e74705SXin Li /// weight based on the count plus 1, so universally add 1 to the value.
837*67e74705SXin Li ///
838*67e74705SXin Li /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
839*67e74705SXin Li /// greater than \c Weight.
scaleBranchWeight(uint64_t Weight,uint64_t Scale)840*67e74705SXin Li static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
841*67e74705SXin Li assert(Scale && "scale by 0?");
842*67e74705SXin Li uint64_t Scaled = Weight / Scale + 1;
843*67e74705SXin Li assert(Scaled <= UINT32_MAX && "overflow 32-bits");
844*67e74705SXin Li return Scaled;
845*67e74705SXin Li }
846*67e74705SXin Li
createProfileWeights(uint64_t TrueCount,uint64_t FalseCount)847*67e74705SXin Li llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
848*67e74705SXin Li uint64_t FalseCount) {
849*67e74705SXin Li // Check for empty weights.
850*67e74705SXin Li if (!TrueCount && !FalseCount)
851*67e74705SXin Li return nullptr;
852*67e74705SXin Li
853*67e74705SXin Li // Calculate how to scale down to 32-bits.
854*67e74705SXin Li uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
855*67e74705SXin Li
856*67e74705SXin Li llvm::MDBuilder MDHelper(CGM.getLLVMContext());
857*67e74705SXin Li return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
858*67e74705SXin Li scaleBranchWeight(FalseCount, Scale));
859*67e74705SXin Li }
860*67e74705SXin Li
861*67e74705SXin Li llvm::MDNode *
createProfileWeights(ArrayRef<uint64_t> Weights)862*67e74705SXin Li CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
863*67e74705SXin Li // We need at least two elements to create meaningful weights.
864*67e74705SXin Li if (Weights.size() < 2)
865*67e74705SXin Li return nullptr;
866*67e74705SXin Li
867*67e74705SXin Li // Check for empty weights.
868*67e74705SXin Li uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
869*67e74705SXin Li if (MaxWeight == 0)
870*67e74705SXin Li return nullptr;
871*67e74705SXin Li
872*67e74705SXin Li // Calculate how to scale down to 32-bits.
873*67e74705SXin Li uint64_t Scale = calculateWeightScale(MaxWeight);
874*67e74705SXin Li
875*67e74705SXin Li SmallVector<uint32_t, 16> ScaledWeights;
876*67e74705SXin Li ScaledWeights.reserve(Weights.size());
877*67e74705SXin Li for (uint64_t W : Weights)
878*67e74705SXin Li ScaledWeights.push_back(scaleBranchWeight(W, Scale));
879*67e74705SXin Li
880*67e74705SXin Li llvm::MDBuilder MDHelper(CGM.getLLVMContext());
881*67e74705SXin Li return MDHelper.createBranchWeights(ScaledWeights);
882*67e74705SXin Li }
883*67e74705SXin Li
createProfileWeightsForLoop(const Stmt * Cond,uint64_t LoopCount)884*67e74705SXin Li llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
885*67e74705SXin Li uint64_t LoopCount) {
886*67e74705SXin Li if (!PGO.haveRegionCounts())
887*67e74705SXin Li return nullptr;
888*67e74705SXin Li Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
889*67e74705SXin Li assert(CondCount.hasValue() && "missing expected loop condition count");
890*67e74705SXin Li if (*CondCount == 0)
891*67e74705SXin Li return nullptr;
892*67e74705SXin Li return createProfileWeights(LoopCount,
893*67e74705SXin Li std::max(*CondCount, LoopCount) - LoopCount);
894*67e74705SXin Li }
895