Index: llvm/include/llvm/Transforms/IPO/SampleProfileImpl.h =================================================================== --- /dev/null +++ llvm/include/llvm/Transforms/IPO/SampleProfileImpl.h @@ -0,0 +1,1286 @@ +//===- SampleProfileImpl.h - SamplePGO Profile Loader Impl -----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +/// \file +/// This file provides the templated implementaion for the sampled PGO loader. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_TRANSFORMS_IPO_SAMPLEPROFILEIMPL_H +#define LLVM_TRANSFORMS_IPO_SAMPLEPROFILEIMPL_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallSet.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringMap.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/Twine.h" +#include "llvm/Analysis/CallGraph.h" +#include "llvm/Analysis/LoopInfo.h" +#include "llvm/Analysis/OptimizationRemarkEmitter.h" +#include "llvm/Analysis/PostDominators.h" +#include "llvm/Analysis/ProfileSummaryInfo.h" +#include "llvm/Analysis/ReplayInlineAdvisor.h" +#include "llvm/Analysis/TargetLibraryInfo.h" +#include "llvm/Analysis/TargetTransformInfo.h" +#include "llvm/CodeGen/MachineBasicBlock.h" +#include "llvm/CodeGen/MachineDominators.h" +#include "llvm/CodeGen/MachineFunction.h" +#include "llvm/CodeGen/MachineInstr.h" +#include "llvm/CodeGen/MachineLoopInfo.h" +#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" +#include "llvm/CodeGen/MachinePostDominators.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/CFG.h" +#include "llvm/IR/DebugLoc.h" +#include "llvm/IR/DiagnosticInfo.h" +#include "llvm/IR/Dominators.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/GlobalValue.h" +#include "llvm/IR/InstrTypes.h" +#include "llvm/IR/Instruction.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/MDBuilder.h" +#include "llvm/IR/Module.h" +#include "llvm/ProfileData/InstrProf.h" +#include "llvm/ProfileData/SampleProf.h" +#include "llvm/ProfileData/SampleProfReader.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/ErrorOr.h" +#include "llvm/Support/GenericDomTree.h" +#include "llvm/Transforms/IPO.h" +#include "llvm/Transforms/IPO/SampleContextTracker.h" +#include "llvm/Transforms/IPO/SampleProfileProbe.h" + +using namespace llvm; +using namespace sampleprof; +using ProfileCount = Function::ProfileCount; + +#define DEBUG_TYPE "sample-profile-impl" + +namespace afdo_detail { + +template struct TypeMap {}; +template <> struct TypeMap { + using InstructionT = Instruction; + using BasicBlockT = BasicBlock; + using FunctionT = Function; + using BlockFrequencyInfoT = BlockFrequencyInfo; + using LoopT = Loop; + using LoopInfoT = LoopInfo; + using OptRemarkEmitterT = OptimizationRemarkEmitter; + using OptRemarkAnalysisT = OptimizationRemarkAnalysis; + using DominatorTreeT = DominatorTree; + using PostDominatorTreeT = PostDominatorTree; +}; +template <> struct TypeMap { + using InstructionT = MachineInstr; + using BasicBlockT = MachineBasicBlock; + using FunctionT = MachineFunction; + using BlockFrequencyInfoT = MachineBlockFrequencyInfo; + using LoopT = MachineLoop; + using LoopInfoT = MachineLoopInfo; + using OptRemarkEmitterT = MachineOptimizationRemarkEmitter; + using OptRemarkAnalysisT = MachineOptimizationRemarkAnalysis; + using DominatorTreeT = MachineDominatorTree; + using PostDominatorTreeT = MachinePostDominatorTree; +}; +} // end namespace afdo_detail + +class SampleCoverageTracker { +public: + SampleCoverageTracker() {} + + bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset, + uint32_t Discriminator, uint64_t Samples); + unsigned computeCoverage(unsigned Used, unsigned Total) const; + unsigned countUsedRecords(const FunctionSamples *FS, + ProfileSummaryInfo *PSI = nullptr) const; + unsigned countBodyRecords(const FunctionSamples *FS, + ProfileSummaryInfo *PSI = nullptr) const; + uint64_t getTotalUsedSamples() const { return TotalUsedSamples; } + uint64_t countBodySamples(const FunctionSamples *FS, + ProfileSummaryInfo *PSI = nullptr) const; + + void clear() { + SampleCoverage.clear(); + TotalUsedSamples = 0; + } + void setProfAccForSymsInList(bool V) { ProfAccForSymsInList = V; } + +private: + using BodySampleCoverageMap = std::map; + using FunctionSamplesCoverageMap = + DenseMap; + + /// Coverage map for sampling records. + /// + /// This map keeps a record of sampling records that have been matched to + /// an IR instruction. This is used to detect some form of staleness in + /// profiles (see flag -sample-profile-check-coverage). + /// + /// Each entry in the map corresponds to a FunctionSamples instance. This is + /// another map that counts how many times the sample record at the + /// given location has been used. + FunctionSamplesCoverageMap SampleCoverage; + + /// Number of samples used from the profile. + /// + /// When a sampling record is used for the first time, the samples from + /// that record are added to this accumulator. Coverage is later computed + /// based on the total number of samples available in this function and + /// its callsites. + /// + /// Note that this accumulator tracks samples used from a single function + /// and all the inlined callsites. Strictly, we should have a map of counters + /// keyed by FunctionSamples pointers, but these stats are cleared after + /// every function, so we just need to keep a single counter. + uint64_t TotalUsedSamples = 0; + + bool ProfAccForSymsInList = false; +}; + +class GUIDToFuncNameMapper { +public: + GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader, + DenseMap &GUIDToFuncNameMap) + : CurrentReader(Reader), CurrentModule(M), + CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) { + if (!CurrentReader.useMD5()) + return; + + for (const auto &F : CurrentModule) { + StringRef OrigName = F.getName(); + CurrentGUIDToFuncNameMap.insert({Function::getGUID(OrigName), OrigName}); + + // Local to global var promotion used by optimization like thinlto + // will rename the var and add suffix like ".llvm.xxx" to the + // original local name. In sample profile, the suffixes of function + // names are all stripped. Since it is possible that the mapper is + // built in post-thin-link phase and var promotion has been done, + // we need to add the substring of function name without the suffix + // into the GUIDToFuncNameMap. + StringRef CanonName = FunctionSamples::getCanonicalFnName(F); + if (CanonName != OrigName) + CurrentGUIDToFuncNameMap.insert( + {Function::getGUID(CanonName), CanonName}); + } + + // Update GUIDToFuncNameMap for each function including inlinees. + SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap); + } + + ~GUIDToFuncNameMapper() { + if (!CurrentReader.useMD5()) + return; + + CurrentGUIDToFuncNameMap.clear(); + + // Reset GUIDToFuncNameMap for of each function as they're no + // longer valid at this point. + SetGUIDToFuncNameMapForAll(nullptr); + } + +private: + void SetGUIDToFuncNameMapForAll(DenseMap *Map) { + std::queue FSToUpdate; + for (auto &IFS : CurrentReader.getProfiles()) { + FSToUpdate.push(&IFS.second); + } + + while (!FSToUpdate.empty()) { + FunctionSamples *FS = FSToUpdate.front(); + FSToUpdate.pop(); + FS->GUIDToFuncNameMap = Map; + for (const auto &ICS : FS->getCallsiteSamples()) { + const FunctionSamplesMap &FSMap = ICS.second; + for (auto &IFS : FSMap) { + FunctionSamples &FS = const_cast(IFS.second); + FSToUpdate.push(&FS); + } + } + } + } + + SampleProfileReader &CurrentReader; + Module &CurrentModule; + DenseMap &CurrentGUIDToFuncNameMap; +}; + +template class SampleProfileLoaderImpl { + + using InstructionT = typename afdo_detail::TypeMap::InstructionT; + using BasicBlockT = typename afdo_detail::TypeMap::BasicBlockT; + using BlockFrequencyInfoT = + typename afdo_detail::TypeMap::BlockFrequencyInfoT; + using FunctionT = typename afdo_detail::TypeMap::FunctionT; + using LoopT = typename afdo_detail::TypeMap::LoopT; + using LoopInfoT = typename afdo_detail::TypeMap::LoopInfoT; + using OptRemarkEmitterT = + typename afdo_detail::TypeMap::OptRemarkEmitterT; + using OptRemarkAnalysisT = + typename afdo_detail::TypeMap::OptRemarkAnalysisT; + using DominatorTreeT = typename afdo_detail::TypeMap::DominatorTreeT; + using PostDominatorTreeT = + typename afdo_detail::TypeMap::PostDominatorTreeT; + + using BlockWeightMap = DenseMap; + using EquivalenceClassMap = + DenseMap; + using Edge = std::pair; + using EdgeWeightMap = DenseMap; + using BlockEdgeMap = + DenseMap>; + +public: + SampleProfileLoaderImpl( + StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase, + std::function GetAssumptionCache, + std::function GetTargetTransformInfo, + std::function GetTLI) + : CoverageTracker(), Filename(std::string(Name)), + RemappingFilename(std::string(RemapName)), + GetAC(std::move(GetAssumptionCache)), + GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)), + LTOPhase(LTOPhase) {} + + SampleProfileLoaderImpl(StringRef Name, StringRef RemapName) + : CoverageTracker(), Filename(std::string(Name)), + RemappingFilename(std::string(RemapName)) {} + + bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr); + bool runOnModule(Module &M, ModuleAnalysisManager *AM, + ProfileSummaryInfo *_PSI, CallGraph *CG); + + bool runOnFunction(FunctionT &F, ModuleAnalysisManager *AM = nullptr); + void dump() { Reader->dump(); } + +protected: + friend class SampleCoverageTracker; + + inline bool isMachineBBProfileLoader() { + return std::is_same::value; + } + inline Function &getFunction(FunctionT &Func); + inline unsigned getSampleProfileMaxPropagateIterations(); + inline bool getNoWarnSampleUnused(); + inline unsigned getSampleProfileRecordCoverage(); + inline unsigned getSampleProfileSampleCoverage(); + inline bool shouldIgnoreInst(const InstructionT &); + inline bool zeroWeightInlinedCallee(const InstructionT &); + inline const BasicBlockT *getEntryBB(const FunctionT *F); + + unsigned getFunctionLoc(FunctionT &Func); + ErrorOr getInstWeight(const InstructionT &I); + ErrorOr getProbeWeight(const InstructionT &I) { + return std::error_code(); + } + ErrorOr getBlockWeight(const BasicBlockT *BB); + mutable DenseMap + DILocation2SampleMap; + const FunctionSamples *findFunctionSamples(const InstructionT &I) const; + void printEdgeWeight(raw_ostream &OS, Edge E); + void printBlockWeight(raw_ostream &OS, const BasicBlockT *BB) const; + void printBlockEquivalence(raw_ostream &OS, const BasicBlockT *BB); + bool computeBlockWeights(FunctionT &F); + void findEquivalenceClasses(FunctionT &F); + void findEquivalencesFor(BasicBlockT *BB1, + ArrayRef Descendants, + PostDominatorTreeT *DomTree); + void propagateWeights(FunctionT &F); + uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge); + void buildEdges(FunctionT &F); + bool propagateThroughEdges(FunctionT &F, bool UpdateBlockCount); + void computeDominanceAndLoopInfo(FunctionT &F) {} + void clearFunctionData(); + bool + computeAndPropagateWeights(FunctionT &F, + const DenseSet &InlinedGUIDs); + void generateMDProfMetadata(FunctionT &F) {} + + /// Map basic blocks to their computed weights. + /// + /// The weight of a basic block is defined to be the maximum + /// of all the instruction weights in that block. + BlockWeightMap BlockWeights; + + /// Map edges to their computed weights. + /// + /// Edge weights are computed by propagating basic block weights in + /// SampleProfile::propagateWeights. + EdgeWeightMap EdgeWeights; + + /// Set of visited blocks during propagation. + SmallPtrSet VisitedBlocks; + + /// Set of visited edges during propagation. + SmallSet VisitedEdges; + + /// Equivalence classes for block weights. + /// + /// Two blocks BB1 and BB2 are in the same equivalence class if they + /// dominate and post-dominate each other, and they are in the same loop + /// nest. When this happens, the two blocks are guaranteed to execute + /// the same number of times. + EquivalenceClassMap EquivalenceClass; + + /// Dominance, post-dominance and loop information. + std::unique_ptr DT; + std::unique_ptr PDT; + std::unique_ptr LI; + + /// Predecessors for each basic block in the CFG. + BlockEdgeMap Predecessors; + + /// Successors for each basic block in the CFG. + BlockEdgeMap Successors; + + SampleCoverageTracker CoverageTracker; + + /// Profile reader object. + std::unique_ptr Reader; + + /// Samples collected for the body of this function. + FunctionSamples *Samples = nullptr; + + /// Name of the profile file to load. + std::string Filename; + + /// Name of the profile remapping file to load. + std::string RemappingFilename; + + /// Flag indicating whether the profile input loaded successfully. + bool ProfileIsValid = false; + + /// Optimization Remark Emitter used to emit diagnostic remarks. + OptRemarkEmitterT *ORE = nullptr; + + // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for + // all the function symbols defined or declared in current module. + DenseMap GUIDToFuncNameMap; + + // For symbol in profile symbol list, whether to regard their profiles + // to be accurate. It is mainly decided by existance of profile symbol + // list and -profile-accurate-for-symsinlist flag, but it can be + // overriden by -profile-sample-accurate or profile-sample-accurate + // attribute. + bool ProfAccForSymsInList; + + // == The followings are only used by BasicBlock type. + const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const; + bool emitAnnotations(FunctionT &F); + std::vector + findIndirectCallFunctionSamples(const InstructionT &I, uint64_t &Sum) const; + bool inlineCallInstruction(CallBase &CB); + bool inlineHotFunctions(FunctionT &F, + DenseSet &InlinedGUIDs); + // Inline cold/small functions in addition to hot ones + bool shouldInlineColdCallee(CallBase &CallInst); + void emitOptimizationRemarksForInlineCandidates( + const SmallVectorImpl &Candidates, const FunctionT &F, + bool Hot); + std::vector buildFunctionOrder(Module &M, CallGraph *CG); + + std::function GetAC; + std::function GetTTI; + std::function GetTLI; + + /// Map from function name to Function *. Used to find the function from + /// the function name. If the function name contains suffix, additional + /// entry is added to map from the stripped name to the function if there + /// is one-to-one mapping. + StringMap SymbolMap; + + /// Profile tracker for different context. + std::unique_ptr ContextTracker; + + // Information recorded when we declined to inline a call site + // because we have determined it is too cold is accumulated for + // each callee function. Initially this is just the entry count. + struct NotInlinedProfileInfo { + uint64_t entryCount; + }; + DenseMap notInlinedCallInfo; + + /// Profle Symbol list tells whether a function name appears in the binary + /// used to generate the current profile. + std::unique_ptr PSL; + + /// Total number of samples collected in this profile. + /// + /// This is the sum of all the samples collected in all the functions executed + /// at runtime. + uint64_t TotalCollectedSamples = 0; + + /// Flag indicating which LTO/ThinLTO phase the pass is invoked in. + /// + /// We need to know the LTO phase because for example in ThinLTOPrelink + /// phase, in annotation, we should not promote indirect calls. Instead, + /// we will mark GUIDs that needs to be annotated to the function. + ThinOrFullLTOPhase LTOPhase; + + /// Profile Summary Info computed from sample profile. + ProfileSummaryInfo *PSI = nullptr; + + /// Flag indicating whether input profile is context-sensitive + bool ProfileIsCS = false; + + // All the Names used in FunctionSamples including outline function + // names, inline instance names and call target names. + StringSet<> NamesInProfile; + + // External inline advisor used to replay inline decision from remarks. + std::unique_ptr ExternalInlineAdvisor; + + // A pseudo probe helper to correlate the imported sample counts. + std::unique_ptr ProbeManager; + + // == The following are only used by MachineBasicBlock type. + void setBranchProbs(FunctionT &F); +}; + +/// Return true if the given callsite is hot wrt to hot cutoff threshold. +/// +/// Functions that were inlined in the original binary will be represented +/// in the inline stack in the sample profile. If the profile shows that +/// the original inline decision was "good" (i.e., the callsite is executed +/// frequently), then we will recreate the inline decision and apply the +/// profile from the inlined callsite. +/// +/// To decide whether an inlined callsite is hot, we compare the callsite +/// sample count with the hot cutoff computed by ProfileSummaryInfo, it is +/// regarded as hot if the count is above the cutoff value. +/// +/// When ProfileAccurateForSymsInList is enabled and profile symbol list +/// is present, functions in the profile symbol list but without profile will +/// be regarded as cold and much less inlining will happen in CGSCC inlining +/// pass, so we tend to lower the hot criteria here to allow more early +/// inlining to happen for warm callsites and it is helpful for performance. +static bool callsiteIsHot(const FunctionSamples *CallsiteFS, + ProfileSummaryInfo *PSI, bool ProfAccForSymsInList) { + if (!CallsiteFS) + return false; // The callsite was not inlined in the original binary. + + assert(PSI && "PSI is expected to be non null"); + uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples(); + if (ProfAccForSymsInList) + return !PSI->isColdCount(CallsiteTotalSamples); + else + return PSI->isHotCount(CallsiteTotalSamples); +} + +/// Mark as used the sample record for the given function samples at +/// (LineOffset, Discriminator). +/// +/// \returns true if this is the first time we mark the given record. +inline bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS, + uint32_t LineOffset, + uint32_t Discriminator, + uint64_t Samples) { + LineLocation Loc(LineOffset, Discriminator); + unsigned &Count = SampleCoverage[FS][Loc]; + bool FirstTime = (++Count == 1); + if (FirstTime) + TotalUsedSamples += Samples; + return FirstTime; +} + +/// Return the number of sample records that were applied from this profile. +/// +/// This count does not include records from cold inlined callsites. +inline unsigned +SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS, + ProfileSummaryInfo *PSI) const { + auto I = SampleCoverage.find(FS); + + // The size of the coverage map for FS represents the number of records + // that were marked used at least once. + unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0; + + // If there are inlined callsites in this function, count the samples found + // in the respective bodies. However, do not bother counting callees with 0 + // total samples, these are callees that were never invoked at runtime. + for (const auto &I : FS->getCallsiteSamples()) + for (const auto &J : I.second) { + const FunctionSamples *CalleeSamples = &J.second; + if (PSI == nullptr || + callsiteIsHot(CalleeSamples, PSI, ProfAccForSymsInList)) + Count += countUsedRecords(CalleeSamples, PSI); + } + + return Count; +} + +/// Return the number of sample records in the body of this profile. +/// +/// This count does not include records from cold inlined callsites. +inline unsigned +SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS, + ProfileSummaryInfo *PSI) const { + unsigned Count = FS->getBodySamples().size(); + + // Only count records in hot callsites. + for (const auto &I : FS->getCallsiteSamples()) + for (const auto &J : I.second) { + const FunctionSamples *CalleeSamples = &J.second; + if (PSI == nullptr || + callsiteIsHot(CalleeSamples, PSI, ProfAccForSymsInList)) + Count += countBodyRecords(CalleeSamples, PSI); + } + + return Count; +} + +/// Return the number of samples collected in the body of this profile. +/// +/// This count does not include samples from cold inlined callsites. +inline uint64_t +SampleCoverageTracker::countBodySamples(const FunctionSamples *FS, + ProfileSummaryInfo *PSI) const { + uint64_t Total = 0; + for (const auto &I : FS->getBodySamples()) + Total += I.second.getSamples(); + + // Only count samples in hot callsites. + for (const auto &I : FS->getCallsiteSamples()) + for (const auto &J : I.second) { + const FunctionSamples *CalleeSamples = &J.second; + if (PSI == nullptr || + callsiteIsHot(CalleeSamples, PSI, ProfAccForSymsInList)) + Total += countBodySamples(CalleeSamples, PSI); + } + + return Total; +} + +/// Return the fraction of sample records used in this profile. +/// +/// The returned value is an unsigned integer in the range 0-100 indicating +/// the percentage of sample records that were used while applying this +/// profile to the associated function. +inline unsigned SampleCoverageTracker::computeCoverage(unsigned Used, + unsigned Total) const { + assert(Used <= Total && + "number of used records cannot exceed the total number of records"); + return Total > 0 ? Used * 100 / Total : 100; +} + +/// Clear all the per-function data used to load samples and propagate weights. +template void SampleProfileLoaderImpl::clearFunctionData() { + BlockWeights.clear(); + EdgeWeights.clear(); + VisitedBlocks.clear(); + VisitedEdges.clear(); + EquivalenceClass.clear(); + DT = nullptr; + PDT = nullptr; + LI = nullptr; + Predecessors.clear(); + Successors.clear(); + CoverageTracker.clear(); +} + +#ifndef NDEBUG +/// Print the weight of edge \p E on stream \p OS. +/// +/// \param OS Stream to emit the output to. +/// \param E Edge to print. +template +void SampleProfileLoaderImpl::printEdgeWeight(raw_ostream &OS, Edge E) { + OS << "weight[" << E.first->getName() << "->" << E.second->getName() + << "]: " << EdgeWeights[E] << "\n"; +} + +/// Print the equivalence class of block \p BB on stream \p OS. +/// +/// \param OS Stream to emit the output to. +/// \param BB Block to print. +template +void SampleProfileLoaderImpl::printBlockEquivalence(raw_ostream &OS, + const BasicBlockT *BB) { + const BasicBlockT *Equiv = EquivalenceClass[BB]; + OS << "equivalence[" << BB->getName() + << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n"; +} + +/// Print the weight of block \p BB on stream \p OS. +/// +/// \param OS Stream to emit the output to. +/// \param BB Block to print. +template +void SampleProfileLoaderImpl::printBlockWeight( + raw_ostream &OS, const BasicBlockT *BB) const { + const auto &I = BlockWeights.find(BB); + uint64_t W = (I == BlockWeights.end() ? 0 : I->second); + OS << "weight[" << BB->getName() << "]: " << W << "\n"; +} +#endif + +/// Get the FunctionSamples for an instruction. +/// +/// The FunctionSamples of an instruction \p Inst is the inlined instance +/// in which that instruction is coming from. We traverse the inline stack +/// of that instruction, and match it with the tree nodes in the profile. +/// +/// \param Inst Instruction to query. +/// +/// \returns the FunctionSamples pointer to the inlined instance. +template +const FunctionSamples *SampleProfileLoaderImpl::findFunctionSamples( + const InstructionT &Inst) const { + const DILocation *DIL = Inst.getDebugLoc(); + if (!DIL) + return Samples; + + auto it = DILocation2SampleMap.try_emplace(DIL, nullptr); + if (it.second) + it.first->second = Samples->findFunctionSamples(DIL); + return it.first->second; +} + +template <> +inline Function & +SampleProfileLoaderImpl::getFunction(FunctionT &Func) { + return Func.getFunction(); +} + +template <> +inline Function & +SampleProfileLoaderImpl::getFunction(FunctionT &Func) { + return Func; +} + +/// Get the weight for an instruction. +/// +/// The "weight" of an instruction \p Inst is the number of samples +/// collected on that instruction at runtime. To retrieve it, we +/// need to compute the line number of \p Inst relative to the start of its +/// function. We use HeaderLineno to compute the offset. We then +/// look up the samples collected for \p Inst using BodySamples. +/// +/// \param Inst Instruction to query. +/// +/// \returns the weight of \p Inst. +template +ErrorOr +SampleProfileLoaderImpl::getInstWeight(const InstructionT &Inst) { + if (FunctionSamples::ProfileIsProbeBased) + return getProbeWeight(Inst); + + const DebugLoc &DLoc = Inst.getDebugLoc(); + if (!DLoc) + return std::error_code(); + + const FunctionSamples *FS = findFunctionSamples(Inst); + if (!FS) + return std::error_code(); + + // Ignore all intrinsics, phinodes and branch instructions. + // Branch and phinodes instruction usually contains debug info from sources + // outside of the residing basic block, thus we ignore them during annotation. + if (shouldIgnoreInst(Inst)) + return std::error_code(); + + // If a direct call/invoke instruction is inlined in profile + // (findCalleeFunctionSamples returns non-empty result), but not inlined here, + // it means that the inlined callsite has no sample, thus the call + // instruction should have 0 count. + if (zeroWeightInlinedCallee(Inst)) + return 0; + + const DILocation *DIL = DLoc; + uint32_t LineOffset = FunctionSamples::getOffset(DIL); + uint32_t Discriminator = DIL->getBaseDiscriminator(); + ErrorOr R = FS->findSamplesAt(LineOffset, Discriminator); + if (R) { + bool FirstMark = + CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get()); + if (FirstMark) { + ORE->emit([&]() { + // OptRemarkAnalysisT Remark(DEBUG_TYPE, "AppliedSamples", + // DiagnosticLocation(), Inst.getParent()); + OptRemarkAnalysisT Remark(DEBUG_TYPE, "AppliedSamples", &Inst); + Remark << "Applied " << ore::NV("NumSamples", *R); + Remark << " samples from profile (offset: "; + Remark << ore::NV("LineOffset", LineOffset); + if (Discriminator) { + Remark << "."; + Remark << ore::NV("Discriminator", Discriminator); + } + Remark << ")"; + return Remark; + }); + } + LLVM_DEBUG(dbgs() << " " << DLoc.getLine() << "." + << DIL->getBaseDiscriminator() << ":" << Inst + << " (line offset: " << LineOffset << "." + << DIL->getBaseDiscriminator() << " - weight: " << R.get() + << ")\n"); + } + return R; +} + +/// Compute the weight of a basic block. +/// +/// The weight of basic block \p BB is the maximum weight of all the +/// instructions in BB. +/// +/// \param BB The basic block to query. +/// +/// \returns the weight for \p BB. +template +ErrorOr +SampleProfileLoaderImpl::getBlockWeight(const BasicBlockT *BB) { + uint64_t Max = 0; + bool HasWeight = false; + for (auto &I : *BB) { + const ErrorOr &R = getInstWeight(I); + if (R) { + Max = std::max(Max, R.get()); + HasWeight = true; + } + } + return HasWeight ? ErrorOr(Max) : std::error_code(); +} + +/// Compute and store the weights of every basic block. +/// +/// This populates the BlockWeights map by computing +/// the weights of every basic block in the CFG. +/// +/// \param F The function to query. +template +bool SampleProfileLoaderImpl::computeBlockWeights(FunctionT &F) { + bool Changed = false; + LLVM_DEBUG(dbgs() << "Block weights\n"); + for (const auto &BB : F) { + ErrorOr Weight = getBlockWeight(&BB); + if (Weight) { + BlockWeights[&BB] = Weight.get(); + VisitedBlocks.insert(&BB); + Changed = true; + } + LLVM_DEBUG(printBlockWeight(dbgs(), &BB)); + } + + return Changed; +} + +/// Find equivalence classes for the given block. +/// +/// This finds all the blocks that are guaranteed to execute the same +/// number of times as \p BB1. To do this, it traverses all the +/// descendants of \p BB1 in the dominator or post-dominator tree. +/// +/// A block BB2 will be in the same equivalence class as \p BB1 if +/// the following holds: +/// +/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2 +/// is a descendant of \p BB1 in the dominator tree, then BB2 should +/// dominate BB1 in the post-dominator tree. +/// +/// 2- Both BB2 and \p BB1 must be in the same loop. +/// +/// For every block BB2 that meets those two requirements, we set BB2's +/// equivalence class to \p BB1. +/// +/// \param BB1 Block to check. +/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree. +/// \param DomTree Opposite dominator tree. If \p Descendants is filled +/// with blocks from \p BB1's dominator tree, then +/// this is the post-dominator tree, and vice versa. +template +void SampleProfileLoaderImpl::findEquivalencesFor( + BasicBlockT *BB1, ArrayRef Descendants, + PostDominatorTreeT *DomTree) { + const BasicBlockT *EC = EquivalenceClass[BB1]; + uint64_t Weight = BlockWeights[EC]; + for (const auto *BB2 : Descendants) { + bool IsDomParent = DomTree->dominates(BB2, BB1); + bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2); + if (BB1 != BB2 && IsDomParent && IsInSameLoop) { + EquivalenceClass[BB2] = EC; + // If BB2 is visited, then the entire EC should be marked as visited. + if (VisitedBlocks.count(BB2)) { + VisitedBlocks.insert(EC); + } + + // If BB2 is heavier than BB1, make BB2 have the same weight + // as BB1. + // + // Note that we don't worry about the opposite situation here + // (when BB2 is lighter than BB1). We will deal with this + // during the propagation phase. Right now, we just want to + // make sure that BB1 has the largest weight of all the + // members of its equivalence set. + Weight = std::max(Weight, BlockWeights[BB2]); + } + } + + const BasicBlockT *EntryBB = getEntryBB(EC->getParent()); + if (EC == EntryBB) { + BlockWeights[EC] = Samples->getHeadSamples() + 1; + } else { + BlockWeights[EC] = Weight; + } +} + +/// Find equivalence classes. +/// +/// Since samples may be missing from blocks, we can fill in the gaps by setting +/// the weights of all the blocks in the same equivalence class to the same +/// weight. To compute the concept of equivalence, we use dominance and loop +/// information. Two blocks B1 and B2 are in the same equivalence class if B1 +/// dominates B2, B2 post-dominates B1 and both are in the same loop. +/// +/// \param F The function to query. +template +void SampleProfileLoaderImpl::findEquivalenceClasses(FunctionT &F) { + SmallVector DominatedBBs; + LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n"); + // Find equivalence sets based on dominance and post-dominance information. + for (auto &BB : F) { + BasicBlockT *BB1 = &BB; + + // Compute BB1's equivalence class once. + if (EquivalenceClass.count(BB1)) { + LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1)); + continue; + } + + // By default, blocks are in their own equivalence class. + EquivalenceClass[BB1] = BB1; + + // Traverse all the blocks dominated by BB1. We are looking for + // every basic block BB2 such that: + // + // 1- BB1 dominates BB2. + // 2- BB2 post-dominates BB1. + // 3- BB1 and BB2 are in the same loop nest. + // + // If all those conditions hold, it means that BB2 is executed + // as many times as BB1, so they are placed in the same equivalence + // class by making BB2's equivalence class be BB1. + DominatedBBs.clear(); + DT->getDescendants(BB1, DominatedBBs); + findEquivalencesFor(BB1, DominatedBBs, PDT.get()); + + LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1)); + } + + // Assign weights to equivalence classes. + // + // All the basic blocks in the same equivalence class will execute + // the same number of times. Since we know that the head block in + // each equivalence class has the largest weight, assign that weight + // to all the blocks in that equivalence class. + LLVM_DEBUG( + dbgs() << "\nAssign the same weight to all blocks in the same class\n"); + for (auto &BI : F) { + const BasicBlockT *BB = &BI; + const BasicBlockT *EquivBB = EquivalenceClass[BB]; + if (BB != EquivBB) + BlockWeights[BB] = BlockWeights[EquivBB]; + LLVM_DEBUG(printBlockWeight(dbgs(), BB)); + } +} + +/// Visit the given edge to decide if it has a valid weight. +/// +/// If \p E has not been visited before, we copy to \p UnknownEdge +/// and increment the count of unknown edges. +/// +/// \param E Edge to visit. +/// \param NumUnknownEdges Current number of unknown edges. +/// \param UnknownEdge Set if E has not been visited before. +/// +/// \returns E's weight, if known. Otherwise, return 0. +template +uint64_t SampleProfileLoaderImpl::visitEdge(Edge E, + unsigned *NumUnknownEdges, + Edge *UnknownEdge) { + if (!VisitedEdges.count(E)) { + (*NumUnknownEdges)++; + *UnknownEdge = E; + return 0; + } + + return EdgeWeights[E]; +} + +/// Propagate weights through incoming/outgoing edges. +/// +/// If the weight of a basic block is known, and there is only one edge +/// with an unknown weight, we can calculate the weight of that edge. +/// +/// Similarly, if all the edges have a known count, we can calculate the +/// count of the basic block, if needed. +/// +/// \param F Function to process. +/// \param UpdateBlockCount Whether we should update basic block counts that +/// has already been annotated. +/// +/// \returns True if new weights were assigned to edges or blocks. +template +bool SampleProfileLoaderImpl::propagateThroughEdges(FunctionT &F, + bool UpdateBlockCount) { + bool Changed = false; + LLVM_DEBUG(dbgs() << "\nPropagation through edges\n"); + for (const auto &BI : F) { + const BasicBlockT *BB = &BI; + const BasicBlockT *EC = EquivalenceClass[BB]; + + // Visit all the predecessor and successor edges to determine + // which ones have a weight assigned already. Note that it doesn't + // matter that we only keep track of a single unknown edge. The + // only case we are interested in handling is when only a single + // edge is unknown (see setEdgeOrBlockWeight). + for (unsigned i = 0; i < 2; i++) { + uint64_t TotalWeight = 0; + unsigned NumUnknownEdges = 0, NumTotalEdges = 0; + Edge UnknownEdge, SelfReferentialEdge, SingleEdge; + + if (i == 0) { + // First, visit all predecessor edges. + NumTotalEdges = Predecessors[BB].size(); + for (auto *Pred : Predecessors[BB]) { + Edge E = std::make_pair(Pred, BB); + TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); + if (E.first == E.second) + SelfReferentialEdge = E; + } + if (NumTotalEdges == 1) { + SingleEdge = std::make_pair(Predecessors[BB][0], BB); + } + } else { + // On the second round, visit all successor edges. + NumTotalEdges = Successors[BB].size(); + for (auto *Succ : Successors[BB]) { + Edge E = std::make_pair(BB, Succ); + TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); + } + if (NumTotalEdges == 1) { + SingleEdge = std::make_pair(BB, Successors[BB][0]); + } + } + + // After visiting all the edges, there are three cases that we + // can handle immediately: + // + // - All the edge weights are known (i.e., NumUnknownEdges == 0). + // In this case, we simply check that the sum of all the edges + // is the same as BB's weight. If not, we change BB's weight + // to match. Additionally, if BB had not been visited before, + // we mark it visited. + // + // - Only one edge is unknown and BB has already been visited. + // In this case, we can compute the weight of the edge by + // subtracting the total block weight from all the known + // edge weights. If the edges weight more than BB, then the + // edge of the last remaining edge is set to zero. + // + // - There exists a self-referential edge and the weight of BB is + // known. In this case, this edge can be based on BB's weight. + // We add up all the other known edges and set the weight on + // the self-referential edge as we did in the previous case. + // + // In any other case, we must continue iterating. Eventually, + // all edges will get a weight, or iteration will stop when + // it reaches SampleProfileMaxPropagateIterations. + if (NumUnknownEdges <= 1) { + uint64_t &BBWeight = BlockWeights[EC]; + if (NumUnknownEdges == 0) { + if (!VisitedBlocks.count(EC)) { + // If we already know the weight of all edges, the weight of the + // basic block can be computed. It should be no larger than the sum + // of all edge weights. + if (TotalWeight > BBWeight) { + BBWeight = TotalWeight; + Changed = true; + LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName() + << " known. Set weight for block: "; + printBlockWeight(dbgs(), BB);); + } + } else if (NumTotalEdges == 1 && + EdgeWeights[SingleEdge] < BlockWeights[EC]) { + // If there is only one edge for the visited basic block, use the + // block weight to adjust edge weight if edge weight is smaller. + EdgeWeights[SingleEdge] = BlockWeights[EC]; + Changed = true; + } + } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) { + // If there is a single unknown edge and the block has been + // visited, then we can compute E's weight. + if (BBWeight >= TotalWeight) + EdgeWeights[UnknownEdge] = BBWeight - TotalWeight; + else + EdgeWeights[UnknownEdge] = 0; + const BasicBlockT *OtherEC; + if (i == 0) + OtherEC = EquivalenceClass[UnknownEdge.first]; + else + OtherEC = EquivalenceClass[UnknownEdge.second]; + // Edge weights should never exceed the BB weights it connects. + if (VisitedBlocks.count(OtherEC) && + EdgeWeights[UnknownEdge] > BlockWeights[OtherEC]) + EdgeWeights[UnknownEdge] = BlockWeights[OtherEC]; + VisitedEdges.insert(UnknownEdge); + Changed = true; + LLVM_DEBUG(dbgs() << "Set weight for edge: "; + printEdgeWeight(dbgs(), UnknownEdge)); + } + } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) { + // If a block Weights 0, all its in/out edges should weight 0. + if (i == 0) { + for (auto *Pred : Predecessors[BB]) { + Edge E = std::make_pair(Pred, BB); + EdgeWeights[E] = 0; + VisitedEdges.insert(E); + } + } else { + for (auto *Succ : Successors[BB]) { + Edge E = std::make_pair(BB, Succ); + EdgeWeights[E] = 0; + VisitedEdges.insert(E); + } + } + } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) { + uint64_t &BBWeight = BlockWeights[BB]; + // We have a self-referential edge and the weight of BB is known. + if (BBWeight >= TotalWeight) + EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight; + else + EdgeWeights[SelfReferentialEdge] = 0; + VisitedEdges.insert(SelfReferentialEdge); + Changed = true; + LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: "; + printEdgeWeight(dbgs(), SelfReferentialEdge)); + } + if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) { + BlockWeights[EC] = TotalWeight; + VisitedBlocks.insert(EC); + Changed = true; + } + } + } + + return Changed; +} + +/// Propagate weights into edges +/// +/// The following rules are applied to every block BB in the CFG: +/// +/// - If BB has a single predecessor/successor, then the weight +/// of that edge is the weight of the block. +/// +/// - If all incoming or outgoing edges are known except one, and the +/// weight of the block is already known, the weight of the unknown +/// edge will be the weight of the block minus the sum of all the known +/// edges. If the sum of all the known edges is larger than BB's weight, +/// we set the unknown edge weight to zero. +/// +/// - If there is a self-referential edge, and the weight of the block is +/// known, the weight for that edge is set to the weight of the block +/// minus the weight of the other incoming edges to that block (if +/// known). +template +void SampleProfileLoaderImpl::propagateWeights(FunctionT &F) { + bool Changed = true; + unsigned I = 0; + + // If BB weight is larger than its corresponding loop's header BB weight, + // use the BB weight to replace the loop header BB weight. + for (auto &BI : F) { + BasicBlockT *BB = &BI; + LoopT *L = LI->getLoopFor(BB); + if (!L) { + continue; + } + BasicBlockT *Header = L->getHeader(); + if (Header && BlockWeights[BB] > BlockWeights[Header]) { + BlockWeights[Header] = BlockWeights[BB]; + } + } + + // Before propagation starts, build, for each block, a list of + // unique predecessors and successors. This is necessary to handle + // identical edges in multiway branches. Since we visit all blocks and all + // edges of the CFG, it is cleaner to build these lists once at the start + // of the pass. + buildEdges(F); + + // Propagate until we converge or we go past the iteration limit. + while (Changed && I++ < getSampleProfileMaxPropagateIterations()) { + Changed = propagateThroughEdges(F, false); + } + + // The first propagation propagates BB counts from annotated BBs to unknown + // BBs. The 2nd propagation pass resets edges weights, and use all BB weights + // to propagate edge weights. + VisitedEdges.clear(); + Changed = true; + while (Changed && I++ < getSampleProfileMaxPropagateIterations()) { + Changed = propagateThroughEdges(F, false); + } + + // The 3rd propagation pass allows adjust annotated BB weights that are + // obviously wrong. + Changed = true; + while (Changed && I++ < getSampleProfileMaxPropagateIterations()) { + Changed = propagateThroughEdges(F, true); + } + + if (isMachineBBProfileLoader()) + return; + generateMDProfMetadata(F); +} + +/// Get the line number for the function header. +/// +/// This looks up function \p F in the current compilation unit and +/// retrieves the line number where the function is defined. This is +/// line 0 for all the samples read from the profile file. Every line +/// number is relative to this line. +/// +/// \param F Function object to query. +/// +/// \returns the line number where \p F is defined. If it returns 0, +/// it means that there is no debug information available for \p F. +template +unsigned SampleProfileLoaderImpl::getFunctionLoc(FunctionT &Func) { + const Function &F = getFunction(Func); + if (DISubprogram *S = F.getSubprogram()) + return S->getLine(); + + if (getNoWarnSampleUnused()) + return 0; + + // If the start of \p F is missing, emit a diagnostic to inform the user + // about the missed opportunity. + F.getContext().diagnose(DiagnosticInfoSampleProfile( + "No debug information found in function " + F.getName() + + ": Function profile not used", + DS_Warning)); + return 0; +} + +/// Generate branch weight metadata for all branches in \p F. +/// +/// Branch weights are computed out of instruction samples using a +/// propagation heuristic. Propagation proceeds in 3 phases: +/// +/// 1- Assignment of block weights. All the basic blocks in the function +/// are initial assigned the same weight as their most frequently +/// executed instruction. +/// +/// 2- Creation of equivalence classes. Since samples may be missing from +/// blocks, we can fill in the gaps by setting the weights of all the +/// blocks in the same equivalence class to the same weight. To compute +/// the concept of equivalence, we use dominance and loop information. +/// Two blocks B1 and B2 are in the same equivalence class if B1 +/// dominates B2, B2 post-dominates B1 and both are in the same loop. +/// +/// 3- Propagation of block weights into edges. This uses a simple +/// propagation heuristic. The following rules are applied to every +/// block BB in the CFG: +/// +/// - If BB has a single predecessor/successor, then the weight +/// of that edge is the weight of the block. +/// +/// - If all the edges are known except one, and the weight of the +/// block is already known, the weight of the unknown edge will +/// be the weight of the block minus the sum of all the known +/// edges. If the sum of all the known edges is larger than BB's weight, +/// we set the unknown edge weight to zero. +/// +/// - If there is a self-referential edge, and the weight of the block is +/// known, the weight for that edge is set to the weight of the block +/// minus the weight of the other incoming edges to that block (if +/// known). +/// +/// Since this propagation is not guaranteed to finalize for every CFG, we +/// only allow it to proceed for a limited number of iterations (controlled +/// by -sample-profile-max-propagate-iterations). +/// +/// FIXME: Try to replace this propagation heuristic with a scheme +/// that is guaranteed to finalize. A work-list approach similar to +/// the standard value propagation algorithm used by SSA-CCP might +/// work here. +/// +/// Once all the branch weights are computed, we emit the MD_prof +/// metadata on BB using the computed values for each of its branches. +/// +/// \param F The function to query. +/// +/// \returns true if \p F was modified. Returns false, otherwise. +template +bool SampleProfileLoaderImpl::computeAndPropagateWeights( + FunctionT &F, const DenseSet &InlinedGUIDs) { + bool Changed = (InlinedGUIDs.size() != 0 || isMachineBBProfileLoader()); + // Compute basic block weights. + Changed |= computeBlockWeights(F); + + if (Changed) { + // Add an entry count to the function using the samples gathered at the + // function entry. + // Sets the GUIDs that are inlined in the profiled binary. This is used + // for ThinLink to make correct liveness analysis, and also make the IR + // match the profiled binary before annotation. + getFunction(F).setEntryCount( + ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real), + &InlinedGUIDs); + + // Compute dominance and loop info needed for propagation. + computeDominanceAndLoopInfo(F); + + // Find equivalence classes. + findEquivalenceClasses(F); + + // Propagate weights to all edges. + propagateWeights(F); + } + + // If coverage checking was requested, compute it now. + if (getSampleProfileRecordCoverage()) { + unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI); + unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI); + unsigned Coverage = CoverageTracker.computeCoverage(Used, Total); + if (Coverage < getSampleProfileRecordCoverage()) { + getFunction(F).getContext().diagnose(DiagnosticInfoSampleProfile( + getFunction(F).getSubprogram()->getFilename(), getFunctionLoc(F), + Twine(Used) + " of " + Twine(Total) + " available profile records (" + + Twine(Coverage) + "%) were applied", + DS_Warning)); + } + } + + if (getSampleProfileSampleCoverage()) { + uint64_t Used = CoverageTracker.getTotalUsedSamples(); + uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI); + unsigned Coverage = CoverageTracker.computeCoverage(Used, Total); + if (Coverage < getSampleProfileSampleCoverage()) { + getFunction(F).getContext().diagnose(DiagnosticInfoSampleProfile( + getFunction(F).getSubprogram()->getFilename(), getFunctionLoc(F), + Twine(Used) + " of " + Twine(Total) + " available profile samples (" + + Twine(Coverage) + "%) were applied", + DS_Warning)); + } + } + return Changed; +} + +#undef DEBUG_TYPE + +#endif // LLVM_TRANSFORMS_SAMPLEPROFILEIMPL_H Index: llvm/lib/Transforms/IPO/SampleProfile.cpp =================================================================== --- llvm/lib/Transforms/IPO/SampleProfile.cpp +++ llvm/lib/Transforms/IPO/SampleProfile.cpp @@ -22,16 +22,13 @@ //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO/SampleProfile.h" -#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/None.h" #include "llvm/ADT/SCCIterator.h" #include "llvm/ADT/SmallPtrSet.h" -#include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" -#include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Analysis/AssumptionCache.h" @@ -48,13 +45,10 @@ #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" -#include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/DebugLoc.h" -#include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalValue.h" -#include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" @@ -65,7 +59,6 @@ #include "llvm/IR/ValueSymbolTable.h" #include "llvm/InitializePasses.h" #include "llvm/Pass.h" -#include "llvm/ProfileData/InstrProf.h" #include "llvm/ProfileData/SampleProf.h" #include "llvm/ProfileData/SampleProfReader.h" #include "llvm/Support/Casting.h" @@ -77,6 +70,7 @@ #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/SampleContextTracker.h" +#include "llvm/Transforms/IPO/SampleProfileImpl.h" #include "llvm/Transforms/IPO/SampleProfileProbe.h" #include "llvm/Transforms/Instrumentation.h" #include "llvm/Transforms/Utils/CallPromotionUtils.h" @@ -182,612 +176,122 @@ "by inlining from sample profile loader."), cl::Hidden); -namespace { - -using BlockWeightMap = DenseMap; -using EquivalenceClassMap = DenseMap; -using Edge = std::pair; -using EdgeWeightMap = DenseMap; -using BlockEdgeMap = - DenseMap>; - -class SampleProfileLoader; - -class SampleCoverageTracker { -public: - SampleCoverageTracker(SampleProfileLoader &SPL) : SPLoader(SPL){}; - - bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset, - uint32_t Discriminator, uint64_t Samples); - unsigned computeCoverage(unsigned Used, unsigned Total) const; - unsigned countUsedRecords(const FunctionSamples *FS, - ProfileSummaryInfo *PSI) const; - unsigned countBodyRecords(const FunctionSamples *FS, - ProfileSummaryInfo *PSI) const; - uint64_t getTotalUsedSamples() const { return TotalUsedSamples; } - uint64_t countBodySamples(const FunctionSamples *FS, - ProfileSummaryInfo *PSI) const; - - void clear() { - SampleCoverage.clear(); - TotalUsedSamples = 0; - } - -private: - using BodySampleCoverageMap = std::map; - using FunctionSamplesCoverageMap = - DenseMap; - - /// Coverage map for sampling records. - /// - /// This map keeps a record of sampling records that have been matched to - /// an IR instruction. This is used to detect some form of staleness in - /// profiles (see flag -sample-profile-check-coverage). - /// - /// Each entry in the map corresponds to a FunctionSamples instance. This is - /// another map that counts how many times the sample record at the - /// given location has been used. - FunctionSamplesCoverageMap SampleCoverage; - - /// Number of samples used from the profile. - /// - /// When a sampling record is used for the first time, the samples from - /// that record are added to this accumulator. Coverage is later computed - /// based on the total number of samples available in this function and - /// its callsites. - /// - /// Note that this accumulator tracks samples used from a single function - /// and all the inlined callsites. Strictly, we should have a map of counters - /// keyed by FunctionSamples pointers, but these stats are cleared after - /// every function, so we just need to keep a single counter. - uint64_t TotalUsedSamples = 0; - - SampleProfileLoader &SPLoader; -}; - -class GUIDToFuncNameMapper { -public: - GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader, - DenseMap &GUIDToFuncNameMap) - : CurrentReader(Reader), CurrentModule(M), - CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) { - if (!CurrentReader.useMD5()) - return; - - for (const auto &F : CurrentModule) { - StringRef OrigName = F.getName(); - CurrentGUIDToFuncNameMap.insert( - {Function::getGUID(OrigName), OrigName}); - - // Local to global var promotion used by optimization like thinlto - // will rename the var and add suffix like ".llvm.xxx" to the - // original local name. In sample profile, the suffixes of function - // names are all stripped. Since it is possible that the mapper is - // built in post-thin-link phase and var promotion has been done, - // we need to add the substring of function name without the suffix - // into the GUIDToFuncNameMap. - StringRef CanonName = FunctionSamples::getCanonicalFnName(F); - if (CanonName != OrigName) - CurrentGUIDToFuncNameMap.insert( - {Function::getGUID(CanonName), CanonName}); - } - - // Update GUIDToFuncNameMap for each function including inlinees. - SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap); - } - - ~GUIDToFuncNameMapper() { - if (!CurrentReader.useMD5()) - return; - - CurrentGUIDToFuncNameMap.clear(); - - // Reset GUIDToFuncNameMap for of each function as they're no - // longer valid at this point. - SetGUIDToFuncNameMapForAll(nullptr); - } - -private: - void SetGUIDToFuncNameMapForAll(DenseMap *Map) { - std::queue FSToUpdate; - for (auto &IFS : CurrentReader.getProfiles()) { - FSToUpdate.push(&IFS.second); - } - - while (!FSToUpdate.empty()) { - FunctionSamples *FS = FSToUpdate.front(); - FSToUpdate.pop(); - FS->GUIDToFuncNameMap = Map; - for (const auto &ICS : FS->getCallsiteSamples()) { - const FunctionSamplesMap &FSMap = ICS.second; - for (auto &IFS : FSMap) { - FunctionSamples &FS = const_cast(IFS.second); - FSToUpdate.push(&FS); - } - } - } - } - - SampleProfileReader &CurrentReader; - Module &CurrentModule; - DenseMap &CurrentGUIDToFuncNameMap; -}; - -/// Sample profile pass. -/// -/// This pass reads profile data from the file specified by -/// -sample-profile-file and annotates every affected function with the -/// profile information found in that file. -class SampleProfileLoader { -public: - SampleProfileLoader( - StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase, - std::function GetAssumptionCache, - std::function GetTargetTransformInfo, - std::function GetTLI) - : GetAC(std::move(GetAssumptionCache)), - GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)), - CoverageTracker(*this), Filename(std::string(Name)), - RemappingFilename(std::string(RemapName)), LTOPhase(LTOPhase) {} - - bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr); - bool runOnModule(Module &M, ModuleAnalysisManager *AM, - ProfileSummaryInfo *_PSI, CallGraph *CG); - - void dump() { Reader->dump(); } - -protected: - friend class SampleCoverageTracker; - - bool runOnFunction(Function &F, ModuleAnalysisManager *AM); - unsigned getFunctionLoc(Function &F); - bool emitAnnotations(Function &F); - ErrorOr getInstWeight(const Instruction &I); - ErrorOr getProbeWeight(const Instruction &I); - ErrorOr getBlockWeight(const BasicBlock *BB); - const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const; - std::vector - findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const; - mutable DenseMap DILocation2SampleMap; - const FunctionSamples *findFunctionSamples(const Instruction &I) const; - bool inlineCallInstruction(CallBase &CB); - bool inlineHotFunctions(Function &F, - DenseSet &InlinedGUIDs); - // Inline cold/small functions in addition to hot ones - bool shouldInlineColdCallee(CallBase &CallInst); - void emitOptimizationRemarksForInlineCandidates( - const SmallVectorImpl &Candidates, const Function &F, - bool Hot); - void printEdgeWeight(raw_ostream &OS, Edge E); - void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const; - void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB); - bool computeBlockWeights(Function &F); - void findEquivalenceClasses(Function &F); - template - void findEquivalencesFor(BasicBlock *BB1, ArrayRef Descendants, - DominatorTreeBase *DomTree); - - void propagateWeights(Function &F); - uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge); - void buildEdges(Function &F); - std::vector buildFunctionOrder(Module &M, CallGraph *CG); - bool propagateThroughEdges(Function &F, bool UpdateBlockCount); - void computeDominanceAndLoopInfo(Function &F); - void clearFunctionData(); - bool callsiteIsHot(const FunctionSamples *CallsiteFS, - ProfileSummaryInfo *PSI); - - /// Map basic blocks to their computed weights. - /// - /// The weight of a basic block is defined to be the maximum - /// of all the instruction weights in that block. - BlockWeightMap BlockWeights; - - /// Map edges to their computed weights. - /// - /// Edge weights are computed by propagating basic block weights in - /// SampleProfile::propagateWeights. - EdgeWeightMap EdgeWeights; - - /// Set of visited blocks during propagation. - SmallPtrSet VisitedBlocks; - - /// Set of visited edges during propagation. - SmallSet VisitedEdges; - - /// Equivalence classes for block weights. - /// - /// Two blocks BB1 and BB2 are in the same equivalence class if they - /// dominate and post-dominate each other, and they are in the same loop - /// nest. When this happens, the two blocks are guaranteed to execute - /// the same number of times. - EquivalenceClassMap EquivalenceClass; - - /// Map from function name to Function *. Used to find the function from - /// the function name. If the function name contains suffix, additional - /// entry is added to map from the stripped name to the function if there - /// is one-to-one mapping. - StringMap SymbolMap; - - /// Dominance, post-dominance and loop information. - std::unique_ptr DT; - std::unique_ptr PDT; - std::unique_ptr LI; - - std::function GetAC; - std::function GetTTI; - std::function GetTLI; - - /// Predecessors for each basic block in the CFG. - BlockEdgeMap Predecessors; - - /// Successors for each basic block in the CFG. - BlockEdgeMap Successors; - - SampleCoverageTracker CoverageTracker; - - /// Profile reader object. - std::unique_ptr Reader; - - /// Profile tracker for different context. - std::unique_ptr ContextTracker; - - /// Samples collected for the body of this function. - FunctionSamples *Samples = nullptr; - - /// Name of the profile file to load. - std::string Filename; - - /// Name of the profile remapping file to load. - std::string RemappingFilename; - - /// Flag indicating whether the profile input loaded successfully. - bool ProfileIsValid = false; - - /// Flag indicating whether input profile is context-sensitive - bool ProfileIsCS = false; - - /// Flag indicating which LTO/ThinLTO phase the pass is invoked in. - /// - /// We need to know the LTO phase because for example in ThinLTOPrelink - /// phase, in annotation, we should not promote indirect calls. Instead, - /// we will mark GUIDs that needs to be annotated to the function. - ThinOrFullLTOPhase LTOPhase; - - /// Profile Summary Info computed from sample profile. - ProfileSummaryInfo *PSI = nullptr; - - /// Profle Symbol list tells whether a function name appears in the binary - /// used to generate the current profile. - std::unique_ptr PSL; - - /// Total number of samples collected in this profile. - /// - /// This is the sum of all the samples collected in all the functions executed - /// at runtime. - uint64_t TotalCollectedSamples = 0; - - /// Optimization Remark Emitter used to emit diagnostic remarks. - OptimizationRemarkEmitter *ORE = nullptr; - - // Information recorded when we declined to inline a call site - // because we have determined it is too cold is accumulated for - // each callee function. Initially this is just the entry count. - struct NotInlinedProfileInfo { - uint64_t entryCount; - }; - DenseMap notInlinedCallInfo; - - // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for - // all the function symbols defined or declared in current module. - DenseMap GUIDToFuncNameMap; - - // All the Names used in FunctionSamples including outline function - // names, inline instance names and call target names. - StringSet<> NamesInProfile; - - // For symbol in profile symbol list, whether to regard their profiles - // to be accurate. It is mainly decided by existance of profile symbol - // list and -profile-accurate-for-symsinlist flag, but it can be - // overriden by -profile-sample-accurate or profile-sample-accurate - // attribute. - bool ProfAccForSymsInList; - - // External inline advisor used to replay inline decision from remarks. - std::unique_ptr ExternalInlineAdvisor; - - // A pseudo probe helper to correlate the imported sample counts. - std::unique_ptr ProbeManager; -}; - -class SampleProfileLoaderLegacyPass : public ModulePass { -public: - // Class identification, replacement for typeinfo - static char ID; - - SampleProfileLoaderLegacyPass( - StringRef Name = SampleProfileFile, - ThinOrFullLTOPhase LTOPhase = ThinOrFullLTOPhase::None) - : ModulePass(ID), SampleLoader( - Name, SampleProfileRemappingFile, LTOPhase, - [&](Function &F) -> AssumptionCache & { - return ACT->getAssumptionCache(F); - }, - [&](Function &F) -> TargetTransformInfo & { - return TTIWP->getTTI(F); - }, - [&](Function &F) -> TargetLibraryInfo & { - return TLIWP->getTLI(F); - }) { - initializeSampleProfileLoaderLegacyPassPass( - *PassRegistry::getPassRegistry()); - } - - void dump() { SampleLoader.dump(); } - - bool doInitialization(Module &M) override { - return SampleLoader.doInitialization(M); - } - - StringRef getPassName() const override { return "Sample profile pass"; } - bool runOnModule(Module &M) override; - - void getAnalysisUsage(AnalysisUsage &AU) const override { - AU.addRequired(); - AU.addRequired(); - AU.addRequired(); - AU.addRequired(); - } - -private: - SampleProfileLoader SampleLoader; - AssumptionCacheTracker *ACT = nullptr; - TargetTransformInfoWrapperPass *TTIWP = nullptr; - TargetLibraryInfoWrapperPass *TLIWP = nullptr; -}; - -} // end anonymous namespace - -/// Return true if the given callsite is hot wrt to hot cutoff threshold. -/// -/// Functions that were inlined in the original binary will be represented -/// in the inline stack in the sample profile. If the profile shows that -/// the original inline decision was "good" (i.e., the callsite is executed -/// frequently), then we will recreate the inline decision and apply the -/// profile from the inlined callsite. -/// -/// To decide whether an inlined callsite is hot, we compare the callsite -/// sample count with the hot cutoff computed by ProfileSummaryInfo, it is -/// regarded as hot if the count is above the cutoff value. -/// -/// When ProfileAccurateForSymsInList is enabled and profile symbol list -/// is present, functions in the profile symbol list but without profile will -/// be regarded as cold and much less inlining will happen in CGSCC inlining -/// pass, so we tend to lower the hot criteria here to allow more early -/// inlining to happen for warm callsites and it is helpful for performance. -bool SampleProfileLoader::callsiteIsHot(const FunctionSamples *CallsiteFS, - ProfileSummaryInfo *PSI) { - if (!CallsiteFS) - return false; // The callsite was not inlined in the original binary. - - assert(PSI && "PSI is expected to be non null"); - uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples(); - if (ProfAccForSymsInList) - return !PSI->isColdCount(CallsiteTotalSamples); - else - return PSI->isHotCount(CallsiteTotalSamples); -} - -/// Mark as used the sample record for the given function samples at -/// (LineOffset, Discriminator). -/// -/// \returns true if this is the first time we mark the given record. -bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS, - uint32_t LineOffset, - uint32_t Discriminator, - uint64_t Samples) { - LineLocation Loc(LineOffset, Discriminator); - unsigned &Count = SampleCoverage[FS][Loc]; - bool FirstTime = (++Count == 1); - if (FirstTime) - TotalUsedSamples += Samples; - return FirstTime; +template <> +inline unsigned +SampleProfileLoaderImpl::getSampleProfileMaxPropagateIterations() { + return SampleProfileMaxPropagateIterations; } -/// Return the number of sample records that were applied from this profile. -/// -/// This count does not include records from cold inlined callsites. -unsigned -SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS, - ProfileSummaryInfo *PSI) const { - auto I = SampleCoverage.find(FS); - - // The size of the coverage map for FS represents the number of records - // that were marked used at least once. - unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0; - - // If there are inlined callsites in this function, count the samples found - // in the respective bodies. However, do not bother counting callees with 0 - // total samples, these are callees that were never invoked at runtime. - for (const auto &I : FS->getCallsiteSamples()) - for (const auto &J : I.second) { - const FunctionSamples *CalleeSamples = &J.second; - if (SPLoader.callsiteIsHot(CalleeSamples, PSI)) - Count += countUsedRecords(CalleeSamples, PSI); - } - - return Count; +template <> +inline bool SampleProfileLoaderImpl::getNoWarnSampleUnused() { + return NoWarnSampleUnused; } -/// Return the number of sample records in the body of this profile. -/// -/// This count does not include records from cold inlined callsites. -unsigned -SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS, - ProfileSummaryInfo *PSI) const { - unsigned Count = FS->getBodySamples().size(); - - // Only count records in hot callsites. - for (const auto &I : FS->getCallsiteSamples()) - for (const auto &J : I.second) { - const FunctionSamples *CalleeSamples = &J.second; - if (SPLoader.callsiteIsHot(CalleeSamples, PSI)) - Count += countBodyRecords(CalleeSamples, PSI); - } - - return Count; +template <> +inline unsigned +SampleProfileLoaderImpl::getSampleProfileRecordCoverage() { + return SampleProfileRecordCoverage; } -/// Return the number of samples collected in the body of this profile. -/// -/// This count does not include samples from cold inlined callsites. -uint64_t -SampleCoverageTracker::countBodySamples(const FunctionSamples *FS, - ProfileSummaryInfo *PSI) const { - uint64_t Total = 0; - for (const auto &I : FS->getBodySamples()) - Total += I.second.getSamples(); - - // Only count samples in hot callsites. - for (const auto &I : FS->getCallsiteSamples()) - for (const auto &J : I.second) { - const FunctionSamples *CalleeSamples = &J.second; - if (SPLoader.callsiteIsHot(CalleeSamples, PSI)) - Total += countBodySamples(CalleeSamples, PSI); - } - - return Total; +template <> +inline unsigned +SampleProfileLoaderImpl::getSampleProfileSampleCoverage() { + return SampleProfileSampleCoverage; } -/// Return the fraction of sample records used in this profile. -/// -/// The returned value is an unsigned integer in the range 0-100 indicating -/// the percentage of sample records that were used while applying this -/// profile to the associated function. -unsigned SampleCoverageTracker::computeCoverage(unsigned Used, - unsigned Total) const { - assert(Used <= Total && - "number of used records cannot exceed the total number of records"); - return Total > 0 ? Used * 100 / Total : 100; +template <> +inline const BasicBlock * +SampleProfileLoaderImpl::getEntryBB(const Function *F) { + return &F->getEntryBlock(); } -/// Clear all the per-function data used to load samples and propagate weights. -void SampleProfileLoader::clearFunctionData() { - BlockWeights.clear(); - EdgeWeights.clear(); - VisitedBlocks.clear(); - VisitedEdges.clear(); - EquivalenceClass.clear(); - DT = nullptr; - PDT = nullptr; - LI = nullptr; - Predecessors.clear(); - Successors.clear(); - CoverageTracker.clear(); +// Ignore all intrinsics, phinodes and branch instructions. +// Branch and phinodes instruction usually contains debug info from sources +// outside of the residing basic block, thus we ignore them during annotation. +template <> +inline bool +SampleProfileLoaderImpl::shouldIgnoreInst(const Instruction &Inst) { + return (isa(Inst) || isa(Inst) || + isa(Inst)); } -#ifndef NDEBUG -/// Print the weight of edge \p E on stream \p OS. -/// -/// \param OS Stream to emit the output to. -/// \param E Edge to print. -void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) { - OS << "weight[" << E.first->getName() << "->" << E.second->getName() - << "]: " << EdgeWeights[E] << "\n"; -} +template <> +const FunctionSamples *SampleProfileLoaderImpl::findFunctionSamples( + const Instruction &Inst) const { + if (FunctionSamples::ProfileIsProbeBased) { + Optional Probe = extractProbe(Inst); + if (!Probe) + return nullptr; + } -/// Print the equivalence class of block \p BB on stream \p OS. -/// -/// \param OS Stream to emit the output to. -/// \param BB Block to print. -void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS, - const BasicBlock *BB) { - const BasicBlock *Equiv = EquivalenceClass[BB]; - OS << "equivalence[" << BB->getName() - << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n"; -} + const DILocation *DIL = Inst.getDebugLoc(); + if (!DIL) + return Samples; -/// Print the weight of block \p BB on stream \p OS. -/// -/// \param OS Stream to emit the output to. -/// \param BB Block to print. -void SampleProfileLoader::printBlockWeight(raw_ostream &OS, - const BasicBlock *BB) const { - const auto &I = BlockWeights.find(BB); - uint64_t W = (I == BlockWeights.end() ? 0 : I->second); - OS << "weight[" << BB->getName() << "]: " << W << "\n"; + auto it = DILocation2SampleMap.try_emplace(DIL, nullptr); + if (it.second) { + if (ProfileIsCS) + it.first->second = ContextTracker->getContextSamplesFor(DIL); + else + it.first->second = + Samples->findFunctionSamples(DIL, Reader->getRemapper()); + } + return it.first->second; } -#endif -/// Get the weight for an instruction. +// Get the FunctionSamples for a call instruction. /// -/// The "weight" of an instruction \p Inst is the number of samples -/// collected on that instruction at runtime. To retrieve it, we -/// need to compute the line number of \p Inst relative to the start of its -/// function. We use HeaderLineno to compute the offset. We then -/// look up the samples collected for \p Inst using BodySamples. +/// The FunctionSamples of a call/invoke instruction \p Inst is the inlined +/// instance in which that call instruction is calling to. It contains +/// all samples that resides in the inlined instance. We first find the +/// inlined instance in which the call instruction is from, then we +/// traverse its children to find the callsite with the matching +/// location. /// -/// \param Inst Instruction to query. +/// \param Inst Call/Invoke instruction to query. /// -/// \returns the weight of \p Inst. -ErrorOr SampleProfileLoader::getInstWeight(const Instruction &Inst) { - if (FunctionSamples::ProfileIsProbeBased) - return getProbeWeight(Inst); +/// \returns The FunctionSamples pointer to the inlined instance. +template <> +const FunctionSamples * +SampleProfileLoaderImpl::findCalleeFunctionSamples( + const CallBase &Inst) const { + const DILocation *DIL = Inst.getDebugLoc(); + if (!DIL) { + return nullptr; + } - const DebugLoc &DLoc = Inst.getDebugLoc(); - if (!DLoc) - return std::error_code(); + StringRef CalleeName; + if (Function *Callee = Inst.getCalledFunction()) + CalleeName = FunctionSamples::getCanonicalFnName(*Callee); + + if (ProfileIsCS) + return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName); const FunctionSamples *FS = findFunctionSamples(Inst); - if (!FS) - return std::error_code(); + if (FS == nullptr) + return nullptr; - // Ignore all intrinsics, phinodes and branch instructions. - // Branch and phinodes instruction usually contains debug info from sources outside of - // the residing basic block, thus we ignore them during annotation. - if (isa(Inst) || isa(Inst) || isa(Inst)) - return std::error_code(); + return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL), + CalleeName, Reader->getRemapper()); +} - // If a direct call/invoke instruction is inlined in profile - // (findCalleeFunctionSamples returns non-empty result), but not inlined here, - // it means that the inlined callsite has no sample, thus the call - // instruction should have 0 count. +// If a direct call/invoke instruction is inlined in profile +// (findCalleeFunctionSamples returns non-empty result), but not inlined here, +// it means that the inlined callsite has no sample, thus the call +// instruction should have 0 count. +template <> +inline bool SampleProfileLoaderImpl::zeroWeightInlinedCallee( + const Instruction &Inst) { if (!ProfileIsCS) if (const auto *CB = dyn_cast(&Inst)) if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB)) - return 0; - - const DILocation *DIL = DLoc; - uint32_t LineOffset = FunctionSamples::getOffset(DIL); - uint32_t Discriminator = DIL->getBaseDiscriminator(); - ErrorOr R = FS->findSamplesAt(LineOffset, Discriminator); - if (R) { - bool FirstMark = - CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get()); - if (FirstMark) { - ORE->emit([&]() { - OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst); - Remark << "Applied " << ore::NV("NumSamples", *R); - Remark << " samples from profile (offset: "; - Remark << ore::NV("LineOffset", LineOffset); - if (Discriminator) { - Remark << "."; - Remark << ore::NV("Discriminator", Discriminator); - } - Remark << ")"; - return Remark; - }); - } - LLVM_DEBUG(dbgs() << " " << DLoc.getLine() << "." - << DIL->getBaseDiscriminator() << ":" << Inst - << " (line offset: " << LineOffset << "." - << DIL->getBaseDiscriminator() << " - weight: " << R.get() - << ")\n"); - } - return R; + return true; + return false; } -ErrorOr SampleProfileLoader::getProbeWeight(const Instruction &Inst) { +template <> +ErrorOr +SampleProfileLoaderImpl::getProbeWeight(const Instruction &Inst) { assert(FunctionSamples::ProfileIsProbeBased && "Profile is not pseudo probe based"); Optional Probe = extractProbe(Inst); @@ -828,88 +332,12 @@ return R; } -/// Compute the weight of a basic block. -/// -/// The weight of basic block \p BB is the maximum weight of all the -/// instructions in BB. -/// -/// \param BB The basic block to query. -/// -/// \returns the weight for \p BB. -ErrorOr SampleProfileLoader::getBlockWeight(const BasicBlock *BB) { - uint64_t Max = 0; - bool HasWeight = false; - for (auto &I : BB->getInstList()) { - const ErrorOr &R = getInstWeight(I); - if (R) { - Max = std::max(Max, R.get()); - HasWeight = true; - } - } - return HasWeight ? ErrorOr(Max) : std::error_code(); -} - -/// Compute and store the weights of every basic block. -/// -/// This populates the BlockWeights map by computing -/// the weights of every basic block in the CFG. -/// -/// \param F The function to query. -bool SampleProfileLoader::computeBlockWeights(Function &F) { - bool Changed = false; - LLVM_DEBUG(dbgs() << "Block weights\n"); - for (const auto &BB : F) { - ErrorOr Weight = getBlockWeight(&BB); - if (Weight) { - BlockWeights[&BB] = Weight.get(); - VisitedBlocks.insert(&BB); - Changed = true; - } - LLVM_DEBUG(printBlockWeight(dbgs(), &BB)); - } - - return Changed; -} - -/// Get the FunctionSamples for a call instruction. -/// -/// The FunctionSamples of a call/invoke instruction \p Inst is the inlined -/// instance in which that call instruction is calling to. It contains -/// all samples that resides in the inlined instance. We first find the -/// inlined instance in which the call instruction is from, then we -/// traverse its children to find the callsite with the matching -/// location. -/// -/// \param Inst Call/Invoke instruction to query. -/// -/// \returns The FunctionSamples pointer to the inlined instance. -const FunctionSamples * -SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const { - const DILocation *DIL = Inst.getDebugLoc(); - if (!DIL) { - return nullptr; - } - - StringRef CalleeName; - if (Function *Callee = Inst.getCalledFunction()) - CalleeName = FunctionSamples::getCanonicalFnName(*Callee); - - if (ProfileIsCS) - return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName); - - const FunctionSamples *FS = findFunctionSamples(Inst); - if (FS == nullptr) - return nullptr; - - return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL), - CalleeName, Reader->getRemapper()); -} - /// Returns a vector of FunctionSamples that are the indirect call targets /// of \p Inst. The vector is sorted by the total number of samples. Stores /// the total call count of the indirect call in \p Sum. +template <> std::vector -SampleProfileLoader::findIndirectCallFunctionSamples( +SampleProfileLoaderImpl::findIndirectCallFunctionSamples( const Instruction &Inst, uint64_t &Sum) const { const DILocation *DIL = Inst.getDebugLoc(); std::vector R; @@ -945,39 +373,8 @@ return R; } -/// Get the FunctionSamples for an instruction. -/// -/// The FunctionSamples of an instruction \p Inst is the inlined instance -/// in which that instruction is coming from. We traverse the inline stack -/// of that instruction, and match it with the tree nodes in the profile. -/// -/// \param Inst Instruction to query. -/// -/// \returns the FunctionSamples pointer to the inlined instance. -const FunctionSamples * -SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const { - if (FunctionSamples::ProfileIsProbeBased) { - Optional Probe = extractProbe(Inst); - if (!Probe) - return nullptr; - } - - const DILocation *DIL = Inst.getDebugLoc(); - if (!DIL) - return Samples; - - auto it = DILocation2SampleMap.try_emplace(DIL,nullptr); - if (it.second) { - if (ProfileIsCS) - it.first->second = ContextTracker->getContextSamplesFor(DIL); - else - it.first->second = - Samples->findFunctionSamples(DIL, Reader->getRemapper()); - } - return it.first->second; -} - -bool SampleProfileLoader::inlineCallInstruction(CallBase &CB) { +template <> +bool SampleProfileLoaderImpl::inlineCallInstruction(CallBase &CB) { if (ExternalInlineAdvisor) { auto Advice = ExternalInlineAdvisor->getAdvice(CB); if (!Advice->isInliningRecommended()) { @@ -1017,7 +414,9 @@ return false; } -bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) { +template <> +bool SampleProfileLoaderImpl::shouldInlineColdCallee( + CallBase &CallInst) { if (!ProfileSizeInline) return false; @@ -1037,9 +436,11 @@ return Cost.getCost() <= SampleColdCallSiteThreshold; } -void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates( - const SmallVectorImpl &Candidates, const Function &F, - bool Hot) { +template <> +void SampleProfileLoaderImpl:: + emitOptimizationRemarksForInlineCandidates( + const SmallVectorImpl &Candidates, const Function &F, + bool Hot) { for (auto I : Candidates) { Function *CalledFunction = I->getCalledFunction(); if (CalledFunction) { @@ -1066,7 +467,8 @@ /// inlined in the profiled binary. /// /// \returns True if there is any inline happened. -bool SampleProfileLoader::inlineHotFunctions( +template <> +bool SampleProfileLoaderImpl::inlineHotFunctions( Function &F, DenseSet &InlinedGUIDs) { DenseSet PromotedInsns; @@ -1096,7 +498,7 @@ AllCandidates.push_back(CB); if (FS->getEntrySamples() > 0 || ProfileIsCS) localNotInlinedCallSites.try_emplace(CB, FS); - if (callsiteIsHot(FS, PSI)) + if (callsiteIsHot(FS, PSI, ProfAccForSymsInList)) Hot = true; else if (shouldInlineColdCallee(*CB)) ColdCandidates.push_back(CB); @@ -1126,7 +528,7 @@ PSI->getOrCompHotCountThreshold()); continue; } - if (!callsiteIsHot(FS, PSI)) + if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList)) continue; const char *Reason = "Callee function not available"; @@ -1232,308 +634,9 @@ return Changed; } -/// Find equivalence classes for the given block. -/// -/// This finds all the blocks that are guaranteed to execute the same -/// number of times as \p BB1. To do this, it traverses all the -/// descendants of \p BB1 in the dominator or post-dominator tree. -/// -/// A block BB2 will be in the same equivalence class as \p BB1 if -/// the following holds: -/// -/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2 -/// is a descendant of \p BB1 in the dominator tree, then BB2 should -/// dominate BB1 in the post-dominator tree. -/// -/// 2- Both BB2 and \p BB1 must be in the same loop. -/// -/// For every block BB2 that meets those two requirements, we set BB2's -/// equivalence class to \p BB1. -/// -/// \param BB1 Block to check. -/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree. -/// \param DomTree Opposite dominator tree. If \p Descendants is filled -/// with blocks from \p BB1's dominator tree, then -/// this is the post-dominator tree, and vice versa. -template -void SampleProfileLoader::findEquivalencesFor( - BasicBlock *BB1, ArrayRef Descendants, - DominatorTreeBase *DomTree) { - const BasicBlock *EC = EquivalenceClass[BB1]; - uint64_t Weight = BlockWeights[EC]; - for (const auto *BB2 : Descendants) { - bool IsDomParent = DomTree->dominates(BB2, BB1); - bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2); - if (BB1 != BB2 && IsDomParent && IsInSameLoop) { - EquivalenceClass[BB2] = EC; - // If BB2 is visited, then the entire EC should be marked as visited. - if (VisitedBlocks.count(BB2)) { - VisitedBlocks.insert(EC); - } - - // If BB2 is heavier than BB1, make BB2 have the same weight - // as BB1. - // - // Note that we don't worry about the opposite situation here - // (when BB2 is lighter than BB1). We will deal with this - // during the propagation phase. Right now, we just want to - // make sure that BB1 has the largest weight of all the - // members of its equivalence set. - Weight = std::max(Weight, BlockWeights[BB2]); - } - } - if (EC == &EC->getParent()->getEntryBlock()) { - BlockWeights[EC] = Samples->getHeadSamples() + 1; - } else { - BlockWeights[EC] = Weight; - } -} - -/// Find equivalence classes. -/// -/// Since samples may be missing from blocks, we can fill in the gaps by setting -/// the weights of all the blocks in the same equivalence class to the same -/// weight. To compute the concept of equivalence, we use dominance and loop -/// information. Two blocks B1 and B2 are in the same equivalence class if B1 -/// dominates B2, B2 post-dominates B1 and both are in the same loop. -/// -/// \param F The function to query. -void SampleProfileLoader::findEquivalenceClasses(Function &F) { - SmallVector DominatedBBs; - LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n"); - // Find equivalence sets based on dominance and post-dominance information. - for (auto &BB : F) { - BasicBlock *BB1 = &BB; - - // Compute BB1's equivalence class once. - if (EquivalenceClass.count(BB1)) { - LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1)); - continue; - } - - // By default, blocks are in their own equivalence class. - EquivalenceClass[BB1] = BB1; - - // Traverse all the blocks dominated by BB1. We are looking for - // every basic block BB2 such that: - // - // 1- BB1 dominates BB2. - // 2- BB2 post-dominates BB1. - // 3- BB1 and BB2 are in the same loop nest. - // - // If all those conditions hold, it means that BB2 is executed - // as many times as BB1, so they are placed in the same equivalence - // class by making BB2's equivalence class be BB1. - DominatedBBs.clear(); - DT->getDescendants(BB1, DominatedBBs); - findEquivalencesFor(BB1, DominatedBBs, PDT.get()); - - LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1)); - } - - // Assign weights to equivalence classes. - // - // All the basic blocks in the same equivalence class will execute - // the same number of times. Since we know that the head block in - // each equivalence class has the largest weight, assign that weight - // to all the blocks in that equivalence class. - LLVM_DEBUG( - dbgs() << "\nAssign the same weight to all blocks in the same class\n"); - for (auto &BI : F) { - const BasicBlock *BB = &BI; - const BasicBlock *EquivBB = EquivalenceClass[BB]; - if (BB != EquivBB) - BlockWeights[BB] = BlockWeights[EquivBB]; - LLVM_DEBUG(printBlockWeight(dbgs(), BB)); - } -} - -/// Visit the given edge to decide if it has a valid weight. -/// -/// If \p E has not been visited before, we copy to \p UnknownEdge -/// and increment the count of unknown edges. -/// -/// \param E Edge to visit. -/// \param NumUnknownEdges Current number of unknown edges. -/// \param UnknownEdge Set if E has not been visited before. -/// -/// \returns E's weight, if known. Otherwise, return 0. -uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges, - Edge *UnknownEdge) { - if (!VisitedEdges.count(E)) { - (*NumUnknownEdges)++; - *UnknownEdge = E; - return 0; - } - - return EdgeWeights[E]; -} - -/// Propagate weights through incoming/outgoing edges. -/// -/// If the weight of a basic block is known, and there is only one edge -/// with an unknown weight, we can calculate the weight of that edge. -/// -/// Similarly, if all the edges have a known count, we can calculate the -/// count of the basic block, if needed. -/// -/// \param F Function to process. -/// \param UpdateBlockCount Whether we should update basic block counts that -/// has already been annotated. -/// -/// \returns True if new weights were assigned to edges or blocks. -bool SampleProfileLoader::propagateThroughEdges(Function &F, - bool UpdateBlockCount) { - bool Changed = false; - LLVM_DEBUG(dbgs() << "\nPropagation through edges\n"); - for (const auto &BI : F) { - const BasicBlock *BB = &BI; - const BasicBlock *EC = EquivalenceClass[BB]; - - // Visit all the predecessor and successor edges to determine - // which ones have a weight assigned already. Note that it doesn't - // matter that we only keep track of a single unknown edge. The - // only case we are interested in handling is when only a single - // edge is unknown (see setEdgeOrBlockWeight). - for (unsigned i = 0; i < 2; i++) { - uint64_t TotalWeight = 0; - unsigned NumUnknownEdges = 0, NumTotalEdges = 0; - Edge UnknownEdge, SelfReferentialEdge, SingleEdge; - - if (i == 0) { - // First, visit all predecessor edges. - NumTotalEdges = Predecessors[BB].size(); - for (auto *Pred : Predecessors[BB]) { - Edge E = std::make_pair(Pred, BB); - TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); - if (E.first == E.second) - SelfReferentialEdge = E; - } - if (NumTotalEdges == 1) { - SingleEdge = std::make_pair(Predecessors[BB][0], BB); - } - } else { - // On the second round, visit all successor edges. - NumTotalEdges = Successors[BB].size(); - for (auto *Succ : Successors[BB]) { - Edge E = std::make_pair(BB, Succ); - TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); - } - if (NumTotalEdges == 1) { - SingleEdge = std::make_pair(BB, Successors[BB][0]); - } - } - - // After visiting all the edges, there are three cases that we - // can handle immediately: - // - // - All the edge weights are known (i.e., NumUnknownEdges == 0). - // In this case, we simply check that the sum of all the edges - // is the same as BB's weight. If not, we change BB's weight - // to match. Additionally, if BB had not been visited before, - // we mark it visited. - // - // - Only one edge is unknown and BB has already been visited. - // In this case, we can compute the weight of the edge by - // subtracting the total block weight from all the known - // edge weights. If the edges weight more than BB, then the - // edge of the last remaining edge is set to zero. - // - // - There exists a self-referential edge and the weight of BB is - // known. In this case, this edge can be based on BB's weight. - // We add up all the other known edges and set the weight on - // the self-referential edge as we did in the previous case. - // - // In any other case, we must continue iterating. Eventually, - // all edges will get a weight, or iteration will stop when - // it reaches SampleProfileMaxPropagateIterations. - if (NumUnknownEdges <= 1) { - uint64_t &BBWeight = BlockWeights[EC]; - if (NumUnknownEdges == 0) { - if (!VisitedBlocks.count(EC)) { - // If we already know the weight of all edges, the weight of the - // basic block can be computed. It should be no larger than the sum - // of all edge weights. - if (TotalWeight > BBWeight) { - BBWeight = TotalWeight; - Changed = true; - LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName() - << " known. Set weight for block: "; - printBlockWeight(dbgs(), BB);); - } - } else if (NumTotalEdges == 1 && - EdgeWeights[SingleEdge] < BlockWeights[EC]) { - // If there is only one edge for the visited basic block, use the - // block weight to adjust edge weight if edge weight is smaller. - EdgeWeights[SingleEdge] = BlockWeights[EC]; - Changed = true; - } - } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) { - // If there is a single unknown edge and the block has been - // visited, then we can compute E's weight. - if (BBWeight >= TotalWeight) - EdgeWeights[UnknownEdge] = BBWeight - TotalWeight; - else - EdgeWeights[UnknownEdge] = 0; - const BasicBlock *OtherEC; - if (i == 0) - OtherEC = EquivalenceClass[UnknownEdge.first]; - else - OtherEC = EquivalenceClass[UnknownEdge.second]; - // Edge weights should never exceed the BB weights it connects. - if (VisitedBlocks.count(OtherEC) && - EdgeWeights[UnknownEdge] > BlockWeights[OtherEC]) - EdgeWeights[UnknownEdge] = BlockWeights[OtherEC]; - VisitedEdges.insert(UnknownEdge); - Changed = true; - LLVM_DEBUG(dbgs() << "Set weight for edge: "; - printEdgeWeight(dbgs(), UnknownEdge)); - } - } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) { - // If a block Weights 0, all its in/out edges should weight 0. - if (i == 0) { - for (auto *Pred : Predecessors[BB]) { - Edge E = std::make_pair(Pred, BB); - EdgeWeights[E] = 0; - VisitedEdges.insert(E); - } - } else { - for (auto *Succ : Successors[BB]) { - Edge E = std::make_pair(BB, Succ); - EdgeWeights[E] = 0; - VisitedEdges.insert(E); - } - } - } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) { - uint64_t &BBWeight = BlockWeights[BB]; - // We have a self-referential edge and the weight of BB is known. - if (BBWeight >= TotalWeight) - EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight; - else - EdgeWeights[SelfReferentialEdge] = 0; - VisitedEdges.insert(SelfReferentialEdge); - Changed = true; - LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: "; - printEdgeWeight(dbgs(), SelfReferentialEdge)); - } - if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) { - BlockWeights[EC] = TotalWeight; - VisitedBlocks.insert(EC); - Changed = true; - } - } - } - - return Changed; -} - -/// Build in/out edge lists for each basic block in the CFG. -/// -/// We are interested in unique edges. If a block B1 has multiple -/// edges to another block B2, we only add a single B1->B2 edge. -void SampleProfileLoader::buildEdges(Function &F) { - for (auto &BI : F) { - BasicBlock *B1 = &BI; +template <> void SampleProfileLoaderImpl::buildEdges(Function &F) { + for (auto &BI : F) { + BasicBlock *B1 = &BI; // Add predecessors for B1. SmallPtrSet Visited; @@ -1558,78 +661,30 @@ } /// Returns the sorted CallTargetMap \p M by count in descending order. -static SmallVector GetSortedValueDataFromCallTargets( - const SampleRecord::CallTargetMap & M) { +static SmallVector +GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) { SmallVector R; for (const auto &I : SampleRecord::SortCallTargets(M)) { - R.emplace_back(InstrProfValueData{FunctionSamples::getGUID(I.first), I.second}); + R.emplace_back( + InstrProfValueData{FunctionSamples::getGUID(I.first), I.second}); } return R; } -/// Propagate weights into edges -/// -/// The following rules are applied to every block BB in the CFG: -/// -/// - If BB has a single predecessor/successor, then the weight -/// of that edge is the weight of the block. -/// -/// - If all incoming or outgoing edges are known except one, and the -/// weight of the block is already known, the weight of the unknown -/// edge will be the weight of the block minus the sum of all the known -/// edges. If the sum of all the known edges is larger than BB's weight, -/// we set the unknown edge weight to zero. -/// -/// - If there is a self-referential edge, and the weight of the block is -/// known, the weight for that edge is set to the weight of the block -/// minus the weight of the other incoming edges to that block (if -/// known). -void SampleProfileLoader::propagateWeights(Function &F) { - bool Changed = true; - unsigned I = 0; - - // If BB weight is larger than its corresponding loop's header BB weight, - // use the BB weight to replace the loop header BB weight. - for (auto &BI : F) { - BasicBlock *BB = &BI; - Loop *L = LI->getLoopFor(BB); - if (!L) { - continue; - } - BasicBlock *Header = L->getHeader(); - if (Header && BlockWeights[BB] > BlockWeights[Header]) { - BlockWeights[Header] = BlockWeights[BB]; - } - } - - // Before propagation starts, build, for each block, a list of - // unique predecessors and successors. This is necessary to handle - // identical edges in multiway branches. Since we visit all blocks and all - // edges of the CFG, it is cleaner to build these lists once at the start - // of the pass. - buildEdges(F); - - // Propagate until we converge or we go past the iteration limit. - while (Changed && I++ < SampleProfileMaxPropagateIterations) { - Changed = propagateThroughEdges(F, false); - } +template <> +void SampleProfileLoaderImpl::computeDominanceAndLoopInfo( + Function &F) { + DT.reset(new DominatorTree); + DT->recalculate(F); - // The first propagation propagates BB counts from annotated BBs to unknown - // BBs. The 2nd propagation pass resets edges weights, and use all BB weights - // to propagate edge weights. - VisitedEdges.clear(); - Changed = true; - while (Changed && I++ < SampleProfileMaxPropagateIterations) { - Changed = propagateThroughEdges(F, false); - } + PDT.reset(new PostDominatorTree(F)); - // The 3rd propagation pass allows adjust annotated BB weights that are - // obviously wrong. - Changed = true; - while (Changed && I++ < SampleProfileMaxPropagateIterations) { - Changed = propagateThroughEdges(F, true); - } + LI.reset(new LoopInfo); + LI->analyze(*DT); +} +template <> +void SampleProfileLoaderImpl::generateMDProfMetadata(Function &F) { // Generate MD_prof metadata for every branch instruction using the // edge weights computed during propagation. LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n"); @@ -1713,8 +768,7 @@ // weights, the second pass does not need to set it. if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) { LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n"); - TI->setMetadata(LLVMContext::MD_prof, - MDB.createBranchWeights(Weights)); + TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); ORE->emit([&]() { return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst) << "most popular destination for conditional branches at " @@ -1726,93 +780,9 @@ } } -/// Get the line number for the function header. -/// -/// This looks up function \p F in the current compilation unit and -/// retrieves the line number where the function is defined. This is -/// line 0 for all the samples read from the profile file. Every line -/// number is relative to this line. -/// -/// \param F Function object to query. -/// -/// \returns the line number where \p F is defined. If it returns 0, -/// it means that there is no debug information available for \p F. -unsigned SampleProfileLoader::getFunctionLoc(Function &F) { - if (DISubprogram *S = F.getSubprogram()) - return S->getLine(); - - if (NoWarnSampleUnused) - return 0; - - // If the start of \p F is missing, emit a diagnostic to inform the user - // about the missed opportunity. - F.getContext().diagnose(DiagnosticInfoSampleProfile( - "No debug information found in function " + F.getName() + - ": Function profile not used", - DS_Warning)); - return 0; -} - -void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) { - DT.reset(new DominatorTree); - DT->recalculate(F); - - PDT.reset(new PostDominatorTree(F)); - - LI.reset(new LoopInfo); - LI->analyze(*DT); -} - -/// Generate branch weight metadata for all branches in \p F. -/// -/// Branch weights are computed out of instruction samples using a -/// propagation heuristic. Propagation proceeds in 3 phases: -/// -/// 1- Assignment of block weights. All the basic blocks in the function -/// are initial assigned the same weight as their most frequently -/// executed instruction. -/// -/// 2- Creation of equivalence classes. Since samples may be missing from -/// blocks, we can fill in the gaps by setting the weights of all the -/// blocks in the same equivalence class to the same weight. To compute -/// the concept of equivalence, we use dominance and loop information. -/// Two blocks B1 and B2 are in the same equivalence class if B1 -/// dominates B2, B2 post-dominates B1 and both are in the same loop. -/// -/// 3- Propagation of block weights into edges. This uses a simple -/// propagation heuristic. The following rules are applied to every -/// block BB in the CFG: -/// -/// - If BB has a single predecessor/successor, then the weight -/// of that edge is the weight of the block. -/// -/// - If all the edges are known except one, and the weight of the -/// block is already known, the weight of the unknown edge will -/// be the weight of the block minus the sum of all the known -/// edges. If the sum of all the known edges is larger than BB's weight, -/// we set the unknown edge weight to zero. -/// -/// - If there is a self-referential edge, and the weight of the block is -/// known, the weight for that edge is set to the weight of the block -/// minus the weight of the other incoming edges to that block (if -/// known). -/// -/// Since this propagation is not guaranteed to finalize for every CFG, we -/// only allow it to proceed for a limited number of iterations (controlled -/// by -sample-profile-max-propagate-iterations). -/// -/// FIXME: Try to replace this propagation heuristic with a scheme -/// that is guaranteed to finalize. A work-list approach similar to -/// the standard value propagation algorithm used by SSA-CCP might -/// work here. -/// -/// Once all the branch weights are computed, we emit the MD_prof -/// metadata on BB using the computed values for each of its branches. -/// -/// \param F The function to query. -/// -/// \returns true if \p F was modified. Returns false, otherwise. -bool SampleProfileLoader::emitAnnotations(Function &F) { +/// Inline hot funcitons, then compute and propagate branch weight. +template <> +bool SampleProfileLoaderImpl::emitAnnotations(Function &F) { bool Changed = false; if (FunctionSamples::ProfileIsProbeBased) { @@ -1835,107 +805,14 @@ DenseSet InlinedGUIDs; Changed |= inlineHotFunctions(F, InlinedGUIDs); - // Compute basic block weights. - Changed |= computeBlockWeights(F); + Changed |= computeAndPropagateWeights(F, InlinedGUIDs); - if (Changed) { - // Add an entry count to the function using the samples gathered at the - // function entry. - // Sets the GUIDs that are inlined in the profiled binary. This is used - // for ThinLink to make correct liveness analysis, and also make the IR - // match the profiled binary before annotation. - F.setEntryCount( - ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real), - &InlinedGUIDs); - - // Compute dominance and loop info needed for propagation. - computeDominanceAndLoopInfo(F); - - // Find equivalence classes. - findEquivalenceClasses(F); - - // Propagate weights to all edges. - propagateWeights(F); - } - - // If coverage checking was requested, compute it now. - if (SampleProfileRecordCoverage) { - unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI); - unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI); - unsigned Coverage = CoverageTracker.computeCoverage(Used, Total); - if (Coverage < SampleProfileRecordCoverage) { - F.getContext().diagnose(DiagnosticInfoSampleProfile( - F.getSubprogram()->getFilename(), getFunctionLoc(F), - Twine(Used) + " of " + Twine(Total) + " available profile records (" + - Twine(Coverage) + "%) were applied", - DS_Warning)); - } - } - - if (SampleProfileSampleCoverage) { - uint64_t Used = CoverageTracker.getTotalUsedSamples(); - uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI); - unsigned Coverage = CoverageTracker.computeCoverage(Used, Total); - if (Coverage < SampleProfileSampleCoverage) { - F.getContext().diagnose(DiagnosticInfoSampleProfile( - F.getSubprogram()->getFilename(), getFunctionLoc(F), - Twine(Used) + " of " + Twine(Total) + " available profile samples (" + - Twine(Coverage) + "%) were applied", - DS_Warning)); - } - } return Changed; } -char SampleProfileLoaderLegacyPass::ID = 0; - -INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile", - "Sample Profile loader", false, false) -INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) -INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) -INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) -INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) -INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile", - "Sample Profile loader", false, false) - -std::vector -SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) { - std::vector FunctionOrderList; - FunctionOrderList.reserve(M.size()); - - if (!ProfileTopDownLoad || CG == nullptr) { - if (ProfileMergeInlinee) { - // Disable ProfileMergeInlinee if profile is not loaded in top down order, - // because the profile for a function may be used for the profile - // annotation of its outline copy before the profile merging of its - // non-inlined inline instances, and that is not the way how - // ProfileMergeInlinee is supposed to work. - ProfileMergeInlinee = false; - } - - for (Function &F : M) - if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile")) - FunctionOrderList.push_back(&F); - return FunctionOrderList; - } - - assert(&CG->getModule() == &M); - scc_iterator CGI = scc_begin(CG); - while (!CGI.isAtEnd()) { - for (CallGraphNode *node : *CGI) { - auto F = node->getFunction(); - if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile")) - FunctionOrderList.push_back(F); - } - ++CGI; - } - - std::reverse(FunctionOrderList.begin(), FunctionOrderList.end()); - return FunctionOrderList; -} - -bool SampleProfileLoader::doInitialization(Module &M, - FunctionAnalysisManager *FAM) { +template <> +bool SampleProfileLoaderImpl::doInitialization( + Module &M, FunctionAnalysisManager *FAM) { auto &Ctx = M.getContext(); auto ReaderOrErr = @@ -1963,6 +840,7 @@ NamesInProfile.clear(); if (auto NameTable = Reader->getNameTable()) NamesInProfile.insert(NameTable->begin(), NameTable->end()); + CoverageTracker.setProfAccForSymsInList(true); } if (FAM && !ProfileInlineReplayFile.empty()) { @@ -1996,16 +874,119 @@ return true; } -ModulePass *llvm::createSampleProfileLoaderPass() { - return new SampleProfileLoaderLegacyPass(); +template <> +bool SampleProfileLoaderImpl::runOnFunction( + Function &F, ModuleAnalysisManager *AM) { + DILocation2SampleMap.clear(); + // By default the entry count is initialized to -1, which will be treated + // conservatively by getEntryCount as the same as unknown (None). This is + // to avoid newly added code to be treated as cold. If we have samples + // this will be overwritten in emitAnnotations. + uint64_t initialEntryCount = -1; + + ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL; + if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) { + // initialize all the function entry counts to 0. It means all the + // functions without profile will be regarded as cold. + initialEntryCount = 0; + // profile-sample-accurate is a user assertion which has a higher precedence + // than symbol list. When profile-sample-accurate is on, ignore symbol list. + ProfAccForSymsInList = false; + } + CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList); + + // PSL -- profile symbol list include all the symbols in sampled binary. + // If ProfileAccurateForSymsInList is enabled, PSL is used to treat + // old functions without samples being cold, without having to worry + // about new and hot functions being mistakenly treated as cold. + if (ProfAccForSymsInList) { + // Initialize the entry count to 0 for functions in the list. + if (PSL->contains(F.getName())) + initialEntryCount = 0; + + // Function in the symbol list but without sample will be regarded as + // cold. To minimize the potential negative performance impact it could + // have, we want to be a little conservative here saying if a function + // shows up in the profile, no matter as outline function, inline instance + // or call targets, treat the function as not being cold. This will handle + // the cases such as most callsites of a function are inlined in sampled + // binary but not inlined in current build (because of source code drift, + // imprecise debug information, or the callsites are all cold individually + // but not cold accumulatively...), so the outline function showing up as + // cold in sampled binary will actually not be cold after current build. + StringRef CanonName = FunctionSamples::getCanonicalFnName(F); + if (NamesInProfile.count(CanonName)) + initialEntryCount = -1; + } + + // Initialize entry count when the function has no existing entry + // count value. + if (!F.getEntryCount().hasValue()) + F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real)); + std::unique_ptr OwnedORE; + if (AM) { + auto &FAM = + AM->getResult(*F.getParent()) + .getManager(); + ORE = &FAM.getResult(F); + } else { + OwnedORE = std::make_unique(&F); + ORE = OwnedORE.get(); + } + + if (ProfileIsCS) + Samples = ContextTracker->getBaseSamplesFor(F); + else + Samples = Reader->getSamplesFor(F); + + if (Samples && !Samples->empty()) + return emitAnnotations(F); + return false; } -ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) { - return new SampleProfileLoaderLegacyPass(Name); +template <> +std::vector +SampleProfileLoaderImpl::buildFunctionOrder(Module &M, + CallGraph *CG) { + std::vector FunctionOrderList; + FunctionOrderList.reserve(M.size()); + + if (!ProfileTopDownLoad || CG == nullptr) { + if (ProfileMergeInlinee) { + // Disable ProfileMergeInlinee if profile is not loaded in top down order, + // because the profile for a function may be used for the profile + // annotation of its outline copy before the profile merging of its + // non-inlined inline instances, and that is not the way how + // ProfileMergeInlinee is supposed to work. + ProfileMergeInlinee = false; + } + + for (Function &F : M) + if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile")) + FunctionOrderList.push_back(&F); + return FunctionOrderList; + } + + assert(&CG->getModule() == &M); + scc_iterator CGI = scc_begin(CG); + while (!CGI.isAtEnd()) { + for (CallGraphNode *node : *CGI) { + auto F = node->getFunction(); + if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile")) + FunctionOrderList.push_back(F); + } + ++CGI; + } + + std::reverse(FunctionOrderList.begin(), FunctionOrderList.end()); + return FunctionOrderList; } -bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM, - ProfileSummaryInfo *_PSI, CallGraph *CG) { +template <> +bool SampleProfileLoaderImpl::runOnModule(Module &M, + ModuleAnalysisManager *AM, + ProfileSummaryInfo *_PSI, + CallGraph *CG) { GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap); PSI = _PSI; @@ -2064,80 +1045,82 @@ return retval; } -bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) { - ACT = &getAnalysis(); - TTIWP = &getAnalysis(); - TLIWP = &getAnalysis(); - ProfileSummaryInfo *PSI = - &getAnalysis().getPSI(); - return SampleLoader.runOnModule(M, nullptr, PSI, nullptr); -} +namespace { -bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) { - DILocation2SampleMap.clear(); - // By default the entry count is initialized to -1, which will be treated - // conservatively by getEntryCount as the same as unknown (None). This is - // to avoid newly added code to be treated as cold. If we have samples - // this will be overwritten in emitAnnotations. - uint64_t initialEntryCount = -1; +class SampleProfileLoaderLegacyPass : public ModulePass { +public: + // Class identification, replacement for typeinfo + static char ID; - ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL; - if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) { - // initialize all the function entry counts to 0. It means all the - // functions without profile will be regarded as cold. - initialEntryCount = 0; - // profile-sample-accurate is a user assertion which has a higher precedence - // than symbol list. When profile-sample-accurate is on, ignore symbol list. - ProfAccForSymsInList = false; + SampleProfileLoaderLegacyPass( + StringRef Name = SampleProfileFile, + ThinOrFullLTOPhase LTOPhase = ThinOrFullLTOPhase::None) + : ModulePass(ID), SampleLoader( + Name, SampleProfileRemappingFile, LTOPhase, + [&](Function &F) -> AssumptionCache & { + return ACT->getAssumptionCache(F); + }, + [&](Function &F) -> TargetTransformInfo & { + return TTIWP->getTTI(F); + }, + [&](Function &F) -> TargetLibraryInfo & { + return TLIWP->getTLI(F); + }) { + initializeSampleProfileLoaderLegacyPassPass( + *PassRegistry::getPassRegistry()); } - // PSL -- profile symbol list include all the symbols in sampled binary. - // If ProfileAccurateForSymsInList is enabled, PSL is used to treat - // old functions without samples being cold, without having to worry - // about new and hot functions being mistakenly treated as cold. - if (ProfAccForSymsInList) { - // Initialize the entry count to 0 for functions in the list. - if (PSL->contains(F.getName())) - initialEntryCount = 0; + void dump() { SampleLoader.dump(); } - // Function in the symbol list but without sample will be regarded as - // cold. To minimize the potential negative performance impact it could - // have, we want to be a little conservative here saying if a function - // shows up in the profile, no matter as outline function, inline instance - // or call targets, treat the function as not being cold. This will handle - // the cases such as most callsites of a function are inlined in sampled - // binary but not inlined in current build (because of source code drift, - // imprecise debug information, or the callsites are all cold individually - // but not cold accumulatively...), so the outline function showing up as - // cold in sampled binary will actually not be cold after current build. - StringRef CanonName = FunctionSamples::getCanonicalFnName(F); - if (NamesInProfile.count(CanonName)) - initialEntryCount = -1; + bool doInitialization(Module &M) override { + return SampleLoader.doInitialization(M); } - // Initialize entry count when the function has no existing entry - // count value. - if (!F.getEntryCount().hasValue()) - F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real)); - std::unique_ptr OwnedORE; - if (AM) { - auto &FAM = - AM->getResult(*F.getParent()) - .getManager(); - ORE = &FAM.getResult(F); - } else { - OwnedORE = std::make_unique(&F); - ORE = OwnedORE.get(); + StringRef getPassName() const override { return "Sample profile pass"; } + bool runOnModule(Module &M) override; + + void getAnalysisUsage(AnalysisUsage &AU) const override { + AU.addRequired(); + AU.addRequired(); + AU.addRequired(); + AU.addRequired(); } - if (ProfileIsCS) - Samples = ContextTracker->getBaseSamplesFor(F); - else - Samples = Reader->getSamplesFor(F); +private: + SampleProfileLoaderImpl SampleLoader; + AssumptionCacheTracker *ACT = nullptr; + TargetTransformInfoWrapperPass *TTIWP = nullptr; + TargetLibraryInfoWrapperPass *TLIWP = nullptr; +}; - if (Samples && !Samples->empty()) - return emitAnnotations(F); - return false; +} // end anonymous namespace + +char SampleProfileLoaderLegacyPass::ID = 0; + +INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile", + "Sample Profile loader", false, false) +INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) +INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) +INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) +INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) +INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile", + "Sample Profile loader", false, false) + +ModulePass *llvm::createSampleProfileLoaderPass() { + return new SampleProfileLoaderLegacyPass(); +} + +ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) { + return new SampleProfileLoaderLegacyPass(Name); +} + +bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) { + ACT = &getAnalysis(); + TTIWP = &getAnalysis(); + TLIWP = &getAnalysis(); + ProfileSummaryInfo *PSI = + &getAnalysis().getPSI(); + return SampleLoader.runOnModule(M, nullptr, PSI, nullptr); } PreservedAnalyses SampleProfileLoaderPass::run(Module &M, @@ -2155,7 +1138,7 @@ return FAM.getResult(F); }; - SampleProfileLoader SampleLoader( + SampleProfileLoaderImpl SampleLoader( ProfileFileName.empty() ? SampleProfileFile : ProfileFileName, ProfileRemappingFileName.empty() ? SampleProfileRemappingFile : ProfileRemappingFileName,