1*0b57cec5SDimitry Andric //===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // Instrumentation-based profile-guided optimization
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "CodeGenPGO.h"
14*0b57cec5SDimitry Andric #include "CodeGenFunction.h"
15*0b57cec5SDimitry Andric #include "CoverageMappingGen.h"
16*0b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
17*0b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
18*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
19*0b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
20480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
21*0b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
22*0b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
23*0b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
24*0b57cec5SDimitry Andric 
25*0b57cec5SDimitry Andric static llvm::cl::opt<bool>
26*0b57cec5SDimitry Andric     EnableValueProfiling("enable-value-profiling", llvm::cl::ZeroOrMore,
27*0b57cec5SDimitry Andric                          llvm::cl::desc("Enable value profiling"),
28*0b57cec5SDimitry Andric                          llvm::cl::Hidden, llvm::cl::init(false));
29*0b57cec5SDimitry Andric 
30*0b57cec5SDimitry Andric using namespace clang;
31*0b57cec5SDimitry Andric using namespace CodeGen;
32*0b57cec5SDimitry Andric 
33*0b57cec5SDimitry Andric void CodeGenPGO::setFuncName(StringRef Name,
34*0b57cec5SDimitry Andric                              llvm::GlobalValue::LinkageTypes Linkage) {
35*0b57cec5SDimitry Andric   llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
36*0b57cec5SDimitry Andric   FuncName = llvm::getPGOFuncName(
37*0b57cec5SDimitry Andric       Name, Linkage, CGM.getCodeGenOpts().MainFileName,
38*0b57cec5SDimitry Andric       PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
39*0b57cec5SDimitry Andric 
40*0b57cec5SDimitry Andric   // If we're generating a profile, create a variable for the name.
41*0b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().hasProfileClangInstr())
42*0b57cec5SDimitry Andric     FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
43*0b57cec5SDimitry Andric }
44*0b57cec5SDimitry Andric 
45*0b57cec5SDimitry Andric void CodeGenPGO::setFuncName(llvm::Function *Fn) {
46*0b57cec5SDimitry Andric   setFuncName(Fn->getName(), Fn->getLinkage());
47*0b57cec5SDimitry Andric   // Create PGOFuncName meta data.
48*0b57cec5SDimitry Andric   llvm::createPGOFuncNameMetadata(*Fn, FuncName);
49*0b57cec5SDimitry Andric }
50*0b57cec5SDimitry Andric 
51*0b57cec5SDimitry Andric /// The version of the PGO hash algorithm.
52*0b57cec5SDimitry Andric enum PGOHashVersion : unsigned {
53*0b57cec5SDimitry Andric   PGO_HASH_V1,
54*0b57cec5SDimitry Andric   PGO_HASH_V2,
555ffd83dbSDimitry Andric   PGO_HASH_V3,
56*0b57cec5SDimitry Andric 
57*0b57cec5SDimitry Andric   // Keep this set to the latest hash version.
585ffd83dbSDimitry Andric   PGO_HASH_LATEST = PGO_HASH_V3
59*0b57cec5SDimitry Andric };
60*0b57cec5SDimitry Andric 
61*0b57cec5SDimitry Andric namespace {
62*0b57cec5SDimitry Andric /// Stable hasher for PGO region counters.
63*0b57cec5SDimitry Andric ///
64*0b57cec5SDimitry Andric /// PGOHash produces a stable hash of a given function's control flow.
65*0b57cec5SDimitry Andric ///
66*0b57cec5SDimitry Andric /// Changing the output of this hash will invalidate all previously generated
67*0b57cec5SDimitry Andric /// profiles -- i.e., don't do it.
68*0b57cec5SDimitry Andric ///
69*0b57cec5SDimitry Andric /// \note  When this hash does eventually change (years?), we still need to
70*0b57cec5SDimitry Andric /// support old hashes.  We'll need to pull in the version number from the
71*0b57cec5SDimitry Andric /// profile data format and use the matching hash function.
72*0b57cec5SDimitry Andric class PGOHash {
73*0b57cec5SDimitry Andric   uint64_t Working;
74*0b57cec5SDimitry Andric   unsigned Count;
75*0b57cec5SDimitry Andric   PGOHashVersion HashVersion;
76*0b57cec5SDimitry Andric   llvm::MD5 MD5;
77*0b57cec5SDimitry Andric 
78*0b57cec5SDimitry Andric   static const int NumBitsPerType = 6;
79*0b57cec5SDimitry Andric   static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
80*0b57cec5SDimitry Andric   static const unsigned TooBig = 1u << NumBitsPerType;
81*0b57cec5SDimitry Andric 
82*0b57cec5SDimitry Andric public:
83*0b57cec5SDimitry Andric   /// Hash values for AST nodes.
84*0b57cec5SDimitry Andric   ///
85*0b57cec5SDimitry Andric   /// Distinct values for AST nodes that have region counters attached.
86*0b57cec5SDimitry Andric   ///
87*0b57cec5SDimitry Andric   /// These values must be stable.  All new members must be added at the end,
88*0b57cec5SDimitry Andric   /// and no members should be removed.  Changing the enumeration value for an
89*0b57cec5SDimitry Andric   /// AST node will affect the hash of every function that contains that node.
90*0b57cec5SDimitry Andric   enum HashType : unsigned char {
91*0b57cec5SDimitry Andric     None = 0,
92*0b57cec5SDimitry Andric     LabelStmt = 1,
93*0b57cec5SDimitry Andric     WhileStmt,
94*0b57cec5SDimitry Andric     DoStmt,
95*0b57cec5SDimitry Andric     ForStmt,
96*0b57cec5SDimitry Andric     CXXForRangeStmt,
97*0b57cec5SDimitry Andric     ObjCForCollectionStmt,
98*0b57cec5SDimitry Andric     SwitchStmt,
99*0b57cec5SDimitry Andric     CaseStmt,
100*0b57cec5SDimitry Andric     DefaultStmt,
101*0b57cec5SDimitry Andric     IfStmt,
102*0b57cec5SDimitry Andric     CXXTryStmt,
103*0b57cec5SDimitry Andric     CXXCatchStmt,
104*0b57cec5SDimitry Andric     ConditionalOperator,
105*0b57cec5SDimitry Andric     BinaryOperatorLAnd,
106*0b57cec5SDimitry Andric     BinaryOperatorLOr,
107*0b57cec5SDimitry Andric     BinaryConditionalOperator,
108*0b57cec5SDimitry Andric     // The preceding values are available with PGO_HASH_V1.
109*0b57cec5SDimitry Andric 
110*0b57cec5SDimitry Andric     EndOfScope,
111*0b57cec5SDimitry Andric     IfThenBranch,
112*0b57cec5SDimitry Andric     IfElseBranch,
113*0b57cec5SDimitry Andric     GotoStmt,
114*0b57cec5SDimitry Andric     IndirectGotoStmt,
115*0b57cec5SDimitry Andric     BreakStmt,
116*0b57cec5SDimitry Andric     ContinueStmt,
117*0b57cec5SDimitry Andric     ReturnStmt,
118*0b57cec5SDimitry Andric     ThrowExpr,
119*0b57cec5SDimitry Andric     UnaryOperatorLNot,
120*0b57cec5SDimitry Andric     BinaryOperatorLT,
121*0b57cec5SDimitry Andric     BinaryOperatorGT,
122*0b57cec5SDimitry Andric     BinaryOperatorLE,
123*0b57cec5SDimitry Andric     BinaryOperatorGE,
124*0b57cec5SDimitry Andric     BinaryOperatorEQ,
125*0b57cec5SDimitry Andric     BinaryOperatorNE,
1265ffd83dbSDimitry Andric     // The preceding values are available since PGO_HASH_V2.
127*0b57cec5SDimitry Andric 
128*0b57cec5SDimitry Andric     // Keep this last.  It's for the static assert that follows.
129*0b57cec5SDimitry Andric     LastHashType
130*0b57cec5SDimitry Andric   };
131*0b57cec5SDimitry Andric   static_assert(LastHashType <= TooBig, "Too many types in HashType");
132*0b57cec5SDimitry Andric 
133*0b57cec5SDimitry Andric   PGOHash(PGOHashVersion HashVersion)
134*0b57cec5SDimitry Andric       : Working(0), Count(0), HashVersion(HashVersion), MD5() {}
135*0b57cec5SDimitry Andric   void combine(HashType Type);
136*0b57cec5SDimitry Andric   uint64_t finalize();
137*0b57cec5SDimitry Andric   PGOHashVersion getHashVersion() const { return HashVersion; }
138*0b57cec5SDimitry Andric };
139*0b57cec5SDimitry Andric const int PGOHash::NumBitsPerType;
140*0b57cec5SDimitry Andric const unsigned PGOHash::NumTypesPerWord;
141*0b57cec5SDimitry Andric const unsigned PGOHash::TooBig;
142*0b57cec5SDimitry Andric 
143*0b57cec5SDimitry Andric /// Get the PGO hash version used in the given indexed profile.
144*0b57cec5SDimitry Andric static PGOHashVersion getPGOHashVersion(llvm::IndexedInstrProfReader *PGOReader,
145*0b57cec5SDimitry Andric                                         CodeGenModule &CGM) {
146*0b57cec5SDimitry Andric   if (PGOReader->getVersion() <= 4)
147*0b57cec5SDimitry Andric     return PGO_HASH_V1;
1485ffd83dbSDimitry Andric   if (PGOReader->getVersion() <= 5)
149*0b57cec5SDimitry Andric     return PGO_HASH_V2;
1505ffd83dbSDimitry Andric   return PGO_HASH_V3;
151*0b57cec5SDimitry Andric }
152*0b57cec5SDimitry Andric 
153*0b57cec5SDimitry Andric /// A RecursiveASTVisitor that fills a map of statements to PGO counters.
154*0b57cec5SDimitry Andric struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
155*0b57cec5SDimitry Andric   using Base = RecursiveASTVisitor<MapRegionCounters>;
156*0b57cec5SDimitry Andric 
157*0b57cec5SDimitry Andric   /// The next counter value to assign.
158*0b57cec5SDimitry Andric   unsigned NextCounter;
159*0b57cec5SDimitry Andric   /// The function hash.
160*0b57cec5SDimitry Andric   PGOHash Hash;
161*0b57cec5SDimitry Andric   /// The map of statements to counters.
162*0b57cec5SDimitry Andric   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
163*0b57cec5SDimitry Andric 
164*0b57cec5SDimitry Andric   MapRegionCounters(PGOHashVersion HashVersion,
165*0b57cec5SDimitry Andric                     llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
166*0b57cec5SDimitry Andric       : NextCounter(0), Hash(HashVersion), CounterMap(CounterMap) {}
167*0b57cec5SDimitry Andric 
168*0b57cec5SDimitry Andric   // Blocks and lambdas are handled as separate functions, so we need not
169*0b57cec5SDimitry Andric   // traverse them in the parent context.
170*0b57cec5SDimitry Andric   bool TraverseBlockExpr(BlockExpr *BE) { return true; }
171*0b57cec5SDimitry Andric   bool TraverseLambdaExpr(LambdaExpr *LE) {
172*0b57cec5SDimitry Andric     // Traverse the captures, but not the body.
173480093f4SDimitry Andric     for (auto C : zip(LE->captures(), LE->capture_inits()))
174*0b57cec5SDimitry Andric       TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
175*0b57cec5SDimitry Andric     return true;
176*0b57cec5SDimitry Andric   }
177*0b57cec5SDimitry Andric   bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
178*0b57cec5SDimitry Andric 
179*0b57cec5SDimitry Andric   bool VisitDecl(const Decl *D) {
180*0b57cec5SDimitry Andric     switch (D->getKind()) {
181*0b57cec5SDimitry Andric     default:
182*0b57cec5SDimitry Andric       break;
183*0b57cec5SDimitry Andric     case Decl::Function:
184*0b57cec5SDimitry Andric     case Decl::CXXMethod:
185*0b57cec5SDimitry Andric     case Decl::CXXConstructor:
186*0b57cec5SDimitry Andric     case Decl::CXXDestructor:
187*0b57cec5SDimitry Andric     case Decl::CXXConversion:
188*0b57cec5SDimitry Andric     case Decl::ObjCMethod:
189*0b57cec5SDimitry Andric     case Decl::Block:
190*0b57cec5SDimitry Andric     case Decl::Captured:
191*0b57cec5SDimitry Andric       CounterMap[D->getBody()] = NextCounter++;
192*0b57cec5SDimitry Andric       break;
193*0b57cec5SDimitry Andric     }
194*0b57cec5SDimitry Andric     return true;
195*0b57cec5SDimitry Andric   }
196*0b57cec5SDimitry Andric 
197*0b57cec5SDimitry Andric   /// If \p S gets a fresh counter, update the counter mappings. Return the
198*0b57cec5SDimitry Andric   /// V1 hash of \p S.
199*0b57cec5SDimitry Andric   PGOHash::HashType updateCounterMappings(Stmt *S) {
200*0b57cec5SDimitry Andric     auto Type = getHashType(PGO_HASH_V1, S);
201*0b57cec5SDimitry Andric     if (Type != PGOHash::None)
202*0b57cec5SDimitry Andric       CounterMap[S] = NextCounter++;
203*0b57cec5SDimitry Andric     return Type;
204*0b57cec5SDimitry Andric   }
205*0b57cec5SDimitry Andric 
206*0b57cec5SDimitry Andric   /// Include \p S in the function hash.
207*0b57cec5SDimitry Andric   bool VisitStmt(Stmt *S) {
208*0b57cec5SDimitry Andric     auto Type = updateCounterMappings(S);
209*0b57cec5SDimitry Andric     if (Hash.getHashVersion() != PGO_HASH_V1)
210*0b57cec5SDimitry Andric       Type = getHashType(Hash.getHashVersion(), S);
211*0b57cec5SDimitry Andric     if (Type != PGOHash::None)
212*0b57cec5SDimitry Andric       Hash.combine(Type);
213*0b57cec5SDimitry Andric     return true;
214*0b57cec5SDimitry Andric   }
215*0b57cec5SDimitry Andric 
216*0b57cec5SDimitry Andric   bool TraverseIfStmt(IfStmt *If) {
217*0b57cec5SDimitry Andric     // If we used the V1 hash, use the default traversal.
218*0b57cec5SDimitry Andric     if (Hash.getHashVersion() == PGO_HASH_V1)
219*0b57cec5SDimitry Andric       return Base::TraverseIfStmt(If);
220*0b57cec5SDimitry Andric 
221*0b57cec5SDimitry Andric     // Otherwise, keep track of which branch we're in while traversing.
222*0b57cec5SDimitry Andric     VisitStmt(If);
223*0b57cec5SDimitry Andric     for (Stmt *CS : If->children()) {
224*0b57cec5SDimitry Andric       if (!CS)
225*0b57cec5SDimitry Andric         continue;
226*0b57cec5SDimitry Andric       if (CS == If->getThen())
227*0b57cec5SDimitry Andric         Hash.combine(PGOHash::IfThenBranch);
228*0b57cec5SDimitry Andric       else if (CS == If->getElse())
229*0b57cec5SDimitry Andric         Hash.combine(PGOHash::IfElseBranch);
230*0b57cec5SDimitry Andric       TraverseStmt(CS);
231*0b57cec5SDimitry Andric     }
232*0b57cec5SDimitry Andric     Hash.combine(PGOHash::EndOfScope);
233*0b57cec5SDimitry Andric     return true;
234*0b57cec5SDimitry Andric   }
235*0b57cec5SDimitry Andric 
236*0b57cec5SDimitry Andric // If the statement type \p N is nestable, and its nesting impacts profile
237*0b57cec5SDimitry Andric // stability, define a custom traversal which tracks the end of the statement
238*0b57cec5SDimitry Andric // in the hash (provided we're not using the V1 hash).
239*0b57cec5SDimitry Andric #define DEFINE_NESTABLE_TRAVERSAL(N)                                           \
240*0b57cec5SDimitry Andric   bool Traverse##N(N *S) {                                                     \
241*0b57cec5SDimitry Andric     Base::Traverse##N(S);                                                      \
242*0b57cec5SDimitry Andric     if (Hash.getHashVersion() != PGO_HASH_V1)                                  \
243*0b57cec5SDimitry Andric       Hash.combine(PGOHash::EndOfScope);                                       \
244*0b57cec5SDimitry Andric     return true;                                                               \
245*0b57cec5SDimitry Andric   }
246*0b57cec5SDimitry Andric 
247*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(WhileStmt)
248*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(DoStmt)
249*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(ForStmt)
250*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(CXXForRangeStmt)
251*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(ObjCForCollectionStmt)
252*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(CXXTryStmt)
253*0b57cec5SDimitry Andric   DEFINE_NESTABLE_TRAVERSAL(CXXCatchStmt)
254*0b57cec5SDimitry Andric 
255*0b57cec5SDimitry Andric   /// Get version \p HashVersion of the PGO hash for \p S.
256*0b57cec5SDimitry Andric   PGOHash::HashType getHashType(PGOHashVersion HashVersion, const Stmt *S) {
257*0b57cec5SDimitry Andric     switch (S->getStmtClass()) {
258*0b57cec5SDimitry Andric     default:
259*0b57cec5SDimitry Andric       break;
260*0b57cec5SDimitry Andric     case Stmt::LabelStmtClass:
261*0b57cec5SDimitry Andric       return PGOHash::LabelStmt;
262*0b57cec5SDimitry Andric     case Stmt::WhileStmtClass:
263*0b57cec5SDimitry Andric       return PGOHash::WhileStmt;
264*0b57cec5SDimitry Andric     case Stmt::DoStmtClass:
265*0b57cec5SDimitry Andric       return PGOHash::DoStmt;
266*0b57cec5SDimitry Andric     case Stmt::ForStmtClass:
267*0b57cec5SDimitry Andric       return PGOHash::ForStmt;
268*0b57cec5SDimitry Andric     case Stmt::CXXForRangeStmtClass:
269*0b57cec5SDimitry Andric       return PGOHash::CXXForRangeStmt;
270*0b57cec5SDimitry Andric     case Stmt::ObjCForCollectionStmtClass:
271*0b57cec5SDimitry Andric       return PGOHash::ObjCForCollectionStmt;
272*0b57cec5SDimitry Andric     case Stmt::SwitchStmtClass:
273*0b57cec5SDimitry Andric       return PGOHash::SwitchStmt;
274*0b57cec5SDimitry Andric     case Stmt::CaseStmtClass:
275*0b57cec5SDimitry Andric       return PGOHash::CaseStmt;
276*0b57cec5SDimitry Andric     case Stmt::DefaultStmtClass:
277*0b57cec5SDimitry Andric       return PGOHash::DefaultStmt;
278*0b57cec5SDimitry Andric     case Stmt::IfStmtClass:
279*0b57cec5SDimitry Andric       return PGOHash::IfStmt;
280*0b57cec5SDimitry Andric     case Stmt::CXXTryStmtClass:
281*0b57cec5SDimitry Andric       return PGOHash::CXXTryStmt;
282*0b57cec5SDimitry Andric     case Stmt::CXXCatchStmtClass:
283*0b57cec5SDimitry Andric       return PGOHash::CXXCatchStmt;
284*0b57cec5SDimitry Andric     case Stmt::ConditionalOperatorClass:
285*0b57cec5SDimitry Andric       return PGOHash::ConditionalOperator;
286*0b57cec5SDimitry Andric     case Stmt::BinaryConditionalOperatorClass:
287*0b57cec5SDimitry Andric       return PGOHash::BinaryConditionalOperator;
288*0b57cec5SDimitry Andric     case Stmt::BinaryOperatorClass: {
289*0b57cec5SDimitry Andric       const BinaryOperator *BO = cast<BinaryOperator>(S);
290*0b57cec5SDimitry Andric       if (BO->getOpcode() == BO_LAnd)
291*0b57cec5SDimitry Andric         return PGOHash::BinaryOperatorLAnd;
292*0b57cec5SDimitry Andric       if (BO->getOpcode() == BO_LOr)
293*0b57cec5SDimitry Andric         return PGOHash::BinaryOperatorLOr;
2945ffd83dbSDimitry Andric       if (HashVersion >= PGO_HASH_V2) {
295*0b57cec5SDimitry Andric         switch (BO->getOpcode()) {
296*0b57cec5SDimitry Andric         default:
297*0b57cec5SDimitry Andric           break;
298*0b57cec5SDimitry Andric         case BO_LT:
299*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorLT;
300*0b57cec5SDimitry Andric         case BO_GT:
301*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorGT;
302*0b57cec5SDimitry Andric         case BO_LE:
303*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorLE;
304*0b57cec5SDimitry Andric         case BO_GE:
305*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorGE;
306*0b57cec5SDimitry Andric         case BO_EQ:
307*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorEQ;
308*0b57cec5SDimitry Andric         case BO_NE:
309*0b57cec5SDimitry Andric           return PGOHash::BinaryOperatorNE;
310*0b57cec5SDimitry Andric         }
311*0b57cec5SDimitry Andric       }
312*0b57cec5SDimitry Andric       break;
313*0b57cec5SDimitry Andric     }
314*0b57cec5SDimitry Andric     }
315*0b57cec5SDimitry Andric 
3165ffd83dbSDimitry Andric     if (HashVersion >= PGO_HASH_V2) {
317*0b57cec5SDimitry Andric       switch (S->getStmtClass()) {
318*0b57cec5SDimitry Andric       default:
319*0b57cec5SDimitry Andric         break;
320*0b57cec5SDimitry Andric       case Stmt::GotoStmtClass:
321*0b57cec5SDimitry Andric         return PGOHash::GotoStmt;
322*0b57cec5SDimitry Andric       case Stmt::IndirectGotoStmtClass:
323*0b57cec5SDimitry Andric         return PGOHash::IndirectGotoStmt;
324*0b57cec5SDimitry Andric       case Stmt::BreakStmtClass:
325*0b57cec5SDimitry Andric         return PGOHash::BreakStmt;
326*0b57cec5SDimitry Andric       case Stmt::ContinueStmtClass:
327*0b57cec5SDimitry Andric         return PGOHash::ContinueStmt;
328*0b57cec5SDimitry Andric       case Stmt::ReturnStmtClass:
329*0b57cec5SDimitry Andric         return PGOHash::ReturnStmt;
330*0b57cec5SDimitry Andric       case Stmt::CXXThrowExprClass:
331*0b57cec5SDimitry Andric         return PGOHash::ThrowExpr;
332*0b57cec5SDimitry Andric       case Stmt::UnaryOperatorClass: {
333*0b57cec5SDimitry Andric         const UnaryOperator *UO = cast<UnaryOperator>(S);
334*0b57cec5SDimitry Andric         if (UO->getOpcode() == UO_LNot)
335*0b57cec5SDimitry Andric           return PGOHash::UnaryOperatorLNot;
336*0b57cec5SDimitry Andric         break;
337*0b57cec5SDimitry Andric       }
338*0b57cec5SDimitry Andric       }
339*0b57cec5SDimitry Andric     }
340*0b57cec5SDimitry Andric 
341*0b57cec5SDimitry Andric     return PGOHash::None;
342*0b57cec5SDimitry Andric   }
343*0b57cec5SDimitry Andric };
344*0b57cec5SDimitry Andric 
345*0b57cec5SDimitry Andric /// A StmtVisitor that propagates the raw counts through the AST and
346*0b57cec5SDimitry Andric /// records the count at statements where the value may change.
347*0b57cec5SDimitry Andric struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
348*0b57cec5SDimitry Andric   /// PGO state.
349*0b57cec5SDimitry Andric   CodeGenPGO &PGO;
350*0b57cec5SDimitry Andric 
351*0b57cec5SDimitry Andric   /// A flag that is set when the current count should be recorded on the
352*0b57cec5SDimitry Andric   /// next statement, such as at the exit of a loop.
353*0b57cec5SDimitry Andric   bool RecordNextStmtCount;
354*0b57cec5SDimitry Andric 
355*0b57cec5SDimitry Andric   /// The count at the current location in the traversal.
356*0b57cec5SDimitry Andric   uint64_t CurrentCount;
357*0b57cec5SDimitry Andric 
358*0b57cec5SDimitry Andric   /// The map of statements to count values.
359*0b57cec5SDimitry Andric   llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
360*0b57cec5SDimitry Andric 
361*0b57cec5SDimitry Andric   /// BreakContinueStack - Keep counts of breaks and continues inside loops.
362*0b57cec5SDimitry Andric   struct BreakContinue {
363*0b57cec5SDimitry Andric     uint64_t BreakCount;
364*0b57cec5SDimitry Andric     uint64_t ContinueCount;
365*0b57cec5SDimitry Andric     BreakContinue() : BreakCount(0), ContinueCount(0) {}
366*0b57cec5SDimitry Andric   };
367*0b57cec5SDimitry Andric   SmallVector<BreakContinue, 8> BreakContinueStack;
368*0b57cec5SDimitry Andric 
369*0b57cec5SDimitry Andric   ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
370*0b57cec5SDimitry Andric                       CodeGenPGO &PGO)
371*0b57cec5SDimitry Andric       : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
372*0b57cec5SDimitry Andric 
373*0b57cec5SDimitry Andric   void RecordStmtCount(const Stmt *S) {
374*0b57cec5SDimitry Andric     if (RecordNextStmtCount) {
375*0b57cec5SDimitry Andric       CountMap[S] = CurrentCount;
376*0b57cec5SDimitry Andric       RecordNextStmtCount = false;
377*0b57cec5SDimitry Andric     }
378*0b57cec5SDimitry Andric   }
379*0b57cec5SDimitry Andric 
380*0b57cec5SDimitry Andric   /// Set and return the current count.
381*0b57cec5SDimitry Andric   uint64_t setCount(uint64_t Count) {
382*0b57cec5SDimitry Andric     CurrentCount = Count;
383*0b57cec5SDimitry Andric     return Count;
384*0b57cec5SDimitry Andric   }
385*0b57cec5SDimitry Andric 
386*0b57cec5SDimitry Andric   void VisitStmt(const Stmt *S) {
387*0b57cec5SDimitry Andric     RecordStmtCount(S);
388*0b57cec5SDimitry Andric     for (const Stmt *Child : S->children())
389*0b57cec5SDimitry Andric       if (Child)
390*0b57cec5SDimitry Andric         this->Visit(Child);
391*0b57cec5SDimitry Andric   }
392*0b57cec5SDimitry Andric 
393*0b57cec5SDimitry Andric   void VisitFunctionDecl(const FunctionDecl *D) {
394*0b57cec5SDimitry Andric     // Counter tracks entry to the function body.
395*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
396*0b57cec5SDimitry Andric     CountMap[D->getBody()] = BodyCount;
397*0b57cec5SDimitry Andric     Visit(D->getBody());
398*0b57cec5SDimitry Andric   }
399*0b57cec5SDimitry Andric 
400*0b57cec5SDimitry Andric   // Skip lambda expressions. We visit these as FunctionDecls when we're
401*0b57cec5SDimitry Andric   // generating them and aren't interested in the body when generating a
402*0b57cec5SDimitry Andric   // parent context.
403*0b57cec5SDimitry Andric   void VisitLambdaExpr(const LambdaExpr *LE) {}
404*0b57cec5SDimitry Andric 
405*0b57cec5SDimitry Andric   void VisitCapturedDecl(const CapturedDecl *D) {
406*0b57cec5SDimitry Andric     // Counter tracks entry to the capture body.
407*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
408*0b57cec5SDimitry Andric     CountMap[D->getBody()] = BodyCount;
409*0b57cec5SDimitry Andric     Visit(D->getBody());
410*0b57cec5SDimitry Andric   }
411*0b57cec5SDimitry Andric 
412*0b57cec5SDimitry Andric   void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
413*0b57cec5SDimitry Andric     // Counter tracks entry to the method body.
414*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
415*0b57cec5SDimitry Andric     CountMap[D->getBody()] = BodyCount;
416*0b57cec5SDimitry Andric     Visit(D->getBody());
417*0b57cec5SDimitry Andric   }
418*0b57cec5SDimitry Andric 
419*0b57cec5SDimitry Andric   void VisitBlockDecl(const BlockDecl *D) {
420*0b57cec5SDimitry Andric     // Counter tracks entry to the block body.
421*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
422*0b57cec5SDimitry Andric     CountMap[D->getBody()] = BodyCount;
423*0b57cec5SDimitry Andric     Visit(D->getBody());
424*0b57cec5SDimitry Andric   }
425*0b57cec5SDimitry Andric 
426*0b57cec5SDimitry Andric   void VisitReturnStmt(const ReturnStmt *S) {
427*0b57cec5SDimitry Andric     RecordStmtCount(S);
428*0b57cec5SDimitry Andric     if (S->getRetValue())
429*0b57cec5SDimitry Andric       Visit(S->getRetValue());
430*0b57cec5SDimitry Andric     CurrentCount = 0;
431*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
432*0b57cec5SDimitry Andric   }
433*0b57cec5SDimitry Andric 
434*0b57cec5SDimitry Andric   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
435*0b57cec5SDimitry Andric     RecordStmtCount(E);
436*0b57cec5SDimitry Andric     if (E->getSubExpr())
437*0b57cec5SDimitry Andric       Visit(E->getSubExpr());
438*0b57cec5SDimitry Andric     CurrentCount = 0;
439*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
440*0b57cec5SDimitry Andric   }
441*0b57cec5SDimitry Andric 
442*0b57cec5SDimitry Andric   void VisitGotoStmt(const GotoStmt *S) {
443*0b57cec5SDimitry Andric     RecordStmtCount(S);
444*0b57cec5SDimitry Andric     CurrentCount = 0;
445*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
446*0b57cec5SDimitry Andric   }
447*0b57cec5SDimitry Andric 
448*0b57cec5SDimitry Andric   void VisitLabelStmt(const LabelStmt *S) {
449*0b57cec5SDimitry Andric     RecordNextStmtCount = false;
450*0b57cec5SDimitry Andric     // Counter tracks the block following the label.
451*0b57cec5SDimitry Andric     uint64_t BlockCount = setCount(PGO.getRegionCount(S));
452*0b57cec5SDimitry Andric     CountMap[S] = BlockCount;
453*0b57cec5SDimitry Andric     Visit(S->getSubStmt());
454*0b57cec5SDimitry Andric   }
455*0b57cec5SDimitry Andric 
456*0b57cec5SDimitry Andric   void VisitBreakStmt(const BreakStmt *S) {
457*0b57cec5SDimitry Andric     RecordStmtCount(S);
458*0b57cec5SDimitry Andric     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
459*0b57cec5SDimitry Andric     BreakContinueStack.back().BreakCount += CurrentCount;
460*0b57cec5SDimitry Andric     CurrentCount = 0;
461*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
462*0b57cec5SDimitry Andric   }
463*0b57cec5SDimitry Andric 
464*0b57cec5SDimitry Andric   void VisitContinueStmt(const ContinueStmt *S) {
465*0b57cec5SDimitry Andric     RecordStmtCount(S);
466*0b57cec5SDimitry Andric     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
467*0b57cec5SDimitry Andric     BreakContinueStack.back().ContinueCount += CurrentCount;
468*0b57cec5SDimitry Andric     CurrentCount = 0;
469*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
470*0b57cec5SDimitry Andric   }
471*0b57cec5SDimitry Andric 
472*0b57cec5SDimitry Andric   void VisitWhileStmt(const WhileStmt *S) {
473*0b57cec5SDimitry Andric     RecordStmtCount(S);
474*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
475*0b57cec5SDimitry Andric 
476*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
477*0b57cec5SDimitry Andric     // Visit the body region first so the break/continue adjustments can be
478*0b57cec5SDimitry Andric     // included when visiting the condition.
479*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
480*0b57cec5SDimitry Andric     CountMap[S->getBody()] = CurrentCount;
481*0b57cec5SDimitry Andric     Visit(S->getBody());
482*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
483*0b57cec5SDimitry Andric 
484*0b57cec5SDimitry Andric     // ...then go back and propagate counts through the condition. The count
485*0b57cec5SDimitry Andric     // at the start of the condition is the sum of the incoming edges,
486*0b57cec5SDimitry Andric     // the backedge from the end of the loop body, and the edges from
487*0b57cec5SDimitry Andric     // continue statements.
488*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
489*0b57cec5SDimitry Andric     uint64_t CondCount =
490*0b57cec5SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
491*0b57cec5SDimitry Andric     CountMap[S->getCond()] = CondCount;
492*0b57cec5SDimitry Andric     Visit(S->getCond());
493*0b57cec5SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
494*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
495*0b57cec5SDimitry Andric   }
496*0b57cec5SDimitry Andric 
497*0b57cec5SDimitry Andric   void VisitDoStmt(const DoStmt *S) {
498*0b57cec5SDimitry Andric     RecordStmtCount(S);
499*0b57cec5SDimitry Andric     uint64_t LoopCount = PGO.getRegionCount(S);
500*0b57cec5SDimitry Andric 
501*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
502*0b57cec5SDimitry Andric     // The count doesn't include the fallthrough from the parent scope. Add it.
503*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(LoopCount + CurrentCount);
504*0b57cec5SDimitry Andric     CountMap[S->getBody()] = BodyCount;
505*0b57cec5SDimitry Andric     Visit(S->getBody());
506*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
507*0b57cec5SDimitry Andric 
508*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
509*0b57cec5SDimitry Andric     // The count at the start of the condition is equal to the count at the
510*0b57cec5SDimitry Andric     // end of the body, plus any continues.
511*0b57cec5SDimitry Andric     uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
512*0b57cec5SDimitry Andric     CountMap[S->getCond()] = CondCount;
513*0b57cec5SDimitry Andric     Visit(S->getCond());
514*0b57cec5SDimitry Andric     setCount(BC.BreakCount + CondCount - LoopCount);
515*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
516*0b57cec5SDimitry Andric   }
517*0b57cec5SDimitry Andric 
518*0b57cec5SDimitry Andric   void VisitForStmt(const ForStmt *S) {
519*0b57cec5SDimitry Andric     RecordStmtCount(S);
520*0b57cec5SDimitry Andric     if (S->getInit())
521*0b57cec5SDimitry Andric       Visit(S->getInit());
522*0b57cec5SDimitry Andric 
523*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
524*0b57cec5SDimitry Andric 
525*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
526*0b57cec5SDimitry Andric     // Visit the body region first. (This is basically the same as a while
527*0b57cec5SDimitry Andric     // loop; see further comments in VisitWhileStmt.)
528*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
529*0b57cec5SDimitry Andric     CountMap[S->getBody()] = BodyCount;
530*0b57cec5SDimitry Andric     Visit(S->getBody());
531*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
532*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
533*0b57cec5SDimitry Andric 
534*0b57cec5SDimitry Andric     // The increment is essentially part of the body but it needs to include
535*0b57cec5SDimitry Andric     // the count for all the continue statements.
536*0b57cec5SDimitry Andric     if (S->getInc()) {
537*0b57cec5SDimitry Andric       uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
538*0b57cec5SDimitry Andric       CountMap[S->getInc()] = IncCount;
539*0b57cec5SDimitry Andric       Visit(S->getInc());
540*0b57cec5SDimitry Andric     }
541*0b57cec5SDimitry Andric 
542*0b57cec5SDimitry Andric     // ...then go back and propagate counts through the condition.
543*0b57cec5SDimitry Andric     uint64_t CondCount =
544*0b57cec5SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
545*0b57cec5SDimitry Andric     if (S->getCond()) {
546*0b57cec5SDimitry Andric       CountMap[S->getCond()] = CondCount;
547*0b57cec5SDimitry Andric       Visit(S->getCond());
548*0b57cec5SDimitry Andric     }
549*0b57cec5SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
550*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
551*0b57cec5SDimitry Andric   }
552*0b57cec5SDimitry Andric 
553*0b57cec5SDimitry Andric   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
554*0b57cec5SDimitry Andric     RecordStmtCount(S);
555*0b57cec5SDimitry Andric     if (S->getInit())
556*0b57cec5SDimitry Andric       Visit(S->getInit());
557*0b57cec5SDimitry Andric     Visit(S->getLoopVarStmt());
558*0b57cec5SDimitry Andric     Visit(S->getRangeStmt());
559*0b57cec5SDimitry Andric     Visit(S->getBeginStmt());
560*0b57cec5SDimitry Andric     Visit(S->getEndStmt());
561*0b57cec5SDimitry Andric 
562*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
563*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
564*0b57cec5SDimitry Andric     // Visit the body region first. (This is basically the same as a while
565*0b57cec5SDimitry Andric     // loop; see further comments in VisitWhileStmt.)
566*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
567*0b57cec5SDimitry Andric     CountMap[S->getBody()] = BodyCount;
568*0b57cec5SDimitry Andric     Visit(S->getBody());
569*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
570*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
571*0b57cec5SDimitry Andric 
572*0b57cec5SDimitry Andric     // The increment is essentially part of the body but it needs to include
573*0b57cec5SDimitry Andric     // the count for all the continue statements.
574*0b57cec5SDimitry Andric     uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
575*0b57cec5SDimitry Andric     CountMap[S->getInc()] = IncCount;
576*0b57cec5SDimitry Andric     Visit(S->getInc());
577*0b57cec5SDimitry Andric 
578*0b57cec5SDimitry Andric     // ...then go back and propagate counts through the condition.
579*0b57cec5SDimitry Andric     uint64_t CondCount =
580*0b57cec5SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
581*0b57cec5SDimitry Andric     CountMap[S->getCond()] = CondCount;
582*0b57cec5SDimitry Andric     Visit(S->getCond());
583*0b57cec5SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
584*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
585*0b57cec5SDimitry Andric   }
586*0b57cec5SDimitry Andric 
587*0b57cec5SDimitry Andric   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
588*0b57cec5SDimitry Andric     RecordStmtCount(S);
589*0b57cec5SDimitry Andric     Visit(S->getElement());
590*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
591*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
592*0b57cec5SDimitry Andric     // Counter tracks the body of the loop.
593*0b57cec5SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
594*0b57cec5SDimitry Andric     CountMap[S->getBody()] = BodyCount;
595*0b57cec5SDimitry Andric     Visit(S->getBody());
596*0b57cec5SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
597*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
598*0b57cec5SDimitry Andric 
599*0b57cec5SDimitry Andric     setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
600*0b57cec5SDimitry Andric              BodyCount);
601*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
602*0b57cec5SDimitry Andric   }
603*0b57cec5SDimitry Andric 
604*0b57cec5SDimitry Andric   void VisitSwitchStmt(const SwitchStmt *S) {
605*0b57cec5SDimitry Andric     RecordStmtCount(S);
606*0b57cec5SDimitry Andric     if (S->getInit())
607*0b57cec5SDimitry Andric       Visit(S->getInit());
608*0b57cec5SDimitry Andric     Visit(S->getCond());
609*0b57cec5SDimitry Andric     CurrentCount = 0;
610*0b57cec5SDimitry Andric     BreakContinueStack.push_back(BreakContinue());
611*0b57cec5SDimitry Andric     Visit(S->getBody());
612*0b57cec5SDimitry Andric     // If the switch is inside a loop, add the continue counts.
613*0b57cec5SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
614*0b57cec5SDimitry Andric     if (!BreakContinueStack.empty())
615*0b57cec5SDimitry Andric       BreakContinueStack.back().ContinueCount += BC.ContinueCount;
616*0b57cec5SDimitry Andric     // Counter tracks the exit block of the switch.
617*0b57cec5SDimitry Andric     setCount(PGO.getRegionCount(S));
618*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
619*0b57cec5SDimitry Andric   }
620*0b57cec5SDimitry Andric 
621*0b57cec5SDimitry Andric   void VisitSwitchCase(const SwitchCase *S) {
622*0b57cec5SDimitry Andric     RecordNextStmtCount = false;
623*0b57cec5SDimitry Andric     // Counter for this particular case. This counts only jumps from the
624*0b57cec5SDimitry Andric     // switch header and does not include fallthrough from the case before
625*0b57cec5SDimitry Andric     // this one.
626*0b57cec5SDimitry Andric     uint64_t CaseCount = PGO.getRegionCount(S);
627*0b57cec5SDimitry Andric     setCount(CurrentCount + CaseCount);
628*0b57cec5SDimitry Andric     // We need the count without fallthrough in the mapping, so it's more useful
629*0b57cec5SDimitry Andric     // for branch probabilities.
630*0b57cec5SDimitry Andric     CountMap[S] = CaseCount;
631*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
632*0b57cec5SDimitry Andric     Visit(S->getSubStmt());
633*0b57cec5SDimitry Andric   }
634*0b57cec5SDimitry Andric 
635*0b57cec5SDimitry Andric   void VisitIfStmt(const IfStmt *S) {
636*0b57cec5SDimitry Andric     RecordStmtCount(S);
637*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
638*0b57cec5SDimitry Andric     if (S->getInit())
639*0b57cec5SDimitry Andric       Visit(S->getInit());
640*0b57cec5SDimitry Andric     Visit(S->getCond());
641*0b57cec5SDimitry Andric 
642*0b57cec5SDimitry Andric     // Counter tracks the "then" part of an if statement. The count for
643*0b57cec5SDimitry Andric     // the "else" part, if it exists, will be calculated from this counter.
644*0b57cec5SDimitry Andric     uint64_t ThenCount = setCount(PGO.getRegionCount(S));
645*0b57cec5SDimitry Andric     CountMap[S->getThen()] = ThenCount;
646*0b57cec5SDimitry Andric     Visit(S->getThen());
647*0b57cec5SDimitry Andric     uint64_t OutCount = CurrentCount;
648*0b57cec5SDimitry Andric 
649*0b57cec5SDimitry Andric     uint64_t ElseCount = ParentCount - ThenCount;
650*0b57cec5SDimitry Andric     if (S->getElse()) {
651*0b57cec5SDimitry Andric       setCount(ElseCount);
652*0b57cec5SDimitry Andric       CountMap[S->getElse()] = ElseCount;
653*0b57cec5SDimitry Andric       Visit(S->getElse());
654*0b57cec5SDimitry Andric       OutCount += CurrentCount;
655*0b57cec5SDimitry Andric     } else
656*0b57cec5SDimitry Andric       OutCount += ElseCount;
657*0b57cec5SDimitry Andric     setCount(OutCount);
658*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
659*0b57cec5SDimitry Andric   }
660*0b57cec5SDimitry Andric 
661*0b57cec5SDimitry Andric   void VisitCXXTryStmt(const CXXTryStmt *S) {
662*0b57cec5SDimitry Andric     RecordStmtCount(S);
663*0b57cec5SDimitry Andric     Visit(S->getTryBlock());
664*0b57cec5SDimitry Andric     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
665*0b57cec5SDimitry Andric       Visit(S->getHandler(I));
666*0b57cec5SDimitry Andric     // Counter tracks the continuation block of the try statement.
667*0b57cec5SDimitry Andric     setCount(PGO.getRegionCount(S));
668*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
669*0b57cec5SDimitry Andric   }
670*0b57cec5SDimitry Andric 
671*0b57cec5SDimitry Andric   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
672*0b57cec5SDimitry Andric     RecordNextStmtCount = false;
673*0b57cec5SDimitry Andric     // Counter tracks the catch statement's handler block.
674*0b57cec5SDimitry Andric     uint64_t CatchCount = setCount(PGO.getRegionCount(S));
675*0b57cec5SDimitry Andric     CountMap[S] = CatchCount;
676*0b57cec5SDimitry Andric     Visit(S->getHandlerBlock());
677*0b57cec5SDimitry Andric   }
678*0b57cec5SDimitry Andric 
679*0b57cec5SDimitry Andric   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
680*0b57cec5SDimitry Andric     RecordStmtCount(E);
681*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
682*0b57cec5SDimitry Andric     Visit(E->getCond());
683*0b57cec5SDimitry Andric 
684*0b57cec5SDimitry Andric     // Counter tracks the "true" part of a conditional operator. The
685*0b57cec5SDimitry Andric     // count in the "false" part will be calculated from this counter.
686*0b57cec5SDimitry Andric     uint64_t TrueCount = setCount(PGO.getRegionCount(E));
687*0b57cec5SDimitry Andric     CountMap[E->getTrueExpr()] = TrueCount;
688*0b57cec5SDimitry Andric     Visit(E->getTrueExpr());
689*0b57cec5SDimitry Andric     uint64_t OutCount = CurrentCount;
690*0b57cec5SDimitry Andric 
691*0b57cec5SDimitry Andric     uint64_t FalseCount = setCount(ParentCount - TrueCount);
692*0b57cec5SDimitry Andric     CountMap[E->getFalseExpr()] = FalseCount;
693*0b57cec5SDimitry Andric     Visit(E->getFalseExpr());
694*0b57cec5SDimitry Andric     OutCount += CurrentCount;
695*0b57cec5SDimitry Andric 
696*0b57cec5SDimitry Andric     setCount(OutCount);
697*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
698*0b57cec5SDimitry Andric   }
699*0b57cec5SDimitry Andric 
700*0b57cec5SDimitry Andric   void VisitBinLAnd(const BinaryOperator *E) {
701*0b57cec5SDimitry Andric     RecordStmtCount(E);
702*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
703*0b57cec5SDimitry Andric     Visit(E->getLHS());
704*0b57cec5SDimitry Andric     // Counter tracks the right hand side of a logical and operator.
705*0b57cec5SDimitry Andric     uint64_t RHSCount = setCount(PGO.getRegionCount(E));
706*0b57cec5SDimitry Andric     CountMap[E->getRHS()] = RHSCount;
707*0b57cec5SDimitry Andric     Visit(E->getRHS());
708*0b57cec5SDimitry Andric     setCount(ParentCount + RHSCount - CurrentCount);
709*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
710*0b57cec5SDimitry Andric   }
711*0b57cec5SDimitry Andric 
712*0b57cec5SDimitry Andric   void VisitBinLOr(const BinaryOperator *E) {
713*0b57cec5SDimitry Andric     RecordStmtCount(E);
714*0b57cec5SDimitry Andric     uint64_t ParentCount = CurrentCount;
715*0b57cec5SDimitry Andric     Visit(E->getLHS());
716*0b57cec5SDimitry Andric     // Counter tracks the right hand side of a logical or operator.
717*0b57cec5SDimitry Andric     uint64_t RHSCount = setCount(PGO.getRegionCount(E));
718*0b57cec5SDimitry Andric     CountMap[E->getRHS()] = RHSCount;
719*0b57cec5SDimitry Andric     Visit(E->getRHS());
720*0b57cec5SDimitry Andric     setCount(ParentCount + RHSCount - CurrentCount);
721*0b57cec5SDimitry Andric     RecordNextStmtCount = true;
722*0b57cec5SDimitry Andric   }
723*0b57cec5SDimitry Andric };
724*0b57cec5SDimitry Andric } // end anonymous namespace
725*0b57cec5SDimitry Andric 
726*0b57cec5SDimitry Andric void PGOHash::combine(HashType Type) {
727*0b57cec5SDimitry Andric   // Check that we never combine 0 and only have six bits.
728*0b57cec5SDimitry Andric   assert(Type && "Hash is invalid: unexpected type 0");
729*0b57cec5SDimitry Andric   assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
730*0b57cec5SDimitry Andric 
731*0b57cec5SDimitry Andric   // Pass through MD5 if enough work has built up.
732*0b57cec5SDimitry Andric   if (Count && Count % NumTypesPerWord == 0) {
733*0b57cec5SDimitry Andric     using namespace llvm::support;
734*0b57cec5SDimitry Andric     uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
735*0b57cec5SDimitry Andric     MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
736*0b57cec5SDimitry Andric     Working = 0;
737*0b57cec5SDimitry Andric   }
738*0b57cec5SDimitry Andric 
739*0b57cec5SDimitry Andric   // Accumulate the current type.
740*0b57cec5SDimitry Andric   ++Count;
741*0b57cec5SDimitry Andric   Working = Working << NumBitsPerType | Type;
742*0b57cec5SDimitry Andric }
743*0b57cec5SDimitry Andric 
744*0b57cec5SDimitry Andric uint64_t PGOHash::finalize() {
745*0b57cec5SDimitry Andric   // Use Working as the hash directly if we never used MD5.
746*0b57cec5SDimitry Andric   if (Count <= NumTypesPerWord)
747*0b57cec5SDimitry Andric     // No need to byte swap here, since none of the math was endian-dependent.
748*0b57cec5SDimitry Andric     // This number will be byte-swapped as required on endianness transitions,
749*0b57cec5SDimitry Andric     // so we will see the same value on the other side.
750*0b57cec5SDimitry Andric     return Working;
751*0b57cec5SDimitry Andric 
752*0b57cec5SDimitry Andric   // Check for remaining work in Working.
7535ffd83dbSDimitry Andric   if (Working) {
7545ffd83dbSDimitry Andric     // Keep the buggy behavior from v1 and v2 for backward-compatibility. This
7555ffd83dbSDimitry Andric     // is buggy because it converts a uint64_t into an array of uint8_t.
7565ffd83dbSDimitry Andric     if (HashVersion < PGO_HASH_V3) {
7575ffd83dbSDimitry Andric       MD5.update({(uint8_t)Working});
7585ffd83dbSDimitry Andric     } else {
7595ffd83dbSDimitry Andric       using namespace llvm::support;
7605ffd83dbSDimitry Andric       uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
7615ffd83dbSDimitry Andric       MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
7625ffd83dbSDimitry Andric     }
7635ffd83dbSDimitry Andric   }
764*0b57cec5SDimitry Andric 
765*0b57cec5SDimitry Andric   // Finalize the MD5 and return the hash.
766*0b57cec5SDimitry Andric   llvm::MD5::MD5Result Result;
767*0b57cec5SDimitry Andric   MD5.final(Result);
768*0b57cec5SDimitry Andric   return Result.low();
769*0b57cec5SDimitry Andric }
770*0b57cec5SDimitry Andric 
771*0b57cec5SDimitry Andric void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
772*0b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
773*0b57cec5SDimitry Andric   if (!D->hasBody())
774*0b57cec5SDimitry Andric     return;
775*0b57cec5SDimitry Andric 
776*0b57cec5SDimitry Andric   bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
777*0b57cec5SDimitry Andric   llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
778*0b57cec5SDimitry Andric   if (!InstrumentRegions && !PGOReader)
779*0b57cec5SDimitry Andric     return;
780*0b57cec5SDimitry Andric   if (D->isImplicit())
781*0b57cec5SDimitry Andric     return;
782*0b57cec5SDimitry Andric   // Constructors and destructors may be represented by several functions in IR.
783*0b57cec5SDimitry Andric   // If so, instrument only base variant, others are implemented by delegation
784*0b57cec5SDimitry Andric   // to the base one, it would be counted twice otherwise.
785*0b57cec5SDimitry Andric   if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
786*0b57cec5SDimitry Andric     if (const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
787*0b57cec5SDimitry Andric       if (GD.getCtorType() != Ctor_Base &&
788*0b57cec5SDimitry Andric           CodeGenFunction::IsConstructorDelegationValid(CCD))
789*0b57cec5SDimitry Andric         return;
790*0b57cec5SDimitry Andric   }
791*0b57cec5SDimitry Andric   if (isa<CXXDestructorDecl>(D) && GD.getDtorType() != Dtor_Base)
792*0b57cec5SDimitry Andric     return;
793*0b57cec5SDimitry Andric 
794*0b57cec5SDimitry Andric   CGM.ClearUnusedCoverageMapping(D);
795*0b57cec5SDimitry Andric   setFuncName(Fn);
796*0b57cec5SDimitry Andric 
797*0b57cec5SDimitry Andric   mapRegionCounters(D);
798*0b57cec5SDimitry Andric   if (CGM.getCodeGenOpts().CoverageMapping)
799*0b57cec5SDimitry Andric     emitCounterRegionMapping(D);
800*0b57cec5SDimitry Andric   if (PGOReader) {
801*0b57cec5SDimitry Andric     SourceManager &SM = CGM.getContext().getSourceManager();
802*0b57cec5SDimitry Andric     loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
803*0b57cec5SDimitry Andric     computeRegionCounts(D);
804*0b57cec5SDimitry Andric     applyFunctionAttributes(PGOReader, Fn);
805*0b57cec5SDimitry Andric   }
806*0b57cec5SDimitry Andric }
807*0b57cec5SDimitry Andric 
808*0b57cec5SDimitry Andric void CodeGenPGO::mapRegionCounters(const Decl *D) {
809*0b57cec5SDimitry Andric   // Use the latest hash version when inserting instrumentation, but use the
810*0b57cec5SDimitry Andric   // version in the indexed profile if we're reading PGO data.
811*0b57cec5SDimitry Andric   PGOHashVersion HashVersion = PGO_HASH_LATEST;
812*0b57cec5SDimitry Andric   if (auto *PGOReader = CGM.getPGOReader())
813*0b57cec5SDimitry Andric     HashVersion = getPGOHashVersion(PGOReader, CGM);
814*0b57cec5SDimitry Andric 
815*0b57cec5SDimitry Andric   RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
816*0b57cec5SDimitry Andric   MapRegionCounters Walker(HashVersion, *RegionCounterMap);
817*0b57cec5SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
818*0b57cec5SDimitry Andric     Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
819*0b57cec5SDimitry Andric   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
820*0b57cec5SDimitry Andric     Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
821*0b57cec5SDimitry Andric   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
822*0b57cec5SDimitry Andric     Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
823*0b57cec5SDimitry Andric   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
824*0b57cec5SDimitry Andric     Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
825*0b57cec5SDimitry Andric   assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
826*0b57cec5SDimitry Andric   NumRegionCounters = Walker.NextCounter;
827*0b57cec5SDimitry Andric   FunctionHash = Walker.Hash.finalize();
828*0b57cec5SDimitry Andric }
829*0b57cec5SDimitry Andric 
830*0b57cec5SDimitry Andric bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
831*0b57cec5SDimitry Andric   if (!D->getBody())
832*0b57cec5SDimitry Andric     return true;
833*0b57cec5SDimitry Andric 
834*0b57cec5SDimitry Andric   // Don't map the functions in system headers.
835*0b57cec5SDimitry Andric   const auto &SM = CGM.getContext().getSourceManager();
836*0b57cec5SDimitry Andric   auto Loc = D->getBody()->getBeginLoc();
837*0b57cec5SDimitry Andric   return SM.isInSystemHeader(Loc);
838*0b57cec5SDimitry Andric }
839*0b57cec5SDimitry Andric 
840*0b57cec5SDimitry Andric void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
841*0b57cec5SDimitry Andric   if (skipRegionMappingForDecl(D))
842*0b57cec5SDimitry Andric     return;
843*0b57cec5SDimitry Andric 
844*0b57cec5SDimitry Andric   std::string CoverageMapping;
845*0b57cec5SDimitry Andric   llvm::raw_string_ostream OS(CoverageMapping);
846*0b57cec5SDimitry Andric   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
847*0b57cec5SDimitry Andric                                 CGM.getContext().getSourceManager(),
848*0b57cec5SDimitry Andric                                 CGM.getLangOpts(), RegionCounterMap.get());
849*0b57cec5SDimitry Andric   MappingGen.emitCounterMapping(D, OS);
850*0b57cec5SDimitry Andric   OS.flush();
851*0b57cec5SDimitry Andric 
852*0b57cec5SDimitry Andric   if (CoverageMapping.empty())
853*0b57cec5SDimitry Andric     return;
854*0b57cec5SDimitry Andric 
855*0b57cec5SDimitry Andric   CGM.getCoverageMapping()->addFunctionMappingRecord(
856*0b57cec5SDimitry Andric       FuncNameVar, FuncName, FunctionHash, CoverageMapping);
857*0b57cec5SDimitry Andric }
858*0b57cec5SDimitry Andric 
859*0b57cec5SDimitry Andric void
860*0b57cec5SDimitry Andric CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
861*0b57cec5SDimitry Andric                                     llvm::GlobalValue::LinkageTypes Linkage) {
862*0b57cec5SDimitry Andric   if (skipRegionMappingForDecl(D))
863*0b57cec5SDimitry Andric     return;
864*0b57cec5SDimitry Andric 
865*0b57cec5SDimitry Andric   std::string CoverageMapping;
866*0b57cec5SDimitry Andric   llvm::raw_string_ostream OS(CoverageMapping);
867*0b57cec5SDimitry Andric   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
868*0b57cec5SDimitry Andric                                 CGM.getContext().getSourceManager(),
869*0b57cec5SDimitry Andric                                 CGM.getLangOpts());
870*0b57cec5SDimitry Andric   MappingGen.emitEmptyMapping(D, OS);
871*0b57cec5SDimitry Andric   OS.flush();
872*0b57cec5SDimitry Andric 
873*0b57cec5SDimitry Andric   if (CoverageMapping.empty())
874*0b57cec5SDimitry Andric     return;
875*0b57cec5SDimitry Andric 
876*0b57cec5SDimitry Andric   setFuncName(Name, Linkage);
877*0b57cec5SDimitry Andric   CGM.getCoverageMapping()->addFunctionMappingRecord(
878*0b57cec5SDimitry Andric       FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
879*0b57cec5SDimitry Andric }
880*0b57cec5SDimitry Andric 
881*0b57cec5SDimitry Andric void CodeGenPGO::computeRegionCounts(const Decl *D) {
882*0b57cec5SDimitry Andric   StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
883*0b57cec5SDimitry Andric   ComputeRegionCounts Walker(*StmtCountMap, *this);
884*0b57cec5SDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
885*0b57cec5SDimitry Andric     Walker.VisitFunctionDecl(FD);
886*0b57cec5SDimitry Andric   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
887*0b57cec5SDimitry Andric     Walker.VisitObjCMethodDecl(MD);
888*0b57cec5SDimitry Andric   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
889*0b57cec5SDimitry Andric     Walker.VisitBlockDecl(BD);
890*0b57cec5SDimitry Andric   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
891*0b57cec5SDimitry Andric     Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
892*0b57cec5SDimitry Andric }
893*0b57cec5SDimitry Andric 
894*0b57cec5SDimitry Andric void
895*0b57cec5SDimitry Andric CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
896*0b57cec5SDimitry Andric                                     llvm::Function *Fn) {
897*0b57cec5SDimitry Andric   if (!haveRegionCounts())
898*0b57cec5SDimitry Andric     return;
899*0b57cec5SDimitry Andric 
900*0b57cec5SDimitry Andric   uint64_t FunctionCount = getRegionCount(nullptr);
901*0b57cec5SDimitry Andric   Fn->setEntryCount(FunctionCount);
902*0b57cec5SDimitry Andric }
903*0b57cec5SDimitry Andric 
904*0b57cec5SDimitry Andric void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S,
905*0b57cec5SDimitry Andric                                       llvm::Value *StepV) {
906*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().hasProfileClangInstr() || !RegionCounterMap)
907*0b57cec5SDimitry Andric     return;
908*0b57cec5SDimitry Andric   if (!Builder.GetInsertBlock())
909*0b57cec5SDimitry Andric     return;
910*0b57cec5SDimitry Andric 
911*0b57cec5SDimitry Andric   unsigned Counter = (*RegionCounterMap)[S];
912*0b57cec5SDimitry Andric   auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
913*0b57cec5SDimitry Andric 
914*0b57cec5SDimitry Andric   llvm::Value *Args[] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
915*0b57cec5SDimitry Andric                          Builder.getInt64(FunctionHash),
916*0b57cec5SDimitry Andric                          Builder.getInt32(NumRegionCounters),
917*0b57cec5SDimitry Andric                          Builder.getInt32(Counter), StepV};
918*0b57cec5SDimitry Andric   if (!StepV)
919*0b57cec5SDimitry Andric     Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
920*0b57cec5SDimitry Andric                        makeArrayRef(Args, 4));
921*0b57cec5SDimitry Andric   else
922*0b57cec5SDimitry Andric     Builder.CreateCall(
923*0b57cec5SDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step),
924*0b57cec5SDimitry Andric         makeArrayRef(Args));
925*0b57cec5SDimitry Andric }
926*0b57cec5SDimitry Andric 
927*0b57cec5SDimitry Andric // This method either inserts a call to the profile run-time during
928*0b57cec5SDimitry Andric // instrumentation or puts profile data into metadata for PGO use.
929*0b57cec5SDimitry Andric void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
930*0b57cec5SDimitry Andric     llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
931*0b57cec5SDimitry Andric 
932*0b57cec5SDimitry Andric   if (!EnableValueProfiling)
933*0b57cec5SDimitry Andric     return;
934*0b57cec5SDimitry Andric 
935*0b57cec5SDimitry Andric   if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
936*0b57cec5SDimitry Andric     return;
937*0b57cec5SDimitry Andric 
938*0b57cec5SDimitry Andric   if (isa<llvm::Constant>(ValuePtr))
939*0b57cec5SDimitry Andric     return;
940*0b57cec5SDimitry Andric 
941*0b57cec5SDimitry Andric   bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
942*0b57cec5SDimitry Andric   if (InstrumentValueSites && RegionCounterMap) {
943*0b57cec5SDimitry Andric     auto BuilderInsertPoint = Builder.saveIP();
944*0b57cec5SDimitry Andric     Builder.SetInsertPoint(ValueSite);
945*0b57cec5SDimitry Andric     llvm::Value *Args[5] = {
946*0b57cec5SDimitry Andric         llvm::ConstantExpr::getBitCast(FuncNameVar, Builder.getInt8PtrTy()),
947*0b57cec5SDimitry Andric         Builder.getInt64(FunctionHash),
948*0b57cec5SDimitry Andric         Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
949*0b57cec5SDimitry Andric         Builder.getInt32(ValueKind),
950*0b57cec5SDimitry Andric         Builder.getInt32(NumValueSites[ValueKind]++)
951*0b57cec5SDimitry Andric     };
952*0b57cec5SDimitry Andric     Builder.CreateCall(
953*0b57cec5SDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
954*0b57cec5SDimitry Andric     Builder.restoreIP(BuilderInsertPoint);
955*0b57cec5SDimitry Andric     return;
956*0b57cec5SDimitry Andric   }
957*0b57cec5SDimitry Andric 
958*0b57cec5SDimitry Andric   llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
959*0b57cec5SDimitry Andric   if (PGOReader && haveRegionCounts()) {
960*0b57cec5SDimitry Andric     // We record the top most called three functions at each call site.
961*0b57cec5SDimitry Andric     // Profile metadata contains "VP" string identifying this metadata
962*0b57cec5SDimitry Andric     // as value profiling data, then a uint32_t value for the value profiling
963*0b57cec5SDimitry Andric     // kind, a uint64_t value for the total number of times the call is
964*0b57cec5SDimitry Andric     // executed, followed by the function hash and execution count (uint64_t)
965*0b57cec5SDimitry Andric     // pairs for each function.
966*0b57cec5SDimitry Andric     if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
967*0b57cec5SDimitry Andric       return;
968*0b57cec5SDimitry Andric 
969*0b57cec5SDimitry Andric     llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
970*0b57cec5SDimitry Andric                             (llvm::InstrProfValueKind)ValueKind,
971*0b57cec5SDimitry Andric                             NumValueSites[ValueKind]);
972*0b57cec5SDimitry Andric 
973*0b57cec5SDimitry Andric     NumValueSites[ValueKind]++;
974*0b57cec5SDimitry Andric   }
975*0b57cec5SDimitry Andric }
976*0b57cec5SDimitry Andric 
977*0b57cec5SDimitry Andric void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
978*0b57cec5SDimitry Andric                                   bool IsInMainFile) {
979*0b57cec5SDimitry Andric   CGM.getPGOStats().addVisited(IsInMainFile);
980*0b57cec5SDimitry Andric   RegionCounts.clear();
981*0b57cec5SDimitry Andric   llvm::Expected<llvm::InstrProfRecord> RecordExpected =
982*0b57cec5SDimitry Andric       PGOReader->getInstrProfRecord(FuncName, FunctionHash);
983*0b57cec5SDimitry Andric   if (auto E = RecordExpected.takeError()) {
984*0b57cec5SDimitry Andric     auto IPE = llvm::InstrProfError::take(std::move(E));
985*0b57cec5SDimitry Andric     if (IPE == llvm::instrprof_error::unknown_function)
986*0b57cec5SDimitry Andric       CGM.getPGOStats().addMissing(IsInMainFile);
987*0b57cec5SDimitry Andric     else if (IPE == llvm::instrprof_error::hash_mismatch)
988*0b57cec5SDimitry Andric       CGM.getPGOStats().addMismatched(IsInMainFile);
989*0b57cec5SDimitry Andric     else if (IPE == llvm::instrprof_error::malformed)
990*0b57cec5SDimitry Andric       // TODO: Consider a more specific warning for this case.
991*0b57cec5SDimitry Andric       CGM.getPGOStats().addMismatched(IsInMainFile);
992*0b57cec5SDimitry Andric     return;
993*0b57cec5SDimitry Andric   }
994*0b57cec5SDimitry Andric   ProfRecord =
995a7dea167SDimitry Andric       std::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
996*0b57cec5SDimitry Andric   RegionCounts = ProfRecord->Counts;
997*0b57cec5SDimitry Andric }
998*0b57cec5SDimitry Andric 
999*0b57cec5SDimitry Andric /// Calculate what to divide by to scale weights.
1000*0b57cec5SDimitry Andric ///
1001*0b57cec5SDimitry Andric /// Given the maximum weight, calculate a divisor that will scale all the
1002*0b57cec5SDimitry Andric /// weights to strictly less than UINT32_MAX.
1003*0b57cec5SDimitry Andric static uint64_t calculateWeightScale(uint64_t MaxWeight) {
1004*0b57cec5SDimitry Andric   return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
1005*0b57cec5SDimitry Andric }
1006*0b57cec5SDimitry Andric 
1007*0b57cec5SDimitry Andric /// Scale an individual branch weight (and add 1).
1008*0b57cec5SDimitry Andric ///
1009*0b57cec5SDimitry Andric /// Scale a 64-bit weight down to 32-bits using \c Scale.
1010*0b57cec5SDimitry Andric ///
1011*0b57cec5SDimitry Andric /// According to Laplace's Rule of Succession, it is better to compute the
1012*0b57cec5SDimitry Andric /// weight based on the count plus 1, so universally add 1 to the value.
1013*0b57cec5SDimitry Andric ///
1014*0b57cec5SDimitry Andric /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
1015*0b57cec5SDimitry Andric /// greater than \c Weight.
1016*0b57cec5SDimitry Andric static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
1017*0b57cec5SDimitry Andric   assert(Scale && "scale by 0?");
1018*0b57cec5SDimitry Andric   uint64_t Scaled = Weight / Scale + 1;
1019*0b57cec5SDimitry Andric   assert(Scaled <= UINT32_MAX && "overflow 32-bits");
1020*0b57cec5SDimitry Andric   return Scaled;
1021*0b57cec5SDimitry Andric }
1022*0b57cec5SDimitry Andric 
1023*0b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
1024*0b57cec5SDimitry Andric                                                     uint64_t FalseCount) {
1025*0b57cec5SDimitry Andric   // Check for empty weights.
1026*0b57cec5SDimitry Andric   if (!TrueCount && !FalseCount)
1027*0b57cec5SDimitry Andric     return nullptr;
1028*0b57cec5SDimitry Andric 
1029*0b57cec5SDimitry Andric   // Calculate how to scale down to 32-bits.
1030*0b57cec5SDimitry Andric   uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
1031*0b57cec5SDimitry Andric 
1032*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1033*0b57cec5SDimitry Andric   return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
1034*0b57cec5SDimitry Andric                                       scaleBranchWeight(FalseCount, Scale));
1035*0b57cec5SDimitry Andric }
1036*0b57cec5SDimitry Andric 
1037*0b57cec5SDimitry Andric llvm::MDNode *
1038*0b57cec5SDimitry Andric CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
1039*0b57cec5SDimitry Andric   // We need at least two elements to create meaningful weights.
1040*0b57cec5SDimitry Andric   if (Weights.size() < 2)
1041*0b57cec5SDimitry Andric     return nullptr;
1042*0b57cec5SDimitry Andric 
1043*0b57cec5SDimitry Andric   // Check for empty weights.
1044*0b57cec5SDimitry Andric   uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
1045*0b57cec5SDimitry Andric   if (MaxWeight == 0)
1046*0b57cec5SDimitry Andric     return nullptr;
1047*0b57cec5SDimitry Andric 
1048*0b57cec5SDimitry Andric   // Calculate how to scale down to 32-bits.
1049*0b57cec5SDimitry Andric   uint64_t Scale = calculateWeightScale(MaxWeight);
1050*0b57cec5SDimitry Andric 
1051*0b57cec5SDimitry Andric   SmallVector<uint32_t, 16> ScaledWeights;
1052*0b57cec5SDimitry Andric   ScaledWeights.reserve(Weights.size());
1053*0b57cec5SDimitry Andric   for (uint64_t W : Weights)
1054*0b57cec5SDimitry Andric     ScaledWeights.push_back(scaleBranchWeight(W, Scale));
1055*0b57cec5SDimitry Andric 
1056*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1057*0b57cec5SDimitry Andric   return MDHelper.createBranchWeights(ScaledWeights);
1058*0b57cec5SDimitry Andric }
1059*0b57cec5SDimitry Andric 
1060*0b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
1061*0b57cec5SDimitry Andric                                                            uint64_t LoopCount) {
1062*0b57cec5SDimitry Andric   if (!PGO.haveRegionCounts())
1063*0b57cec5SDimitry Andric     return nullptr;
1064*0b57cec5SDimitry Andric   Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
10655ffd83dbSDimitry Andric   if (!CondCount || *CondCount == 0)
1066*0b57cec5SDimitry Andric     return nullptr;
1067*0b57cec5SDimitry Andric   return createProfileWeights(LoopCount,
1068*0b57cec5SDimitry Andric                               std::max(*CondCount, LoopCount) - LoopCount);
1069*0b57cec5SDimitry Andric }
1070