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