159d1ed5bSDimitry Andric //===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
259d1ed5bSDimitry Andric //
359d1ed5bSDimitry Andric //                     The LLVM Compiler Infrastructure
459d1ed5bSDimitry Andric //
559d1ed5bSDimitry Andric // This file is distributed under the University of Illinois Open Source
659d1ed5bSDimitry Andric // License. See LICENSE.TXT for details.
759d1ed5bSDimitry Andric //
859d1ed5bSDimitry Andric //===----------------------------------------------------------------------===//
959d1ed5bSDimitry Andric //
1059d1ed5bSDimitry Andric // Instrumentation-based profile-guided optimization
1159d1ed5bSDimitry Andric //
1259d1ed5bSDimitry Andric //===----------------------------------------------------------------------===//
1359d1ed5bSDimitry Andric 
1459d1ed5bSDimitry Andric #include "CodeGenPGO.h"
1559d1ed5bSDimitry Andric #include "CodeGenFunction.h"
1639d628a0SDimitry Andric #include "CoverageMappingGen.h"
1759d1ed5bSDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
1859d1ed5bSDimitry Andric #include "clang/AST/StmtVisitor.h"
1939d628a0SDimitry Andric #include "llvm/IR/Intrinsics.h"
2059d1ed5bSDimitry Andric #include "llvm/IR/MDBuilder.h"
2159d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
2259d1ed5bSDimitry Andric #include "llvm/Support/Endian.h"
2359d1ed5bSDimitry Andric #include "llvm/Support/FileSystem.h"
2459d1ed5bSDimitry Andric #include "llvm/Support/MD5.h"
2559d1ed5bSDimitry Andric 
2659d1ed5bSDimitry Andric using namespace clang;
2759d1ed5bSDimitry Andric using namespace CodeGen;
2859d1ed5bSDimitry Andric 
2939d628a0SDimitry Andric void CodeGenPGO::setFuncName(StringRef Name,
3039d628a0SDimitry Andric                              llvm::GlobalValue::LinkageTypes Linkage) {
3139d628a0SDimitry Andric   StringRef RawFuncName = Name;
3259d1ed5bSDimitry Andric 
3359d1ed5bSDimitry Andric   // Function names may be prefixed with a binary '1' to indicate
3459d1ed5bSDimitry Andric   // that the backend should not modify the symbols due to any platform
3559d1ed5bSDimitry Andric   // naming convention. Do not include that '1' in the PGO profile name.
3659d1ed5bSDimitry Andric   if (RawFuncName[0] == '\1')
3759d1ed5bSDimitry Andric     RawFuncName = RawFuncName.substr(1);
3859d1ed5bSDimitry Andric 
3939d628a0SDimitry Andric   FuncName = RawFuncName;
4039d628a0SDimitry Andric   if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
4159d1ed5bSDimitry Andric     // For local symbols, prepend the main file name to distinguish them.
4259d1ed5bSDimitry Andric     // Do not include the full path in the file name since there's no guarantee
4359d1ed5bSDimitry Andric     // that it will stay the same, e.g., if the files are checked out from
4459d1ed5bSDimitry Andric     // version control in different locations.
4539d628a0SDimitry Andric     if (CGM.getCodeGenOpts().MainFileName.empty())
4639d628a0SDimitry Andric       FuncName = FuncName.insert(0, "<unknown>:");
4739d628a0SDimitry Andric     else
4839d628a0SDimitry Andric       FuncName = FuncName.insert(0, CGM.getCodeGenOpts().MainFileName + ":");
4959d1ed5bSDimitry Andric   }
5059d1ed5bSDimitry Andric 
5139d628a0SDimitry Andric   // If we're generating a profile, create a variable for the name.
5239d628a0SDimitry Andric   if (CGM.getCodeGenOpts().ProfileInstrGenerate)
5339d628a0SDimitry Andric     createFuncNameVar(Linkage);
5459d1ed5bSDimitry Andric }
5559d1ed5bSDimitry Andric 
5639d628a0SDimitry Andric void CodeGenPGO::setFuncName(llvm::Function *Fn) {
5739d628a0SDimitry Andric   setFuncName(Fn->getName(), Fn->getLinkage());
5859d1ed5bSDimitry Andric }
5959d1ed5bSDimitry Andric 
6039d628a0SDimitry Andric void CodeGenPGO::createFuncNameVar(llvm::GlobalValue::LinkageTypes Linkage) {
6133956c43SDimitry Andric   // We generally want to match the function's linkage, but available_externally
6233956c43SDimitry Andric   // and extern_weak both have the wrong semantics, and anything that doesn't
6333956c43SDimitry Andric   // need to link across compilation units doesn't need to be visible at all.
6439d628a0SDimitry Andric   if (Linkage == llvm::GlobalValue::ExternalWeakLinkage)
6539d628a0SDimitry Andric     Linkage = llvm::GlobalValue::LinkOnceAnyLinkage;
6639d628a0SDimitry Andric   else if (Linkage == llvm::GlobalValue::AvailableExternallyLinkage)
6739d628a0SDimitry Andric     Linkage = llvm::GlobalValue::LinkOnceODRLinkage;
6833956c43SDimitry Andric   else if (Linkage == llvm::GlobalValue::InternalLinkage ||
6933956c43SDimitry Andric            Linkage == llvm::GlobalValue::ExternalLinkage)
7033956c43SDimitry Andric     Linkage = llvm::GlobalValue::PrivateLinkage;
7159d1ed5bSDimitry Andric 
7239d628a0SDimitry Andric   auto *Value =
7339d628a0SDimitry Andric       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), FuncName, false);
7439d628a0SDimitry Andric   FuncNameVar =
7539d628a0SDimitry Andric       new llvm::GlobalVariable(CGM.getModule(), Value->getType(), true, Linkage,
7639d628a0SDimitry Andric                                Value, "__llvm_profile_name_" + FuncName);
7759d1ed5bSDimitry Andric 
7839d628a0SDimitry Andric   // Hide the symbol so that we correctly get a copy for each executable.
7939d628a0SDimitry Andric   if (!llvm::GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
8039d628a0SDimitry Andric     FuncNameVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
8159d1ed5bSDimitry Andric }
8259d1ed5bSDimitry Andric 
8359d1ed5bSDimitry Andric namespace {
8459d1ed5bSDimitry Andric /// \brief Stable hasher for PGO region counters.
8559d1ed5bSDimitry Andric ///
8659d1ed5bSDimitry Andric /// PGOHash produces a stable hash of a given function's control flow.
8759d1ed5bSDimitry Andric ///
8859d1ed5bSDimitry Andric /// Changing the output of this hash will invalidate all previously generated
8959d1ed5bSDimitry Andric /// profiles -- i.e., don't do it.
9059d1ed5bSDimitry Andric ///
9159d1ed5bSDimitry Andric /// \note  When this hash does eventually change (years?), we still need to
9259d1ed5bSDimitry Andric /// support old hashes.  We'll need to pull in the version number from the
9359d1ed5bSDimitry Andric /// profile data format and use the matching hash function.
9459d1ed5bSDimitry Andric class PGOHash {
9559d1ed5bSDimitry Andric   uint64_t Working;
9659d1ed5bSDimitry Andric   unsigned Count;
9759d1ed5bSDimitry Andric   llvm::MD5 MD5;
9859d1ed5bSDimitry Andric 
9959d1ed5bSDimitry Andric   static const int NumBitsPerType = 6;
10059d1ed5bSDimitry Andric   static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
10159d1ed5bSDimitry Andric   static const unsigned TooBig = 1u << NumBitsPerType;
10259d1ed5bSDimitry Andric 
10359d1ed5bSDimitry Andric public:
10459d1ed5bSDimitry Andric   /// \brief Hash values for AST nodes.
10559d1ed5bSDimitry Andric   ///
10659d1ed5bSDimitry Andric   /// Distinct values for AST nodes that have region counters attached.
10759d1ed5bSDimitry Andric   ///
10859d1ed5bSDimitry Andric   /// These values must be stable.  All new members must be added at the end,
10959d1ed5bSDimitry Andric   /// and no members should be removed.  Changing the enumeration value for an
11059d1ed5bSDimitry Andric   /// AST node will affect the hash of every function that contains that node.
11159d1ed5bSDimitry Andric   enum HashType : unsigned char {
11259d1ed5bSDimitry Andric     None = 0,
11359d1ed5bSDimitry Andric     LabelStmt = 1,
11459d1ed5bSDimitry Andric     WhileStmt,
11559d1ed5bSDimitry Andric     DoStmt,
11659d1ed5bSDimitry Andric     ForStmt,
11759d1ed5bSDimitry Andric     CXXForRangeStmt,
11859d1ed5bSDimitry Andric     ObjCForCollectionStmt,
11959d1ed5bSDimitry Andric     SwitchStmt,
12059d1ed5bSDimitry Andric     CaseStmt,
12159d1ed5bSDimitry Andric     DefaultStmt,
12259d1ed5bSDimitry Andric     IfStmt,
12359d1ed5bSDimitry Andric     CXXTryStmt,
12459d1ed5bSDimitry Andric     CXXCatchStmt,
12559d1ed5bSDimitry Andric     ConditionalOperator,
12659d1ed5bSDimitry Andric     BinaryOperatorLAnd,
12759d1ed5bSDimitry Andric     BinaryOperatorLOr,
12859d1ed5bSDimitry Andric     BinaryConditionalOperator,
12959d1ed5bSDimitry Andric 
13059d1ed5bSDimitry Andric     // Keep this last.  It's for the static assert that follows.
13159d1ed5bSDimitry Andric     LastHashType
13259d1ed5bSDimitry Andric   };
13359d1ed5bSDimitry Andric   static_assert(LastHashType <= TooBig, "Too many types in HashType");
13459d1ed5bSDimitry Andric 
13559d1ed5bSDimitry Andric   // TODO: When this format changes, take in a version number here, and use the
13659d1ed5bSDimitry Andric   // old hash calculation for file formats that used the old hash.
13759d1ed5bSDimitry Andric   PGOHash() : Working(0), Count(0) {}
13859d1ed5bSDimitry Andric   void combine(HashType Type);
13959d1ed5bSDimitry Andric   uint64_t finalize();
14059d1ed5bSDimitry Andric };
14159d1ed5bSDimitry Andric const int PGOHash::NumBitsPerType;
14259d1ed5bSDimitry Andric const unsigned PGOHash::NumTypesPerWord;
14359d1ed5bSDimitry Andric const unsigned PGOHash::TooBig;
14459d1ed5bSDimitry Andric 
14559d1ed5bSDimitry Andric /// A RecursiveASTVisitor that fills a map of statements to PGO counters.
14659d1ed5bSDimitry Andric struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
14759d1ed5bSDimitry Andric   /// The next counter value to assign.
14859d1ed5bSDimitry Andric   unsigned NextCounter;
14959d1ed5bSDimitry Andric   /// The function hash.
15059d1ed5bSDimitry Andric   PGOHash Hash;
15159d1ed5bSDimitry Andric   /// The map of statements to counters.
15259d1ed5bSDimitry Andric   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
15359d1ed5bSDimitry Andric 
15459d1ed5bSDimitry Andric   MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
15559d1ed5bSDimitry Andric       : NextCounter(0), CounterMap(CounterMap) {}
15659d1ed5bSDimitry Andric 
15759d1ed5bSDimitry Andric   // Blocks and lambdas are handled as separate functions, so we need not
15859d1ed5bSDimitry Andric   // traverse them in the parent context.
15959d1ed5bSDimitry Andric   bool TraverseBlockExpr(BlockExpr *BE) { return true; }
16059d1ed5bSDimitry Andric   bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
16159d1ed5bSDimitry Andric   bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
16259d1ed5bSDimitry Andric 
16359d1ed5bSDimitry Andric   bool VisitDecl(const Decl *D) {
16459d1ed5bSDimitry Andric     switch (D->getKind()) {
16559d1ed5bSDimitry Andric     default:
16659d1ed5bSDimitry Andric       break;
16759d1ed5bSDimitry Andric     case Decl::Function:
16859d1ed5bSDimitry Andric     case Decl::CXXMethod:
16959d1ed5bSDimitry Andric     case Decl::CXXConstructor:
17059d1ed5bSDimitry Andric     case Decl::CXXDestructor:
17159d1ed5bSDimitry Andric     case Decl::CXXConversion:
17259d1ed5bSDimitry Andric     case Decl::ObjCMethod:
17359d1ed5bSDimitry Andric     case Decl::Block:
17459d1ed5bSDimitry Andric     case Decl::Captured:
17559d1ed5bSDimitry Andric       CounterMap[D->getBody()] = NextCounter++;
17659d1ed5bSDimitry Andric       break;
17759d1ed5bSDimitry Andric     }
17859d1ed5bSDimitry Andric     return true;
17959d1ed5bSDimitry Andric   }
18059d1ed5bSDimitry Andric 
18159d1ed5bSDimitry Andric   bool VisitStmt(const Stmt *S) {
18259d1ed5bSDimitry Andric     auto Type = getHashType(S);
18359d1ed5bSDimitry Andric     if (Type == PGOHash::None)
18459d1ed5bSDimitry Andric       return true;
18559d1ed5bSDimitry Andric 
18659d1ed5bSDimitry Andric     CounterMap[S] = NextCounter++;
18759d1ed5bSDimitry Andric     Hash.combine(Type);
18859d1ed5bSDimitry Andric     return true;
18959d1ed5bSDimitry Andric   }
19059d1ed5bSDimitry Andric   PGOHash::HashType getHashType(const Stmt *S) {
19159d1ed5bSDimitry Andric     switch (S->getStmtClass()) {
19259d1ed5bSDimitry Andric     default:
19359d1ed5bSDimitry Andric       break;
19459d1ed5bSDimitry Andric     case Stmt::LabelStmtClass:
19559d1ed5bSDimitry Andric       return PGOHash::LabelStmt;
19659d1ed5bSDimitry Andric     case Stmt::WhileStmtClass:
19759d1ed5bSDimitry Andric       return PGOHash::WhileStmt;
19859d1ed5bSDimitry Andric     case Stmt::DoStmtClass:
19959d1ed5bSDimitry Andric       return PGOHash::DoStmt;
20059d1ed5bSDimitry Andric     case Stmt::ForStmtClass:
20159d1ed5bSDimitry Andric       return PGOHash::ForStmt;
20259d1ed5bSDimitry Andric     case Stmt::CXXForRangeStmtClass:
20359d1ed5bSDimitry Andric       return PGOHash::CXXForRangeStmt;
20459d1ed5bSDimitry Andric     case Stmt::ObjCForCollectionStmtClass:
20559d1ed5bSDimitry Andric       return PGOHash::ObjCForCollectionStmt;
20659d1ed5bSDimitry Andric     case Stmt::SwitchStmtClass:
20759d1ed5bSDimitry Andric       return PGOHash::SwitchStmt;
20859d1ed5bSDimitry Andric     case Stmt::CaseStmtClass:
20959d1ed5bSDimitry Andric       return PGOHash::CaseStmt;
21059d1ed5bSDimitry Andric     case Stmt::DefaultStmtClass:
21159d1ed5bSDimitry Andric       return PGOHash::DefaultStmt;
21259d1ed5bSDimitry Andric     case Stmt::IfStmtClass:
21359d1ed5bSDimitry Andric       return PGOHash::IfStmt;
21459d1ed5bSDimitry Andric     case Stmt::CXXTryStmtClass:
21559d1ed5bSDimitry Andric       return PGOHash::CXXTryStmt;
21659d1ed5bSDimitry Andric     case Stmt::CXXCatchStmtClass:
21759d1ed5bSDimitry Andric       return PGOHash::CXXCatchStmt;
21859d1ed5bSDimitry Andric     case Stmt::ConditionalOperatorClass:
21959d1ed5bSDimitry Andric       return PGOHash::ConditionalOperator;
22059d1ed5bSDimitry Andric     case Stmt::BinaryConditionalOperatorClass:
22159d1ed5bSDimitry Andric       return PGOHash::BinaryConditionalOperator;
22259d1ed5bSDimitry Andric     case Stmt::BinaryOperatorClass: {
22359d1ed5bSDimitry Andric       const BinaryOperator *BO = cast<BinaryOperator>(S);
22459d1ed5bSDimitry Andric       if (BO->getOpcode() == BO_LAnd)
22559d1ed5bSDimitry Andric         return PGOHash::BinaryOperatorLAnd;
22659d1ed5bSDimitry Andric       if (BO->getOpcode() == BO_LOr)
22759d1ed5bSDimitry Andric         return PGOHash::BinaryOperatorLOr;
22859d1ed5bSDimitry Andric       break;
22959d1ed5bSDimitry Andric     }
23059d1ed5bSDimitry Andric     }
23159d1ed5bSDimitry Andric     return PGOHash::None;
23259d1ed5bSDimitry Andric   }
23359d1ed5bSDimitry Andric };
23459d1ed5bSDimitry Andric 
23559d1ed5bSDimitry Andric /// A StmtVisitor that propagates the raw counts through the AST and
23659d1ed5bSDimitry Andric /// records the count at statements where the value may change.
23759d1ed5bSDimitry Andric struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
23859d1ed5bSDimitry Andric   /// PGO state.
23959d1ed5bSDimitry Andric   CodeGenPGO &PGO;
24059d1ed5bSDimitry Andric 
24159d1ed5bSDimitry Andric   /// A flag that is set when the current count should be recorded on the
24259d1ed5bSDimitry Andric   /// next statement, such as at the exit of a loop.
24359d1ed5bSDimitry Andric   bool RecordNextStmtCount;
24459d1ed5bSDimitry Andric 
24533956c43SDimitry Andric   /// The count at the current location in the traversal.
24633956c43SDimitry Andric   uint64_t CurrentCount;
24733956c43SDimitry Andric 
24859d1ed5bSDimitry Andric   /// The map of statements to count values.
24959d1ed5bSDimitry Andric   llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
25059d1ed5bSDimitry Andric 
25159d1ed5bSDimitry Andric   /// BreakContinueStack - Keep counts of breaks and continues inside loops.
25259d1ed5bSDimitry Andric   struct BreakContinue {
25359d1ed5bSDimitry Andric     uint64_t BreakCount;
25459d1ed5bSDimitry Andric     uint64_t ContinueCount;
25559d1ed5bSDimitry Andric     BreakContinue() : BreakCount(0), ContinueCount(0) {}
25659d1ed5bSDimitry Andric   };
25759d1ed5bSDimitry Andric   SmallVector<BreakContinue, 8> BreakContinueStack;
25859d1ed5bSDimitry Andric 
25959d1ed5bSDimitry Andric   ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
26059d1ed5bSDimitry Andric                       CodeGenPGO &PGO)
26159d1ed5bSDimitry Andric       : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
26259d1ed5bSDimitry Andric 
26359d1ed5bSDimitry Andric   void RecordStmtCount(const Stmt *S) {
26459d1ed5bSDimitry Andric     if (RecordNextStmtCount) {
26533956c43SDimitry Andric       CountMap[S] = CurrentCount;
26659d1ed5bSDimitry Andric       RecordNextStmtCount = false;
26759d1ed5bSDimitry Andric     }
26859d1ed5bSDimitry Andric   }
26959d1ed5bSDimitry Andric 
27033956c43SDimitry Andric   /// Set and return the current count.
27133956c43SDimitry Andric   uint64_t setCount(uint64_t Count) {
27233956c43SDimitry Andric     CurrentCount = Count;
27333956c43SDimitry Andric     return Count;
27433956c43SDimitry Andric   }
27533956c43SDimitry Andric 
27659d1ed5bSDimitry Andric   void VisitStmt(const Stmt *S) {
27759d1ed5bSDimitry Andric     RecordStmtCount(S);
27859d1ed5bSDimitry Andric     for (Stmt::const_child_range I = S->children(); I; ++I) {
27959d1ed5bSDimitry Andric       if (*I)
28059d1ed5bSDimitry Andric         this->Visit(*I);
28159d1ed5bSDimitry Andric     }
28259d1ed5bSDimitry Andric   }
28359d1ed5bSDimitry Andric 
28459d1ed5bSDimitry Andric   void VisitFunctionDecl(const FunctionDecl *D) {
28559d1ed5bSDimitry Andric     // Counter tracks entry to the function body.
28633956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
28733956c43SDimitry Andric     CountMap[D->getBody()] = BodyCount;
28859d1ed5bSDimitry Andric     Visit(D->getBody());
28959d1ed5bSDimitry Andric   }
29059d1ed5bSDimitry Andric 
29159d1ed5bSDimitry Andric   // Skip lambda expressions. We visit these as FunctionDecls when we're
29259d1ed5bSDimitry Andric   // generating them and aren't interested in the body when generating a
29359d1ed5bSDimitry Andric   // parent context.
29459d1ed5bSDimitry Andric   void VisitLambdaExpr(const LambdaExpr *LE) {}
29559d1ed5bSDimitry Andric 
29659d1ed5bSDimitry Andric   void VisitCapturedDecl(const CapturedDecl *D) {
29759d1ed5bSDimitry Andric     // Counter tracks entry to the capture body.
29833956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
29933956c43SDimitry Andric     CountMap[D->getBody()] = BodyCount;
30059d1ed5bSDimitry Andric     Visit(D->getBody());
30159d1ed5bSDimitry Andric   }
30259d1ed5bSDimitry Andric 
30359d1ed5bSDimitry Andric   void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
30459d1ed5bSDimitry Andric     // Counter tracks entry to the method body.
30533956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
30633956c43SDimitry Andric     CountMap[D->getBody()] = BodyCount;
30759d1ed5bSDimitry Andric     Visit(D->getBody());
30859d1ed5bSDimitry Andric   }
30959d1ed5bSDimitry Andric 
31059d1ed5bSDimitry Andric   void VisitBlockDecl(const BlockDecl *D) {
31159d1ed5bSDimitry Andric     // Counter tracks entry to the block body.
31233956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
31333956c43SDimitry Andric     CountMap[D->getBody()] = BodyCount;
31459d1ed5bSDimitry Andric     Visit(D->getBody());
31559d1ed5bSDimitry Andric   }
31659d1ed5bSDimitry Andric 
31759d1ed5bSDimitry Andric   void VisitReturnStmt(const ReturnStmt *S) {
31859d1ed5bSDimitry Andric     RecordStmtCount(S);
31959d1ed5bSDimitry Andric     if (S->getRetValue())
32059d1ed5bSDimitry Andric       Visit(S->getRetValue());
32133956c43SDimitry Andric     CurrentCount = 0;
32233956c43SDimitry Andric     RecordNextStmtCount = true;
32333956c43SDimitry Andric   }
32433956c43SDimitry Andric 
32533956c43SDimitry Andric   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
32633956c43SDimitry Andric     RecordStmtCount(E);
32733956c43SDimitry Andric     if (E->getSubExpr())
32833956c43SDimitry Andric       Visit(E->getSubExpr());
32933956c43SDimitry Andric     CurrentCount = 0;
33059d1ed5bSDimitry Andric     RecordNextStmtCount = true;
33159d1ed5bSDimitry Andric   }
33259d1ed5bSDimitry Andric 
33359d1ed5bSDimitry Andric   void VisitGotoStmt(const GotoStmt *S) {
33459d1ed5bSDimitry Andric     RecordStmtCount(S);
33533956c43SDimitry Andric     CurrentCount = 0;
33659d1ed5bSDimitry Andric     RecordNextStmtCount = true;
33759d1ed5bSDimitry Andric   }
33859d1ed5bSDimitry Andric 
33959d1ed5bSDimitry Andric   void VisitLabelStmt(const LabelStmt *S) {
34059d1ed5bSDimitry Andric     RecordNextStmtCount = false;
34159d1ed5bSDimitry Andric     // Counter tracks the block following the label.
34233956c43SDimitry Andric     uint64_t BlockCount = setCount(PGO.getRegionCount(S));
34333956c43SDimitry Andric     CountMap[S] = BlockCount;
34459d1ed5bSDimitry Andric     Visit(S->getSubStmt());
34559d1ed5bSDimitry Andric   }
34659d1ed5bSDimitry Andric 
34759d1ed5bSDimitry Andric   void VisitBreakStmt(const BreakStmt *S) {
34859d1ed5bSDimitry Andric     RecordStmtCount(S);
34959d1ed5bSDimitry Andric     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
35033956c43SDimitry Andric     BreakContinueStack.back().BreakCount += CurrentCount;
35133956c43SDimitry Andric     CurrentCount = 0;
35259d1ed5bSDimitry Andric     RecordNextStmtCount = true;
35359d1ed5bSDimitry Andric   }
35459d1ed5bSDimitry Andric 
35559d1ed5bSDimitry Andric   void VisitContinueStmt(const ContinueStmt *S) {
35659d1ed5bSDimitry Andric     RecordStmtCount(S);
35759d1ed5bSDimitry Andric     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
35833956c43SDimitry Andric     BreakContinueStack.back().ContinueCount += CurrentCount;
35933956c43SDimitry Andric     CurrentCount = 0;
36059d1ed5bSDimitry Andric     RecordNextStmtCount = true;
36159d1ed5bSDimitry Andric   }
36259d1ed5bSDimitry Andric 
36359d1ed5bSDimitry Andric   void VisitWhileStmt(const WhileStmt *S) {
36459d1ed5bSDimitry Andric     RecordStmtCount(S);
36533956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
36633956c43SDimitry Andric 
36759d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
36859d1ed5bSDimitry Andric     // Visit the body region first so the break/continue adjustments can be
36959d1ed5bSDimitry Andric     // included when visiting the condition.
37033956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
37133956c43SDimitry Andric     CountMap[S->getBody()] = CurrentCount;
37259d1ed5bSDimitry Andric     Visit(S->getBody());
37333956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
37459d1ed5bSDimitry Andric 
37559d1ed5bSDimitry Andric     // ...then go back and propagate counts through the condition. The count
37659d1ed5bSDimitry Andric     // at the start of the condition is the sum of the incoming edges,
37759d1ed5bSDimitry Andric     // the backedge from the end of the loop body, and the edges from
37859d1ed5bSDimitry Andric     // continue statements.
37959d1ed5bSDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
38033956c43SDimitry Andric     uint64_t CondCount =
38133956c43SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
38233956c43SDimitry Andric     CountMap[S->getCond()] = CondCount;
38359d1ed5bSDimitry Andric     Visit(S->getCond());
38433956c43SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
38559d1ed5bSDimitry Andric     RecordNextStmtCount = true;
38659d1ed5bSDimitry Andric   }
38759d1ed5bSDimitry Andric 
38859d1ed5bSDimitry Andric   void VisitDoStmt(const DoStmt *S) {
38959d1ed5bSDimitry Andric     RecordStmtCount(S);
39033956c43SDimitry Andric     uint64_t LoopCount = PGO.getRegionCount(S);
39133956c43SDimitry Andric 
39259d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
39333956c43SDimitry Andric     // The count doesn't include the fallthrough from the parent scope. Add it.
39433956c43SDimitry Andric     uint64_t BodyCount = setCount(LoopCount + CurrentCount);
39533956c43SDimitry Andric     CountMap[S->getBody()] = BodyCount;
39659d1ed5bSDimitry Andric     Visit(S->getBody());
39733956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
39859d1ed5bSDimitry Andric 
39959d1ed5bSDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
40059d1ed5bSDimitry Andric     // The count at the start of the condition is equal to the count at the
40133956c43SDimitry Andric     // end of the body, plus any continues.
40233956c43SDimitry Andric     uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
40333956c43SDimitry Andric     CountMap[S->getCond()] = CondCount;
40459d1ed5bSDimitry Andric     Visit(S->getCond());
40533956c43SDimitry Andric     setCount(BC.BreakCount + CondCount - LoopCount);
40659d1ed5bSDimitry Andric     RecordNextStmtCount = true;
40759d1ed5bSDimitry Andric   }
40859d1ed5bSDimitry Andric 
40959d1ed5bSDimitry Andric   void VisitForStmt(const ForStmt *S) {
41059d1ed5bSDimitry Andric     RecordStmtCount(S);
41159d1ed5bSDimitry Andric     if (S->getInit())
41259d1ed5bSDimitry Andric       Visit(S->getInit());
41333956c43SDimitry Andric 
41433956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
41533956c43SDimitry Andric 
41659d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
41759d1ed5bSDimitry Andric     // Visit the body region first. (This is basically the same as a while
41859d1ed5bSDimitry Andric     // loop; see further comments in VisitWhileStmt.)
41933956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
42033956c43SDimitry Andric     CountMap[S->getBody()] = BodyCount;
42159d1ed5bSDimitry Andric     Visit(S->getBody());
42233956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
42333956c43SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
42459d1ed5bSDimitry Andric 
42559d1ed5bSDimitry Andric     // The increment is essentially part of the body but it needs to include
42659d1ed5bSDimitry Andric     // the count for all the continue statements.
42759d1ed5bSDimitry Andric     if (S->getInc()) {
42833956c43SDimitry Andric       uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
42933956c43SDimitry Andric       CountMap[S->getInc()] = IncCount;
43059d1ed5bSDimitry Andric       Visit(S->getInc());
43159d1ed5bSDimitry Andric     }
43259d1ed5bSDimitry Andric 
43359d1ed5bSDimitry Andric     // ...then go back and propagate counts through the condition.
43433956c43SDimitry Andric     uint64_t CondCount =
43533956c43SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
43659d1ed5bSDimitry Andric     if (S->getCond()) {
43733956c43SDimitry Andric       CountMap[S->getCond()] = CondCount;
43859d1ed5bSDimitry Andric       Visit(S->getCond());
43959d1ed5bSDimitry Andric     }
44033956c43SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
44159d1ed5bSDimitry Andric     RecordNextStmtCount = true;
44259d1ed5bSDimitry Andric   }
44359d1ed5bSDimitry Andric 
44459d1ed5bSDimitry Andric   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
44559d1ed5bSDimitry Andric     RecordStmtCount(S);
44633956c43SDimitry Andric     Visit(S->getLoopVarStmt());
44759d1ed5bSDimitry Andric     Visit(S->getRangeStmt());
44859d1ed5bSDimitry Andric     Visit(S->getBeginEndStmt());
44933956c43SDimitry Andric 
45033956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
45159d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
45259d1ed5bSDimitry Andric     // Visit the body region first. (This is basically the same as a while
45359d1ed5bSDimitry Andric     // loop; see further comments in VisitWhileStmt.)
45433956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
45533956c43SDimitry Andric     CountMap[S->getBody()] = BodyCount;
45659d1ed5bSDimitry Andric     Visit(S->getBody());
45733956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
45833956c43SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
45959d1ed5bSDimitry Andric 
46059d1ed5bSDimitry Andric     // The increment is essentially part of the body but it needs to include
46159d1ed5bSDimitry Andric     // the count for all the continue statements.
46233956c43SDimitry Andric     uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
46333956c43SDimitry Andric     CountMap[S->getInc()] = IncCount;
46459d1ed5bSDimitry Andric     Visit(S->getInc());
46559d1ed5bSDimitry Andric 
46659d1ed5bSDimitry Andric     // ...then go back and propagate counts through the condition.
46733956c43SDimitry Andric     uint64_t CondCount =
46833956c43SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
46933956c43SDimitry Andric     CountMap[S->getCond()] = CondCount;
47059d1ed5bSDimitry Andric     Visit(S->getCond());
47133956c43SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
47259d1ed5bSDimitry Andric     RecordNextStmtCount = true;
47359d1ed5bSDimitry Andric   }
47459d1ed5bSDimitry Andric 
47559d1ed5bSDimitry Andric   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
47659d1ed5bSDimitry Andric     RecordStmtCount(S);
47759d1ed5bSDimitry Andric     Visit(S->getElement());
47833956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
47959d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
48033956c43SDimitry Andric     // Counter tracks the body of the loop.
48133956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
48233956c43SDimitry Andric     CountMap[S->getBody()] = BodyCount;
48359d1ed5bSDimitry Andric     Visit(S->getBody());
48433956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
48559d1ed5bSDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
48633956c43SDimitry Andric 
48733956c43SDimitry Andric     setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
48833956c43SDimitry Andric              BodyCount);
48959d1ed5bSDimitry Andric     RecordNextStmtCount = true;
49059d1ed5bSDimitry Andric   }
49159d1ed5bSDimitry Andric 
49259d1ed5bSDimitry Andric   void VisitSwitchStmt(const SwitchStmt *S) {
49359d1ed5bSDimitry Andric     RecordStmtCount(S);
49459d1ed5bSDimitry Andric     Visit(S->getCond());
49533956c43SDimitry Andric     CurrentCount = 0;
49659d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
49759d1ed5bSDimitry Andric     Visit(S->getBody());
49859d1ed5bSDimitry Andric     // If the switch is inside a loop, add the continue counts.
49959d1ed5bSDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
50059d1ed5bSDimitry Andric     if (!BreakContinueStack.empty())
50159d1ed5bSDimitry Andric       BreakContinueStack.back().ContinueCount += BC.ContinueCount;
50259d1ed5bSDimitry Andric     // Counter tracks the exit block of the switch.
50333956c43SDimitry Andric     setCount(PGO.getRegionCount(S));
50459d1ed5bSDimitry Andric     RecordNextStmtCount = true;
50559d1ed5bSDimitry Andric   }
50659d1ed5bSDimitry Andric 
50733956c43SDimitry Andric   void VisitSwitchCase(const SwitchCase *S) {
50859d1ed5bSDimitry Andric     RecordNextStmtCount = false;
50959d1ed5bSDimitry Andric     // Counter for this particular case. This counts only jumps from the
51059d1ed5bSDimitry Andric     // switch header and does not include fallthrough from the case before
51159d1ed5bSDimitry Andric     // this one.
51233956c43SDimitry Andric     uint64_t CaseCount = PGO.getRegionCount(S);
51333956c43SDimitry Andric     setCount(CurrentCount + CaseCount);
51433956c43SDimitry Andric     // We need the count without fallthrough in the mapping, so it's more useful
51533956c43SDimitry Andric     // for branch probabilities.
51633956c43SDimitry Andric     CountMap[S] = CaseCount;
51759d1ed5bSDimitry Andric     RecordNextStmtCount = true;
51859d1ed5bSDimitry Andric     Visit(S->getSubStmt());
51959d1ed5bSDimitry Andric   }
52059d1ed5bSDimitry Andric 
52159d1ed5bSDimitry Andric   void VisitIfStmt(const IfStmt *S) {
52259d1ed5bSDimitry Andric     RecordStmtCount(S);
52333956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
52459d1ed5bSDimitry Andric     Visit(S->getCond());
52559d1ed5bSDimitry Andric 
52633956c43SDimitry Andric     // Counter tracks the "then" part of an if statement. The count for
52733956c43SDimitry Andric     // the "else" part, if it exists, will be calculated from this counter.
52833956c43SDimitry Andric     uint64_t ThenCount = setCount(PGO.getRegionCount(S));
52933956c43SDimitry Andric     CountMap[S->getThen()] = ThenCount;
53059d1ed5bSDimitry Andric     Visit(S->getThen());
53133956c43SDimitry Andric     uint64_t OutCount = CurrentCount;
53259d1ed5bSDimitry Andric 
53333956c43SDimitry Andric     uint64_t ElseCount = ParentCount - ThenCount;
53459d1ed5bSDimitry Andric     if (S->getElse()) {
53533956c43SDimitry Andric       setCount(ElseCount);
53633956c43SDimitry Andric       CountMap[S->getElse()] = ElseCount;
53759d1ed5bSDimitry Andric       Visit(S->getElse());
53833956c43SDimitry Andric       OutCount += CurrentCount;
53933956c43SDimitry Andric     } else
54033956c43SDimitry Andric       OutCount += ElseCount;
54133956c43SDimitry Andric     setCount(OutCount);
54259d1ed5bSDimitry Andric     RecordNextStmtCount = true;
54359d1ed5bSDimitry Andric   }
54459d1ed5bSDimitry Andric 
54559d1ed5bSDimitry Andric   void VisitCXXTryStmt(const CXXTryStmt *S) {
54659d1ed5bSDimitry Andric     RecordStmtCount(S);
54759d1ed5bSDimitry Andric     Visit(S->getTryBlock());
54859d1ed5bSDimitry Andric     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
54959d1ed5bSDimitry Andric       Visit(S->getHandler(I));
55059d1ed5bSDimitry Andric     // Counter tracks the continuation block of the try statement.
55133956c43SDimitry Andric     setCount(PGO.getRegionCount(S));
55259d1ed5bSDimitry Andric     RecordNextStmtCount = true;
55359d1ed5bSDimitry Andric   }
55459d1ed5bSDimitry Andric 
55559d1ed5bSDimitry Andric   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
55659d1ed5bSDimitry Andric     RecordNextStmtCount = false;
55759d1ed5bSDimitry Andric     // Counter tracks the catch statement's handler block.
55833956c43SDimitry Andric     uint64_t CatchCount = setCount(PGO.getRegionCount(S));
55933956c43SDimitry Andric     CountMap[S] = CatchCount;
56059d1ed5bSDimitry Andric     Visit(S->getHandlerBlock());
56159d1ed5bSDimitry Andric   }
56259d1ed5bSDimitry Andric 
56333956c43SDimitry Andric   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
56459d1ed5bSDimitry Andric     RecordStmtCount(E);
56533956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
56659d1ed5bSDimitry Andric     Visit(E->getCond());
56759d1ed5bSDimitry Andric 
56833956c43SDimitry Andric     // Counter tracks the "true" part of a conditional operator. The
56933956c43SDimitry Andric     // count in the "false" part will be calculated from this counter.
57033956c43SDimitry Andric     uint64_t TrueCount = setCount(PGO.getRegionCount(E));
57133956c43SDimitry Andric     CountMap[E->getTrueExpr()] = TrueCount;
57259d1ed5bSDimitry Andric     Visit(E->getTrueExpr());
57333956c43SDimitry Andric     uint64_t OutCount = CurrentCount;
57459d1ed5bSDimitry Andric 
57533956c43SDimitry Andric     uint64_t FalseCount = setCount(ParentCount - TrueCount);
57633956c43SDimitry Andric     CountMap[E->getFalseExpr()] = FalseCount;
57759d1ed5bSDimitry Andric     Visit(E->getFalseExpr());
57833956c43SDimitry Andric     OutCount += CurrentCount;
57959d1ed5bSDimitry Andric 
58033956c43SDimitry Andric     setCount(OutCount);
58159d1ed5bSDimitry Andric     RecordNextStmtCount = true;
58259d1ed5bSDimitry Andric   }
58359d1ed5bSDimitry Andric 
58459d1ed5bSDimitry Andric   void VisitBinLAnd(const BinaryOperator *E) {
58559d1ed5bSDimitry Andric     RecordStmtCount(E);
58633956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
58759d1ed5bSDimitry Andric     Visit(E->getLHS());
58833956c43SDimitry Andric     // Counter tracks the right hand side of a logical and operator.
58933956c43SDimitry Andric     uint64_t RHSCount = setCount(PGO.getRegionCount(E));
59033956c43SDimitry Andric     CountMap[E->getRHS()] = RHSCount;
59159d1ed5bSDimitry Andric     Visit(E->getRHS());
59233956c43SDimitry Andric     setCount(ParentCount + RHSCount - CurrentCount);
59359d1ed5bSDimitry Andric     RecordNextStmtCount = true;
59459d1ed5bSDimitry Andric   }
59559d1ed5bSDimitry Andric 
59659d1ed5bSDimitry Andric   void VisitBinLOr(const BinaryOperator *E) {
59759d1ed5bSDimitry Andric     RecordStmtCount(E);
59833956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
59959d1ed5bSDimitry Andric     Visit(E->getLHS());
60033956c43SDimitry Andric     // Counter tracks the right hand side of a logical or operator.
60133956c43SDimitry Andric     uint64_t RHSCount = setCount(PGO.getRegionCount(E));
60233956c43SDimitry Andric     CountMap[E->getRHS()] = RHSCount;
60359d1ed5bSDimitry Andric     Visit(E->getRHS());
60433956c43SDimitry Andric     setCount(ParentCount + RHSCount - CurrentCount);
60559d1ed5bSDimitry Andric     RecordNextStmtCount = true;
60659d1ed5bSDimitry Andric   }
60759d1ed5bSDimitry Andric };
60859d1ed5bSDimitry Andric }
60959d1ed5bSDimitry Andric 
61059d1ed5bSDimitry Andric void PGOHash::combine(HashType Type) {
61159d1ed5bSDimitry Andric   // Check that we never combine 0 and only have six bits.
61259d1ed5bSDimitry Andric   assert(Type && "Hash is invalid: unexpected type 0");
61359d1ed5bSDimitry Andric   assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
61459d1ed5bSDimitry Andric 
61559d1ed5bSDimitry Andric   // Pass through MD5 if enough work has built up.
61659d1ed5bSDimitry Andric   if (Count && Count % NumTypesPerWord == 0) {
61759d1ed5bSDimitry Andric     using namespace llvm::support;
61859d1ed5bSDimitry Andric     uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
61959d1ed5bSDimitry Andric     MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
62059d1ed5bSDimitry Andric     Working = 0;
62159d1ed5bSDimitry Andric   }
62259d1ed5bSDimitry Andric 
62359d1ed5bSDimitry Andric   // Accumulate the current type.
62459d1ed5bSDimitry Andric   ++Count;
62559d1ed5bSDimitry Andric   Working = Working << NumBitsPerType | Type;
62659d1ed5bSDimitry Andric }
62759d1ed5bSDimitry Andric 
62859d1ed5bSDimitry Andric uint64_t PGOHash::finalize() {
62959d1ed5bSDimitry Andric   // Use Working as the hash directly if we never used MD5.
63059d1ed5bSDimitry Andric   if (Count <= NumTypesPerWord)
63159d1ed5bSDimitry Andric     // No need to byte swap here, since none of the math was endian-dependent.
63259d1ed5bSDimitry Andric     // This number will be byte-swapped as required on endianness transitions,
63359d1ed5bSDimitry Andric     // so we will see the same value on the other side.
63459d1ed5bSDimitry Andric     return Working;
63559d1ed5bSDimitry Andric 
63659d1ed5bSDimitry Andric   // Check for remaining work in Working.
63759d1ed5bSDimitry Andric   if (Working)
63859d1ed5bSDimitry Andric     MD5.update(Working);
63959d1ed5bSDimitry Andric 
64059d1ed5bSDimitry Andric   // Finalize the MD5 and return the hash.
64159d1ed5bSDimitry Andric   llvm::MD5::MD5Result Result;
64259d1ed5bSDimitry Andric   MD5.final(Result);
64359d1ed5bSDimitry Andric   using namespace llvm::support;
64459d1ed5bSDimitry Andric   return endian::read<uint64_t, little, unaligned>(Result);
64559d1ed5bSDimitry Andric }
64659d1ed5bSDimitry Andric 
64739d628a0SDimitry Andric void CodeGenPGO::checkGlobalDecl(GlobalDecl GD) {
64839d628a0SDimitry Andric   // Make sure we only emit coverage mapping for one constructor/destructor.
64939d628a0SDimitry Andric   // Clang emits several functions for the constructor and the destructor of
65039d628a0SDimitry Andric   // a class. Every function is instrumented, but we only want to provide
65139d628a0SDimitry Andric   // coverage for one of them. Because of that we only emit the coverage mapping
65239d628a0SDimitry Andric   // for the base constructor/destructor.
65339d628a0SDimitry Andric   if ((isa<CXXConstructorDecl>(GD.getDecl()) &&
65439d628a0SDimitry Andric        GD.getCtorType() != Ctor_Base) ||
65539d628a0SDimitry Andric       (isa<CXXDestructorDecl>(GD.getDecl()) &&
65639d628a0SDimitry Andric        GD.getDtorType() != Dtor_Base)) {
65739d628a0SDimitry Andric     SkipCoverageMapping = true;
65839d628a0SDimitry Andric   }
65959d1ed5bSDimitry Andric }
66059d1ed5bSDimitry Andric 
66159d1ed5bSDimitry Andric void CodeGenPGO::assignRegionCounters(const Decl *D, llvm::Function *Fn) {
66259d1ed5bSDimitry Andric   bool InstrumentRegions = CGM.getCodeGenOpts().ProfileInstrGenerate;
66359d1ed5bSDimitry Andric   llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
66459d1ed5bSDimitry Andric   if (!InstrumentRegions && !PGOReader)
66559d1ed5bSDimitry Andric     return;
66659d1ed5bSDimitry Andric   if (D->isImplicit())
66759d1ed5bSDimitry Andric     return;
66839d628a0SDimitry Andric   CGM.ClearUnusedCoverageMapping(D);
66959d1ed5bSDimitry Andric   setFuncName(Fn);
67059d1ed5bSDimitry Andric 
67159d1ed5bSDimitry Andric   mapRegionCounters(D);
67239d628a0SDimitry Andric   if (CGM.getCodeGenOpts().CoverageMapping)
67339d628a0SDimitry Andric     emitCounterRegionMapping(D);
67459d1ed5bSDimitry Andric   if (PGOReader) {
67559d1ed5bSDimitry Andric     SourceManager &SM = CGM.getContext().getSourceManager();
67659d1ed5bSDimitry Andric     loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
67759d1ed5bSDimitry Andric     computeRegionCounts(D);
67859d1ed5bSDimitry Andric     applyFunctionAttributes(PGOReader, Fn);
67959d1ed5bSDimitry Andric   }
68059d1ed5bSDimitry Andric }
68159d1ed5bSDimitry Andric 
68259d1ed5bSDimitry Andric void CodeGenPGO::mapRegionCounters(const Decl *D) {
68359d1ed5bSDimitry Andric   RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
68459d1ed5bSDimitry Andric   MapRegionCounters Walker(*RegionCounterMap);
68559d1ed5bSDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
68659d1ed5bSDimitry Andric     Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
68759d1ed5bSDimitry Andric   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
68859d1ed5bSDimitry Andric     Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
68959d1ed5bSDimitry Andric   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
69059d1ed5bSDimitry Andric     Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
69159d1ed5bSDimitry Andric   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
69259d1ed5bSDimitry Andric     Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
69359d1ed5bSDimitry Andric   assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
69459d1ed5bSDimitry Andric   NumRegionCounters = Walker.NextCounter;
69559d1ed5bSDimitry Andric   FunctionHash = Walker.Hash.finalize();
69659d1ed5bSDimitry Andric }
69759d1ed5bSDimitry Andric 
69839d628a0SDimitry Andric void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
69939d628a0SDimitry Andric   if (SkipCoverageMapping)
70039d628a0SDimitry Andric     return;
70139d628a0SDimitry Andric   // Don't map the functions inside the system headers
70239d628a0SDimitry Andric   auto Loc = D->getBody()->getLocStart();
70339d628a0SDimitry Andric   if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
70439d628a0SDimitry Andric     return;
70539d628a0SDimitry Andric 
70639d628a0SDimitry Andric   std::string CoverageMapping;
70739d628a0SDimitry Andric   llvm::raw_string_ostream OS(CoverageMapping);
70839d628a0SDimitry Andric   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
70939d628a0SDimitry Andric                                 CGM.getContext().getSourceManager(),
71039d628a0SDimitry Andric                                 CGM.getLangOpts(), RegionCounterMap.get());
71139d628a0SDimitry Andric   MappingGen.emitCounterMapping(D, OS);
71239d628a0SDimitry Andric   OS.flush();
71339d628a0SDimitry Andric 
71439d628a0SDimitry Andric   if (CoverageMapping.empty())
71539d628a0SDimitry Andric     return;
71639d628a0SDimitry Andric 
71739d628a0SDimitry Andric   CGM.getCoverageMapping()->addFunctionMappingRecord(
71839d628a0SDimitry Andric       FuncNameVar, FuncName, FunctionHash, CoverageMapping);
71939d628a0SDimitry Andric }
72039d628a0SDimitry Andric 
72139d628a0SDimitry Andric void
72233956c43SDimitry Andric CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
72339d628a0SDimitry Andric                                     llvm::GlobalValue::LinkageTypes Linkage) {
72439d628a0SDimitry Andric   if (SkipCoverageMapping)
72539d628a0SDimitry Andric     return;
72639d628a0SDimitry Andric   // Don't map the functions inside the system headers
72739d628a0SDimitry Andric   auto Loc = D->getBody()->getLocStart();
72839d628a0SDimitry Andric   if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
72939d628a0SDimitry Andric     return;
73039d628a0SDimitry Andric 
73139d628a0SDimitry Andric   std::string CoverageMapping;
73239d628a0SDimitry Andric   llvm::raw_string_ostream OS(CoverageMapping);
73339d628a0SDimitry Andric   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
73439d628a0SDimitry Andric                                 CGM.getContext().getSourceManager(),
73539d628a0SDimitry Andric                                 CGM.getLangOpts());
73639d628a0SDimitry Andric   MappingGen.emitEmptyMapping(D, OS);
73739d628a0SDimitry Andric   OS.flush();
73839d628a0SDimitry Andric 
73939d628a0SDimitry Andric   if (CoverageMapping.empty())
74039d628a0SDimitry Andric     return;
74139d628a0SDimitry Andric 
74233956c43SDimitry Andric   setFuncName(Name, Linkage);
74339d628a0SDimitry Andric   CGM.getCoverageMapping()->addFunctionMappingRecord(
74439d628a0SDimitry Andric       FuncNameVar, FuncName, FunctionHash, CoverageMapping);
74539d628a0SDimitry Andric }
74639d628a0SDimitry Andric 
74759d1ed5bSDimitry Andric void CodeGenPGO::computeRegionCounts(const Decl *D) {
74859d1ed5bSDimitry Andric   StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
74959d1ed5bSDimitry Andric   ComputeRegionCounts Walker(*StmtCountMap, *this);
75059d1ed5bSDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
75159d1ed5bSDimitry Andric     Walker.VisitFunctionDecl(FD);
75259d1ed5bSDimitry Andric   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
75359d1ed5bSDimitry Andric     Walker.VisitObjCMethodDecl(MD);
75459d1ed5bSDimitry Andric   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
75559d1ed5bSDimitry Andric     Walker.VisitBlockDecl(BD);
75659d1ed5bSDimitry Andric   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
75759d1ed5bSDimitry Andric     Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
75859d1ed5bSDimitry Andric }
75959d1ed5bSDimitry Andric 
76059d1ed5bSDimitry Andric void
76159d1ed5bSDimitry Andric CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
76259d1ed5bSDimitry Andric                                     llvm::Function *Fn) {
76359d1ed5bSDimitry Andric   if (!haveRegionCounts())
76459d1ed5bSDimitry Andric     return;
76559d1ed5bSDimitry Andric 
76659d1ed5bSDimitry Andric   uint64_t MaxFunctionCount = PGOReader->getMaximumFunctionCount();
76759d1ed5bSDimitry Andric   uint64_t FunctionCount = getRegionCount(0);
76859d1ed5bSDimitry Andric   if (FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount))
76959d1ed5bSDimitry Andric     // Turn on InlineHint attribute for hot functions.
77059d1ed5bSDimitry Andric     // FIXME: 30% is from preliminary tuning on SPEC, it may not be optimal.
77159d1ed5bSDimitry Andric     Fn->addFnAttr(llvm::Attribute::InlineHint);
77259d1ed5bSDimitry Andric   else if (FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount))
77359d1ed5bSDimitry Andric     // Turn on Cold attribute for cold functions.
77459d1ed5bSDimitry Andric     // FIXME: 1% is from preliminary tuning on SPEC, it may not be optimal.
77559d1ed5bSDimitry Andric     Fn->addFnAttr(llvm::Attribute::Cold);
77659d1ed5bSDimitry Andric }
77759d1ed5bSDimitry Andric 
77833956c43SDimitry Andric void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S) {
77939d628a0SDimitry Andric   if (!CGM.getCodeGenOpts().ProfileInstrGenerate || !RegionCounterMap)
78059d1ed5bSDimitry Andric     return;
78139d628a0SDimitry Andric   if (!Builder.GetInsertPoint())
78239d628a0SDimitry Andric     return;
78333956c43SDimitry Andric 
78433956c43SDimitry Andric   unsigned Counter = (*RegionCounterMap)[S];
78539d628a0SDimitry Andric   auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
78633956c43SDimitry Andric   Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
78733956c43SDimitry Andric                      {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
78839d628a0SDimitry Andric                       Builder.getInt64(FunctionHash),
78939d628a0SDimitry Andric                       Builder.getInt32(NumRegionCounters),
79033956c43SDimitry Andric                       Builder.getInt32(Counter)});
79159d1ed5bSDimitry Andric }
79259d1ed5bSDimitry Andric 
79359d1ed5bSDimitry Andric void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
79459d1ed5bSDimitry Andric                                   bool IsInMainFile) {
79559d1ed5bSDimitry Andric   CGM.getPGOStats().addVisited(IsInMainFile);
79639d628a0SDimitry Andric   RegionCounts.clear();
79739d628a0SDimitry Andric   if (std::error_code EC =
79839d628a0SDimitry Andric           PGOReader->getFunctionCounts(FuncName, FunctionHash, RegionCounts)) {
79939d628a0SDimitry Andric     if (EC == llvm::instrprof_error::unknown_function)
80059d1ed5bSDimitry Andric       CGM.getPGOStats().addMissing(IsInMainFile);
80139d628a0SDimitry Andric     else if (EC == llvm::instrprof_error::hash_mismatch)
80259d1ed5bSDimitry Andric       CGM.getPGOStats().addMismatched(IsInMainFile);
80339d628a0SDimitry Andric     else if (EC == llvm::instrprof_error::malformed)
80439d628a0SDimitry Andric       // TODO: Consider a more specific warning for this case.
80539d628a0SDimitry Andric       CGM.getPGOStats().addMismatched(IsInMainFile);
80639d628a0SDimitry Andric     RegionCounts.clear();
80759d1ed5bSDimitry Andric   }
80859d1ed5bSDimitry Andric }
80959d1ed5bSDimitry Andric 
81059d1ed5bSDimitry Andric /// \brief Calculate what to divide by to scale weights.
81159d1ed5bSDimitry Andric ///
81259d1ed5bSDimitry Andric /// Given the maximum weight, calculate a divisor that will scale all the
81359d1ed5bSDimitry Andric /// weights to strictly less than UINT32_MAX.
81459d1ed5bSDimitry Andric static uint64_t calculateWeightScale(uint64_t MaxWeight) {
81559d1ed5bSDimitry Andric   return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
81659d1ed5bSDimitry Andric }
81759d1ed5bSDimitry Andric 
81859d1ed5bSDimitry Andric /// \brief Scale an individual branch weight (and add 1).
81959d1ed5bSDimitry Andric ///
82059d1ed5bSDimitry Andric /// Scale a 64-bit weight down to 32-bits using \c Scale.
82159d1ed5bSDimitry Andric ///
82259d1ed5bSDimitry Andric /// According to Laplace's Rule of Succession, it is better to compute the
82359d1ed5bSDimitry Andric /// weight based on the count plus 1, so universally add 1 to the value.
82459d1ed5bSDimitry Andric ///
82559d1ed5bSDimitry Andric /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
82659d1ed5bSDimitry Andric /// greater than \c Weight.
82759d1ed5bSDimitry Andric static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
82859d1ed5bSDimitry Andric   assert(Scale && "scale by 0?");
82959d1ed5bSDimitry Andric   uint64_t Scaled = Weight / Scale + 1;
83059d1ed5bSDimitry Andric   assert(Scaled <= UINT32_MAX && "overflow 32-bits");
83159d1ed5bSDimitry Andric   return Scaled;
83259d1ed5bSDimitry Andric }
83359d1ed5bSDimitry Andric 
83433956c43SDimitry Andric llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
83559d1ed5bSDimitry Andric                                                     uint64_t FalseCount) {
83659d1ed5bSDimitry Andric   // Check for empty weights.
83759d1ed5bSDimitry Andric   if (!TrueCount && !FalseCount)
83859d1ed5bSDimitry Andric     return nullptr;
83959d1ed5bSDimitry Andric 
84059d1ed5bSDimitry Andric   // Calculate how to scale down to 32-bits.
84159d1ed5bSDimitry Andric   uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
84259d1ed5bSDimitry Andric 
84359d1ed5bSDimitry Andric   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
84459d1ed5bSDimitry Andric   return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
84559d1ed5bSDimitry Andric                                       scaleBranchWeight(FalseCount, Scale));
84659d1ed5bSDimitry Andric }
84759d1ed5bSDimitry Andric 
84833956c43SDimitry Andric llvm::MDNode *
84933956c43SDimitry Andric CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
85059d1ed5bSDimitry Andric   // We need at least two elements to create meaningful weights.
85159d1ed5bSDimitry Andric   if (Weights.size() < 2)
85259d1ed5bSDimitry Andric     return nullptr;
85359d1ed5bSDimitry Andric 
85459d1ed5bSDimitry Andric   // Check for empty weights.
85559d1ed5bSDimitry Andric   uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
85659d1ed5bSDimitry Andric   if (MaxWeight == 0)
85759d1ed5bSDimitry Andric     return nullptr;
85859d1ed5bSDimitry Andric 
85959d1ed5bSDimitry Andric   // Calculate how to scale down to 32-bits.
86059d1ed5bSDimitry Andric   uint64_t Scale = calculateWeightScale(MaxWeight);
86159d1ed5bSDimitry Andric 
86259d1ed5bSDimitry Andric   SmallVector<uint32_t, 16> ScaledWeights;
86359d1ed5bSDimitry Andric   ScaledWeights.reserve(Weights.size());
86459d1ed5bSDimitry Andric   for (uint64_t W : Weights)
86559d1ed5bSDimitry Andric     ScaledWeights.push_back(scaleBranchWeight(W, Scale));
86659d1ed5bSDimitry Andric 
86759d1ed5bSDimitry Andric   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
86859d1ed5bSDimitry Andric   return MDHelper.createBranchWeights(ScaledWeights);
86959d1ed5bSDimitry Andric }
87059d1ed5bSDimitry Andric 
87133956c43SDimitry Andric llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
87233956c43SDimitry Andric                                                            uint64_t LoopCount) {
87333956c43SDimitry Andric   if (!PGO.haveRegionCounts())
87459d1ed5bSDimitry Andric     return nullptr;
87533956c43SDimitry Andric   Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
87633956c43SDimitry Andric   assert(CondCount.hasValue() && "missing expected loop condition count");
87733956c43SDimitry Andric   if (*CondCount == 0)
87859d1ed5bSDimitry Andric     return nullptr;
87933956c43SDimitry Andric   return createProfileWeights(LoopCount,
88033956c43SDimitry Andric                               std::max(*CondCount, LoopCount) - LoopCount);
88159d1ed5bSDimitry Andric }
882