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);
2783dac3a9bSDimitry Andric     for (const Stmt *Child : S->children())
2793dac3a9bSDimitry Andric       if (Child)
2803dac3a9bSDimitry Andric         this->Visit(Child);
28159d1ed5bSDimitry Andric   }
28259d1ed5bSDimitry Andric 
28359d1ed5bSDimitry Andric   void VisitFunctionDecl(const FunctionDecl *D) {
28459d1ed5bSDimitry Andric     // Counter tracks entry to the function body.
28533956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
28633956c43SDimitry Andric     CountMap[D->getBody()] = BodyCount;
28759d1ed5bSDimitry Andric     Visit(D->getBody());
28859d1ed5bSDimitry Andric   }
28959d1ed5bSDimitry Andric 
29059d1ed5bSDimitry Andric   // Skip lambda expressions. We visit these as FunctionDecls when we're
29159d1ed5bSDimitry Andric   // generating them and aren't interested in the body when generating a
29259d1ed5bSDimitry Andric   // parent context.
29359d1ed5bSDimitry Andric   void VisitLambdaExpr(const LambdaExpr *LE) {}
29459d1ed5bSDimitry Andric 
29559d1ed5bSDimitry Andric   void VisitCapturedDecl(const CapturedDecl *D) {
29659d1ed5bSDimitry Andric     // Counter tracks entry to the capture body.
29733956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
29833956c43SDimitry Andric     CountMap[D->getBody()] = BodyCount;
29959d1ed5bSDimitry Andric     Visit(D->getBody());
30059d1ed5bSDimitry Andric   }
30159d1ed5bSDimitry Andric 
30259d1ed5bSDimitry Andric   void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
30359d1ed5bSDimitry Andric     // Counter tracks entry to the method body.
30433956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
30533956c43SDimitry Andric     CountMap[D->getBody()] = BodyCount;
30659d1ed5bSDimitry Andric     Visit(D->getBody());
30759d1ed5bSDimitry Andric   }
30859d1ed5bSDimitry Andric 
30959d1ed5bSDimitry Andric   void VisitBlockDecl(const BlockDecl *D) {
31059d1ed5bSDimitry Andric     // Counter tracks entry to the block body.
31133956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
31233956c43SDimitry Andric     CountMap[D->getBody()] = BodyCount;
31359d1ed5bSDimitry Andric     Visit(D->getBody());
31459d1ed5bSDimitry Andric   }
31559d1ed5bSDimitry Andric 
31659d1ed5bSDimitry Andric   void VisitReturnStmt(const ReturnStmt *S) {
31759d1ed5bSDimitry Andric     RecordStmtCount(S);
31859d1ed5bSDimitry Andric     if (S->getRetValue())
31959d1ed5bSDimitry Andric       Visit(S->getRetValue());
32033956c43SDimitry Andric     CurrentCount = 0;
32133956c43SDimitry Andric     RecordNextStmtCount = true;
32233956c43SDimitry Andric   }
32333956c43SDimitry Andric 
32433956c43SDimitry Andric   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
32533956c43SDimitry Andric     RecordStmtCount(E);
32633956c43SDimitry Andric     if (E->getSubExpr())
32733956c43SDimitry Andric       Visit(E->getSubExpr());
32833956c43SDimitry Andric     CurrentCount = 0;
32959d1ed5bSDimitry Andric     RecordNextStmtCount = true;
33059d1ed5bSDimitry Andric   }
33159d1ed5bSDimitry Andric 
33259d1ed5bSDimitry Andric   void VisitGotoStmt(const GotoStmt *S) {
33359d1ed5bSDimitry Andric     RecordStmtCount(S);
33433956c43SDimitry Andric     CurrentCount = 0;
33559d1ed5bSDimitry Andric     RecordNextStmtCount = true;
33659d1ed5bSDimitry Andric   }
33759d1ed5bSDimitry Andric 
33859d1ed5bSDimitry Andric   void VisitLabelStmt(const LabelStmt *S) {
33959d1ed5bSDimitry Andric     RecordNextStmtCount = false;
34059d1ed5bSDimitry Andric     // Counter tracks the block following the label.
34133956c43SDimitry Andric     uint64_t BlockCount = setCount(PGO.getRegionCount(S));
34233956c43SDimitry Andric     CountMap[S] = BlockCount;
34359d1ed5bSDimitry Andric     Visit(S->getSubStmt());
34459d1ed5bSDimitry Andric   }
34559d1ed5bSDimitry Andric 
34659d1ed5bSDimitry Andric   void VisitBreakStmt(const BreakStmt *S) {
34759d1ed5bSDimitry Andric     RecordStmtCount(S);
34859d1ed5bSDimitry Andric     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
34933956c43SDimitry Andric     BreakContinueStack.back().BreakCount += CurrentCount;
35033956c43SDimitry Andric     CurrentCount = 0;
35159d1ed5bSDimitry Andric     RecordNextStmtCount = true;
35259d1ed5bSDimitry Andric   }
35359d1ed5bSDimitry Andric 
35459d1ed5bSDimitry Andric   void VisitContinueStmt(const ContinueStmt *S) {
35559d1ed5bSDimitry Andric     RecordStmtCount(S);
35659d1ed5bSDimitry Andric     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
35733956c43SDimitry Andric     BreakContinueStack.back().ContinueCount += CurrentCount;
35833956c43SDimitry Andric     CurrentCount = 0;
35959d1ed5bSDimitry Andric     RecordNextStmtCount = true;
36059d1ed5bSDimitry Andric   }
36159d1ed5bSDimitry Andric 
36259d1ed5bSDimitry Andric   void VisitWhileStmt(const WhileStmt *S) {
36359d1ed5bSDimitry Andric     RecordStmtCount(S);
36433956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
36533956c43SDimitry Andric 
36659d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
36759d1ed5bSDimitry Andric     // Visit the body region first so the break/continue adjustments can be
36859d1ed5bSDimitry Andric     // included when visiting the condition.
36933956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
37033956c43SDimitry Andric     CountMap[S->getBody()] = CurrentCount;
37159d1ed5bSDimitry Andric     Visit(S->getBody());
37233956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
37359d1ed5bSDimitry Andric 
37459d1ed5bSDimitry Andric     // ...then go back and propagate counts through the condition. The count
37559d1ed5bSDimitry Andric     // at the start of the condition is the sum of the incoming edges,
37659d1ed5bSDimitry Andric     // the backedge from the end of the loop body, and the edges from
37759d1ed5bSDimitry Andric     // continue statements.
37859d1ed5bSDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
37933956c43SDimitry Andric     uint64_t CondCount =
38033956c43SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
38133956c43SDimitry Andric     CountMap[S->getCond()] = CondCount;
38259d1ed5bSDimitry Andric     Visit(S->getCond());
38333956c43SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
38459d1ed5bSDimitry Andric     RecordNextStmtCount = true;
38559d1ed5bSDimitry Andric   }
38659d1ed5bSDimitry Andric 
38759d1ed5bSDimitry Andric   void VisitDoStmt(const DoStmt *S) {
38859d1ed5bSDimitry Andric     RecordStmtCount(S);
38933956c43SDimitry Andric     uint64_t LoopCount = PGO.getRegionCount(S);
39033956c43SDimitry Andric 
39159d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
39233956c43SDimitry Andric     // The count doesn't include the fallthrough from the parent scope. Add it.
39333956c43SDimitry Andric     uint64_t BodyCount = setCount(LoopCount + CurrentCount);
39433956c43SDimitry Andric     CountMap[S->getBody()] = BodyCount;
39559d1ed5bSDimitry Andric     Visit(S->getBody());
39633956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
39759d1ed5bSDimitry Andric 
39859d1ed5bSDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
39959d1ed5bSDimitry Andric     // The count at the start of the condition is equal to the count at the
40033956c43SDimitry Andric     // end of the body, plus any continues.
40133956c43SDimitry Andric     uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
40233956c43SDimitry Andric     CountMap[S->getCond()] = CondCount;
40359d1ed5bSDimitry Andric     Visit(S->getCond());
40433956c43SDimitry Andric     setCount(BC.BreakCount + CondCount - LoopCount);
40559d1ed5bSDimitry Andric     RecordNextStmtCount = true;
40659d1ed5bSDimitry Andric   }
40759d1ed5bSDimitry Andric 
40859d1ed5bSDimitry Andric   void VisitForStmt(const ForStmt *S) {
40959d1ed5bSDimitry Andric     RecordStmtCount(S);
41059d1ed5bSDimitry Andric     if (S->getInit())
41159d1ed5bSDimitry Andric       Visit(S->getInit());
41233956c43SDimitry Andric 
41333956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
41433956c43SDimitry Andric 
41559d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
41659d1ed5bSDimitry Andric     // Visit the body region first. (This is basically the same as a while
41759d1ed5bSDimitry Andric     // loop; see further comments in VisitWhileStmt.)
41833956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
41933956c43SDimitry Andric     CountMap[S->getBody()] = BodyCount;
42059d1ed5bSDimitry Andric     Visit(S->getBody());
42133956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
42233956c43SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
42359d1ed5bSDimitry Andric 
42459d1ed5bSDimitry Andric     // The increment is essentially part of the body but it needs to include
42559d1ed5bSDimitry Andric     // the count for all the continue statements.
42659d1ed5bSDimitry Andric     if (S->getInc()) {
42733956c43SDimitry Andric       uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
42833956c43SDimitry Andric       CountMap[S->getInc()] = IncCount;
42959d1ed5bSDimitry Andric       Visit(S->getInc());
43059d1ed5bSDimitry Andric     }
43159d1ed5bSDimitry Andric 
43259d1ed5bSDimitry Andric     // ...then go back and propagate counts through the condition.
43333956c43SDimitry Andric     uint64_t CondCount =
43433956c43SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
43559d1ed5bSDimitry Andric     if (S->getCond()) {
43633956c43SDimitry Andric       CountMap[S->getCond()] = CondCount;
43759d1ed5bSDimitry Andric       Visit(S->getCond());
43859d1ed5bSDimitry Andric     }
43933956c43SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
44059d1ed5bSDimitry Andric     RecordNextStmtCount = true;
44159d1ed5bSDimitry Andric   }
44259d1ed5bSDimitry Andric 
44359d1ed5bSDimitry Andric   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
44459d1ed5bSDimitry Andric     RecordStmtCount(S);
44533956c43SDimitry Andric     Visit(S->getLoopVarStmt());
44659d1ed5bSDimitry Andric     Visit(S->getRangeStmt());
44759d1ed5bSDimitry Andric     Visit(S->getBeginEndStmt());
44833956c43SDimitry Andric 
44933956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
45059d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
45159d1ed5bSDimitry Andric     // Visit the body region first. (This is basically the same as a while
45259d1ed5bSDimitry Andric     // loop; see further comments in VisitWhileStmt.)
45333956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
45433956c43SDimitry Andric     CountMap[S->getBody()] = BodyCount;
45559d1ed5bSDimitry Andric     Visit(S->getBody());
45633956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
45733956c43SDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
45859d1ed5bSDimitry Andric 
45959d1ed5bSDimitry Andric     // The increment is essentially part of the body but it needs to include
46059d1ed5bSDimitry Andric     // the count for all the continue statements.
46133956c43SDimitry Andric     uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
46233956c43SDimitry Andric     CountMap[S->getInc()] = IncCount;
46359d1ed5bSDimitry Andric     Visit(S->getInc());
46459d1ed5bSDimitry Andric 
46559d1ed5bSDimitry Andric     // ...then go back and propagate counts through the condition.
46633956c43SDimitry Andric     uint64_t CondCount =
46733956c43SDimitry Andric         setCount(ParentCount + BackedgeCount + BC.ContinueCount);
46833956c43SDimitry Andric     CountMap[S->getCond()] = CondCount;
46959d1ed5bSDimitry Andric     Visit(S->getCond());
47033956c43SDimitry Andric     setCount(BC.BreakCount + CondCount - BodyCount);
47159d1ed5bSDimitry Andric     RecordNextStmtCount = true;
47259d1ed5bSDimitry Andric   }
47359d1ed5bSDimitry Andric 
47459d1ed5bSDimitry Andric   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
47559d1ed5bSDimitry Andric     RecordStmtCount(S);
47659d1ed5bSDimitry Andric     Visit(S->getElement());
47733956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
47859d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
47933956c43SDimitry Andric     // Counter tracks the body of the loop.
48033956c43SDimitry Andric     uint64_t BodyCount = setCount(PGO.getRegionCount(S));
48133956c43SDimitry Andric     CountMap[S->getBody()] = BodyCount;
48259d1ed5bSDimitry Andric     Visit(S->getBody());
48333956c43SDimitry Andric     uint64_t BackedgeCount = CurrentCount;
48459d1ed5bSDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
48533956c43SDimitry Andric 
48633956c43SDimitry Andric     setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
48733956c43SDimitry Andric              BodyCount);
48859d1ed5bSDimitry Andric     RecordNextStmtCount = true;
48959d1ed5bSDimitry Andric   }
49059d1ed5bSDimitry Andric 
49159d1ed5bSDimitry Andric   void VisitSwitchStmt(const SwitchStmt *S) {
49259d1ed5bSDimitry Andric     RecordStmtCount(S);
49359d1ed5bSDimitry Andric     Visit(S->getCond());
49433956c43SDimitry Andric     CurrentCount = 0;
49559d1ed5bSDimitry Andric     BreakContinueStack.push_back(BreakContinue());
49659d1ed5bSDimitry Andric     Visit(S->getBody());
49759d1ed5bSDimitry Andric     // If the switch is inside a loop, add the continue counts.
49859d1ed5bSDimitry Andric     BreakContinue BC = BreakContinueStack.pop_back_val();
49959d1ed5bSDimitry Andric     if (!BreakContinueStack.empty())
50059d1ed5bSDimitry Andric       BreakContinueStack.back().ContinueCount += BC.ContinueCount;
50159d1ed5bSDimitry Andric     // Counter tracks the exit block of the switch.
50233956c43SDimitry Andric     setCount(PGO.getRegionCount(S));
50359d1ed5bSDimitry Andric     RecordNextStmtCount = true;
50459d1ed5bSDimitry Andric   }
50559d1ed5bSDimitry Andric 
50633956c43SDimitry Andric   void VisitSwitchCase(const SwitchCase *S) {
50759d1ed5bSDimitry Andric     RecordNextStmtCount = false;
50859d1ed5bSDimitry Andric     // Counter for this particular case. This counts only jumps from the
50959d1ed5bSDimitry Andric     // switch header and does not include fallthrough from the case before
51059d1ed5bSDimitry Andric     // this one.
51133956c43SDimitry Andric     uint64_t CaseCount = PGO.getRegionCount(S);
51233956c43SDimitry Andric     setCount(CurrentCount + CaseCount);
51333956c43SDimitry Andric     // We need the count without fallthrough in the mapping, so it's more useful
51433956c43SDimitry Andric     // for branch probabilities.
51533956c43SDimitry Andric     CountMap[S] = CaseCount;
51659d1ed5bSDimitry Andric     RecordNextStmtCount = true;
51759d1ed5bSDimitry Andric     Visit(S->getSubStmt());
51859d1ed5bSDimitry Andric   }
51959d1ed5bSDimitry Andric 
52059d1ed5bSDimitry Andric   void VisitIfStmt(const IfStmt *S) {
52159d1ed5bSDimitry Andric     RecordStmtCount(S);
52233956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
52359d1ed5bSDimitry Andric     Visit(S->getCond());
52459d1ed5bSDimitry Andric 
52533956c43SDimitry Andric     // Counter tracks the "then" part of an if statement. The count for
52633956c43SDimitry Andric     // the "else" part, if it exists, will be calculated from this counter.
52733956c43SDimitry Andric     uint64_t ThenCount = setCount(PGO.getRegionCount(S));
52833956c43SDimitry Andric     CountMap[S->getThen()] = ThenCount;
52959d1ed5bSDimitry Andric     Visit(S->getThen());
53033956c43SDimitry Andric     uint64_t OutCount = CurrentCount;
53159d1ed5bSDimitry Andric 
53233956c43SDimitry Andric     uint64_t ElseCount = ParentCount - ThenCount;
53359d1ed5bSDimitry Andric     if (S->getElse()) {
53433956c43SDimitry Andric       setCount(ElseCount);
53533956c43SDimitry Andric       CountMap[S->getElse()] = ElseCount;
53659d1ed5bSDimitry Andric       Visit(S->getElse());
53733956c43SDimitry Andric       OutCount += CurrentCount;
53833956c43SDimitry Andric     } else
53933956c43SDimitry Andric       OutCount += ElseCount;
54033956c43SDimitry Andric     setCount(OutCount);
54159d1ed5bSDimitry Andric     RecordNextStmtCount = true;
54259d1ed5bSDimitry Andric   }
54359d1ed5bSDimitry Andric 
54459d1ed5bSDimitry Andric   void VisitCXXTryStmt(const CXXTryStmt *S) {
54559d1ed5bSDimitry Andric     RecordStmtCount(S);
54659d1ed5bSDimitry Andric     Visit(S->getTryBlock());
54759d1ed5bSDimitry Andric     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
54859d1ed5bSDimitry Andric       Visit(S->getHandler(I));
54959d1ed5bSDimitry Andric     // Counter tracks the continuation block of the try statement.
55033956c43SDimitry Andric     setCount(PGO.getRegionCount(S));
55159d1ed5bSDimitry Andric     RecordNextStmtCount = true;
55259d1ed5bSDimitry Andric   }
55359d1ed5bSDimitry Andric 
55459d1ed5bSDimitry Andric   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
55559d1ed5bSDimitry Andric     RecordNextStmtCount = false;
55659d1ed5bSDimitry Andric     // Counter tracks the catch statement's handler block.
55733956c43SDimitry Andric     uint64_t CatchCount = setCount(PGO.getRegionCount(S));
55833956c43SDimitry Andric     CountMap[S] = CatchCount;
55959d1ed5bSDimitry Andric     Visit(S->getHandlerBlock());
56059d1ed5bSDimitry Andric   }
56159d1ed5bSDimitry Andric 
56233956c43SDimitry Andric   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
56359d1ed5bSDimitry Andric     RecordStmtCount(E);
56433956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
56559d1ed5bSDimitry Andric     Visit(E->getCond());
56659d1ed5bSDimitry Andric 
56733956c43SDimitry Andric     // Counter tracks the "true" part of a conditional operator. The
56833956c43SDimitry Andric     // count in the "false" part will be calculated from this counter.
56933956c43SDimitry Andric     uint64_t TrueCount = setCount(PGO.getRegionCount(E));
57033956c43SDimitry Andric     CountMap[E->getTrueExpr()] = TrueCount;
57159d1ed5bSDimitry Andric     Visit(E->getTrueExpr());
57233956c43SDimitry Andric     uint64_t OutCount = CurrentCount;
57359d1ed5bSDimitry Andric 
57433956c43SDimitry Andric     uint64_t FalseCount = setCount(ParentCount - TrueCount);
57533956c43SDimitry Andric     CountMap[E->getFalseExpr()] = FalseCount;
57659d1ed5bSDimitry Andric     Visit(E->getFalseExpr());
57733956c43SDimitry Andric     OutCount += CurrentCount;
57859d1ed5bSDimitry Andric 
57933956c43SDimitry Andric     setCount(OutCount);
58059d1ed5bSDimitry Andric     RecordNextStmtCount = true;
58159d1ed5bSDimitry Andric   }
58259d1ed5bSDimitry Andric 
58359d1ed5bSDimitry Andric   void VisitBinLAnd(const BinaryOperator *E) {
58459d1ed5bSDimitry Andric     RecordStmtCount(E);
58533956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
58659d1ed5bSDimitry Andric     Visit(E->getLHS());
58733956c43SDimitry Andric     // Counter tracks the right hand side of a logical and operator.
58833956c43SDimitry Andric     uint64_t RHSCount = setCount(PGO.getRegionCount(E));
58933956c43SDimitry Andric     CountMap[E->getRHS()] = RHSCount;
59059d1ed5bSDimitry Andric     Visit(E->getRHS());
59133956c43SDimitry Andric     setCount(ParentCount + RHSCount - CurrentCount);
59259d1ed5bSDimitry Andric     RecordNextStmtCount = true;
59359d1ed5bSDimitry Andric   }
59459d1ed5bSDimitry Andric 
59559d1ed5bSDimitry Andric   void VisitBinLOr(const BinaryOperator *E) {
59659d1ed5bSDimitry Andric     RecordStmtCount(E);
59733956c43SDimitry Andric     uint64_t ParentCount = CurrentCount;
59859d1ed5bSDimitry Andric     Visit(E->getLHS());
59933956c43SDimitry Andric     // Counter tracks the right hand side of a logical or operator.
60033956c43SDimitry Andric     uint64_t RHSCount = setCount(PGO.getRegionCount(E));
60133956c43SDimitry Andric     CountMap[E->getRHS()] = RHSCount;
60259d1ed5bSDimitry Andric     Visit(E->getRHS());
60333956c43SDimitry Andric     setCount(ParentCount + RHSCount - CurrentCount);
60459d1ed5bSDimitry Andric     RecordNextStmtCount = true;
60559d1ed5bSDimitry Andric   }
60659d1ed5bSDimitry Andric };
60759d1ed5bSDimitry Andric }
60859d1ed5bSDimitry Andric 
60959d1ed5bSDimitry Andric void PGOHash::combine(HashType Type) {
61059d1ed5bSDimitry Andric   // Check that we never combine 0 and only have six bits.
61159d1ed5bSDimitry Andric   assert(Type && "Hash is invalid: unexpected type 0");
61259d1ed5bSDimitry Andric   assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
61359d1ed5bSDimitry Andric 
61459d1ed5bSDimitry Andric   // Pass through MD5 if enough work has built up.
61559d1ed5bSDimitry Andric   if (Count && Count % NumTypesPerWord == 0) {
61659d1ed5bSDimitry Andric     using namespace llvm::support;
61759d1ed5bSDimitry Andric     uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
61859d1ed5bSDimitry Andric     MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
61959d1ed5bSDimitry Andric     Working = 0;
62059d1ed5bSDimitry Andric   }
62159d1ed5bSDimitry Andric 
62259d1ed5bSDimitry Andric   // Accumulate the current type.
62359d1ed5bSDimitry Andric   ++Count;
62459d1ed5bSDimitry Andric   Working = Working << NumBitsPerType | Type;
62559d1ed5bSDimitry Andric }
62659d1ed5bSDimitry Andric 
62759d1ed5bSDimitry Andric uint64_t PGOHash::finalize() {
62859d1ed5bSDimitry Andric   // Use Working as the hash directly if we never used MD5.
62959d1ed5bSDimitry Andric   if (Count <= NumTypesPerWord)
63059d1ed5bSDimitry Andric     // No need to byte swap here, since none of the math was endian-dependent.
63159d1ed5bSDimitry Andric     // This number will be byte-swapped as required on endianness transitions,
63259d1ed5bSDimitry Andric     // so we will see the same value on the other side.
63359d1ed5bSDimitry Andric     return Working;
63459d1ed5bSDimitry Andric 
63559d1ed5bSDimitry Andric   // Check for remaining work in Working.
63659d1ed5bSDimitry Andric   if (Working)
63759d1ed5bSDimitry Andric     MD5.update(Working);
63859d1ed5bSDimitry Andric 
63959d1ed5bSDimitry Andric   // Finalize the MD5 and return the hash.
64059d1ed5bSDimitry Andric   llvm::MD5::MD5Result Result;
64159d1ed5bSDimitry Andric   MD5.final(Result);
64259d1ed5bSDimitry Andric   using namespace llvm::support;
64359d1ed5bSDimitry Andric   return endian::read<uint64_t, little, unaligned>(Result);
64459d1ed5bSDimitry Andric }
64559d1ed5bSDimitry Andric 
64639d628a0SDimitry Andric void CodeGenPGO::checkGlobalDecl(GlobalDecl GD) {
64739d628a0SDimitry Andric   // Make sure we only emit coverage mapping for one constructor/destructor.
64839d628a0SDimitry Andric   // Clang emits several functions for the constructor and the destructor of
64939d628a0SDimitry Andric   // a class. Every function is instrumented, but we only want to provide
65039d628a0SDimitry Andric   // coverage for one of them. Because of that we only emit the coverage mapping
65139d628a0SDimitry Andric   // for the base constructor/destructor.
65239d628a0SDimitry Andric   if ((isa<CXXConstructorDecl>(GD.getDecl()) &&
65339d628a0SDimitry Andric        GD.getCtorType() != Ctor_Base) ||
65439d628a0SDimitry Andric       (isa<CXXDestructorDecl>(GD.getDecl()) &&
65539d628a0SDimitry Andric        GD.getDtorType() != Dtor_Base)) {
65639d628a0SDimitry Andric     SkipCoverageMapping = true;
65739d628a0SDimitry Andric   }
65859d1ed5bSDimitry Andric }
65959d1ed5bSDimitry Andric 
66059d1ed5bSDimitry Andric void CodeGenPGO::assignRegionCounters(const Decl *D, llvm::Function *Fn) {
66159d1ed5bSDimitry Andric   bool InstrumentRegions = CGM.getCodeGenOpts().ProfileInstrGenerate;
66259d1ed5bSDimitry Andric   llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
66359d1ed5bSDimitry Andric   if (!InstrumentRegions && !PGOReader)
66459d1ed5bSDimitry Andric     return;
66559d1ed5bSDimitry Andric   if (D->isImplicit())
66659d1ed5bSDimitry Andric     return;
66739d628a0SDimitry Andric   CGM.ClearUnusedCoverageMapping(D);
66859d1ed5bSDimitry Andric   setFuncName(Fn);
66959d1ed5bSDimitry Andric 
67059d1ed5bSDimitry Andric   mapRegionCounters(D);
67139d628a0SDimitry Andric   if (CGM.getCodeGenOpts().CoverageMapping)
67239d628a0SDimitry Andric     emitCounterRegionMapping(D);
67359d1ed5bSDimitry Andric   if (PGOReader) {
67459d1ed5bSDimitry Andric     SourceManager &SM = CGM.getContext().getSourceManager();
67559d1ed5bSDimitry Andric     loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
67659d1ed5bSDimitry Andric     computeRegionCounts(D);
67759d1ed5bSDimitry Andric     applyFunctionAttributes(PGOReader, Fn);
67859d1ed5bSDimitry Andric   }
67959d1ed5bSDimitry Andric }
68059d1ed5bSDimitry Andric 
68159d1ed5bSDimitry Andric void CodeGenPGO::mapRegionCounters(const Decl *D) {
68259d1ed5bSDimitry Andric   RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
68359d1ed5bSDimitry Andric   MapRegionCounters Walker(*RegionCounterMap);
68459d1ed5bSDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
68559d1ed5bSDimitry Andric     Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
68659d1ed5bSDimitry Andric   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
68759d1ed5bSDimitry Andric     Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
68859d1ed5bSDimitry Andric   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
68959d1ed5bSDimitry Andric     Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
69059d1ed5bSDimitry Andric   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
69159d1ed5bSDimitry Andric     Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
69259d1ed5bSDimitry Andric   assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
69359d1ed5bSDimitry Andric   NumRegionCounters = Walker.NextCounter;
69459d1ed5bSDimitry Andric   FunctionHash = Walker.Hash.finalize();
69559d1ed5bSDimitry Andric }
69659d1ed5bSDimitry Andric 
69739d628a0SDimitry Andric void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
69839d628a0SDimitry Andric   if (SkipCoverageMapping)
69939d628a0SDimitry Andric     return;
70039d628a0SDimitry Andric   // Don't map the functions inside the system headers
70139d628a0SDimitry Andric   auto Loc = D->getBody()->getLocStart();
70239d628a0SDimitry Andric   if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
70339d628a0SDimitry Andric     return;
70439d628a0SDimitry Andric 
70539d628a0SDimitry Andric   std::string CoverageMapping;
70639d628a0SDimitry Andric   llvm::raw_string_ostream OS(CoverageMapping);
70739d628a0SDimitry Andric   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
70839d628a0SDimitry Andric                                 CGM.getContext().getSourceManager(),
70939d628a0SDimitry Andric                                 CGM.getLangOpts(), RegionCounterMap.get());
71039d628a0SDimitry Andric   MappingGen.emitCounterMapping(D, OS);
71139d628a0SDimitry Andric   OS.flush();
71239d628a0SDimitry Andric 
71339d628a0SDimitry Andric   if (CoverageMapping.empty())
71439d628a0SDimitry Andric     return;
71539d628a0SDimitry Andric 
71639d628a0SDimitry Andric   CGM.getCoverageMapping()->addFunctionMappingRecord(
71739d628a0SDimitry Andric       FuncNameVar, FuncName, FunctionHash, CoverageMapping);
71839d628a0SDimitry Andric }
71939d628a0SDimitry Andric 
72039d628a0SDimitry Andric void
72133956c43SDimitry Andric CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
72239d628a0SDimitry Andric                                     llvm::GlobalValue::LinkageTypes Linkage) {
72339d628a0SDimitry Andric   if (SkipCoverageMapping)
72439d628a0SDimitry Andric     return;
72539d628a0SDimitry Andric   // Don't map the functions inside the system headers
72639d628a0SDimitry Andric   auto Loc = D->getBody()->getLocStart();
72739d628a0SDimitry Andric   if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
72839d628a0SDimitry Andric     return;
72939d628a0SDimitry Andric 
73039d628a0SDimitry Andric   std::string CoverageMapping;
73139d628a0SDimitry Andric   llvm::raw_string_ostream OS(CoverageMapping);
73239d628a0SDimitry Andric   CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
73339d628a0SDimitry Andric                                 CGM.getContext().getSourceManager(),
73439d628a0SDimitry Andric                                 CGM.getLangOpts());
73539d628a0SDimitry Andric   MappingGen.emitEmptyMapping(D, OS);
73639d628a0SDimitry Andric   OS.flush();
73739d628a0SDimitry Andric 
73839d628a0SDimitry Andric   if (CoverageMapping.empty())
73939d628a0SDimitry Andric     return;
74039d628a0SDimitry Andric 
74133956c43SDimitry Andric   setFuncName(Name, Linkage);
74239d628a0SDimitry Andric   CGM.getCoverageMapping()->addFunctionMappingRecord(
74339d628a0SDimitry Andric       FuncNameVar, FuncName, FunctionHash, CoverageMapping);
74439d628a0SDimitry Andric }
74539d628a0SDimitry Andric 
74659d1ed5bSDimitry Andric void CodeGenPGO::computeRegionCounts(const Decl *D) {
74759d1ed5bSDimitry Andric   StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
74859d1ed5bSDimitry Andric   ComputeRegionCounts Walker(*StmtCountMap, *this);
74959d1ed5bSDimitry Andric   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
75059d1ed5bSDimitry Andric     Walker.VisitFunctionDecl(FD);
75159d1ed5bSDimitry Andric   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
75259d1ed5bSDimitry Andric     Walker.VisitObjCMethodDecl(MD);
75359d1ed5bSDimitry Andric   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
75459d1ed5bSDimitry Andric     Walker.VisitBlockDecl(BD);
75559d1ed5bSDimitry Andric   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
75659d1ed5bSDimitry Andric     Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
75759d1ed5bSDimitry Andric }
75859d1ed5bSDimitry Andric 
75959d1ed5bSDimitry Andric void
76059d1ed5bSDimitry Andric CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
76159d1ed5bSDimitry Andric                                     llvm::Function *Fn) {
76259d1ed5bSDimitry Andric   if (!haveRegionCounts())
76359d1ed5bSDimitry Andric     return;
76459d1ed5bSDimitry Andric 
76559d1ed5bSDimitry Andric   uint64_t MaxFunctionCount = PGOReader->getMaximumFunctionCount();
76659d1ed5bSDimitry Andric   uint64_t FunctionCount = getRegionCount(0);
76759d1ed5bSDimitry Andric   if (FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount))
76859d1ed5bSDimitry Andric     // Turn on InlineHint attribute for hot functions.
76959d1ed5bSDimitry Andric     // FIXME: 30% is from preliminary tuning on SPEC, it may not be optimal.
77059d1ed5bSDimitry Andric     Fn->addFnAttr(llvm::Attribute::InlineHint);
77159d1ed5bSDimitry Andric   else if (FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount))
77259d1ed5bSDimitry Andric     // Turn on Cold attribute for cold functions.
77359d1ed5bSDimitry Andric     // FIXME: 1% is from preliminary tuning on SPEC, it may not be optimal.
77459d1ed5bSDimitry Andric     Fn->addFnAttr(llvm::Attribute::Cold);
77597bc6c73SDimitry Andric 
77697bc6c73SDimitry Andric   Fn->setEntryCount(FunctionCount);
77759d1ed5bSDimitry Andric }
77859d1ed5bSDimitry Andric 
77933956c43SDimitry Andric void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S) {
78039d628a0SDimitry Andric   if (!CGM.getCodeGenOpts().ProfileInstrGenerate || !RegionCounterMap)
78159d1ed5bSDimitry Andric     return;
78239d628a0SDimitry Andric   if (!Builder.GetInsertPoint())
78339d628a0SDimitry Andric     return;
78433956c43SDimitry Andric 
78533956c43SDimitry Andric   unsigned Counter = (*RegionCounterMap)[S];
78639d628a0SDimitry Andric   auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
78733956c43SDimitry Andric   Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
78833956c43SDimitry Andric                      {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
78939d628a0SDimitry Andric                       Builder.getInt64(FunctionHash),
79039d628a0SDimitry Andric                       Builder.getInt32(NumRegionCounters),
79133956c43SDimitry Andric                       Builder.getInt32(Counter)});
79259d1ed5bSDimitry Andric }
79359d1ed5bSDimitry Andric 
79459d1ed5bSDimitry Andric void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
79559d1ed5bSDimitry Andric                                   bool IsInMainFile) {
79659d1ed5bSDimitry Andric   CGM.getPGOStats().addVisited(IsInMainFile);
79739d628a0SDimitry Andric   RegionCounts.clear();
79839d628a0SDimitry Andric   if (std::error_code EC =
79939d628a0SDimitry Andric           PGOReader->getFunctionCounts(FuncName, FunctionHash, RegionCounts)) {
80039d628a0SDimitry Andric     if (EC == llvm::instrprof_error::unknown_function)
80159d1ed5bSDimitry Andric       CGM.getPGOStats().addMissing(IsInMainFile);
80239d628a0SDimitry Andric     else if (EC == llvm::instrprof_error::hash_mismatch)
80359d1ed5bSDimitry Andric       CGM.getPGOStats().addMismatched(IsInMainFile);
80439d628a0SDimitry Andric     else if (EC == llvm::instrprof_error::malformed)
80539d628a0SDimitry Andric       // TODO: Consider a more specific warning for this case.
80639d628a0SDimitry Andric       CGM.getPGOStats().addMismatched(IsInMainFile);
80739d628a0SDimitry Andric     RegionCounts.clear();
80859d1ed5bSDimitry Andric   }
80959d1ed5bSDimitry Andric }
81059d1ed5bSDimitry Andric 
81159d1ed5bSDimitry Andric /// \brief Calculate what to divide by to scale weights.
81259d1ed5bSDimitry Andric ///
81359d1ed5bSDimitry Andric /// Given the maximum weight, calculate a divisor that will scale all the
81459d1ed5bSDimitry Andric /// weights to strictly less than UINT32_MAX.
81559d1ed5bSDimitry Andric static uint64_t calculateWeightScale(uint64_t MaxWeight) {
81659d1ed5bSDimitry Andric   return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
81759d1ed5bSDimitry Andric }
81859d1ed5bSDimitry Andric 
81959d1ed5bSDimitry Andric /// \brief Scale an individual branch weight (and add 1).
82059d1ed5bSDimitry Andric ///
82159d1ed5bSDimitry Andric /// Scale a 64-bit weight down to 32-bits using \c Scale.
82259d1ed5bSDimitry Andric ///
82359d1ed5bSDimitry Andric /// According to Laplace's Rule of Succession, it is better to compute the
82459d1ed5bSDimitry Andric /// weight based on the count plus 1, so universally add 1 to the value.
82559d1ed5bSDimitry Andric ///
82659d1ed5bSDimitry Andric /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
82759d1ed5bSDimitry Andric /// greater than \c Weight.
82859d1ed5bSDimitry Andric static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
82959d1ed5bSDimitry Andric   assert(Scale && "scale by 0?");
83059d1ed5bSDimitry Andric   uint64_t Scaled = Weight / Scale + 1;
83159d1ed5bSDimitry Andric   assert(Scaled <= UINT32_MAX && "overflow 32-bits");
83259d1ed5bSDimitry Andric   return Scaled;
83359d1ed5bSDimitry Andric }
83459d1ed5bSDimitry Andric 
83533956c43SDimitry Andric llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
83659d1ed5bSDimitry Andric                                                     uint64_t FalseCount) {
83759d1ed5bSDimitry Andric   // Check for empty weights.
83859d1ed5bSDimitry Andric   if (!TrueCount && !FalseCount)
83959d1ed5bSDimitry Andric     return nullptr;
84059d1ed5bSDimitry Andric 
84159d1ed5bSDimitry Andric   // Calculate how to scale down to 32-bits.
84259d1ed5bSDimitry Andric   uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
84359d1ed5bSDimitry Andric 
84459d1ed5bSDimitry Andric   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
84559d1ed5bSDimitry Andric   return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
84659d1ed5bSDimitry Andric                                       scaleBranchWeight(FalseCount, Scale));
84759d1ed5bSDimitry Andric }
84859d1ed5bSDimitry Andric 
84933956c43SDimitry Andric llvm::MDNode *
85033956c43SDimitry Andric CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
85159d1ed5bSDimitry Andric   // We need at least two elements to create meaningful weights.
85259d1ed5bSDimitry Andric   if (Weights.size() < 2)
85359d1ed5bSDimitry Andric     return nullptr;
85459d1ed5bSDimitry Andric 
85559d1ed5bSDimitry Andric   // Check for empty weights.
85659d1ed5bSDimitry Andric   uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
85759d1ed5bSDimitry Andric   if (MaxWeight == 0)
85859d1ed5bSDimitry Andric     return nullptr;
85959d1ed5bSDimitry Andric 
86059d1ed5bSDimitry Andric   // Calculate how to scale down to 32-bits.
86159d1ed5bSDimitry Andric   uint64_t Scale = calculateWeightScale(MaxWeight);
86259d1ed5bSDimitry Andric 
86359d1ed5bSDimitry Andric   SmallVector<uint32_t, 16> ScaledWeights;
86459d1ed5bSDimitry Andric   ScaledWeights.reserve(Weights.size());
86559d1ed5bSDimitry Andric   for (uint64_t W : Weights)
86659d1ed5bSDimitry Andric     ScaledWeights.push_back(scaleBranchWeight(W, Scale));
86759d1ed5bSDimitry Andric 
86859d1ed5bSDimitry Andric   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
86959d1ed5bSDimitry Andric   return MDHelper.createBranchWeights(ScaledWeights);
87059d1ed5bSDimitry Andric }
87159d1ed5bSDimitry Andric 
87233956c43SDimitry Andric llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
87333956c43SDimitry Andric                                                            uint64_t LoopCount) {
87433956c43SDimitry Andric   if (!PGO.haveRegionCounts())
87559d1ed5bSDimitry Andric     return nullptr;
87633956c43SDimitry Andric   Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
87733956c43SDimitry Andric   assert(CondCount.hasValue() && "missing expected loop condition count");
87833956c43SDimitry Andric   if (*CondCount == 0)
87959d1ed5bSDimitry Andric     return nullptr;
88033956c43SDimitry Andric   return createProfileWeights(LoopCount,
88133956c43SDimitry Andric                               std::max(*CondCount, LoopCount) - LoopCount);
88259d1ed5bSDimitry Andric }
883