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