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