Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:44

0001 ////===- SampleProfileLoadBaseImpl.h - Profile loader base impl --*- C++-*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 /// \file
0010 /// This file provides the interface for the sampled PGO profile loader base
0011 /// implementation.
0012 //
0013 //===----------------------------------------------------------------------===//
0014 
0015 #ifndef LLVM_TRANSFORMS_UTILS_SAMPLEPROFILELOADERBASEIMPL_H
0016 #define LLVM_TRANSFORMS_UTILS_SAMPLEPROFILELOADERBASEIMPL_H
0017 
0018 #include "llvm/ADT/ArrayRef.h"
0019 #include "llvm/ADT/DenseMap.h"
0020 #include "llvm/ADT/DenseSet.h"
0021 #include "llvm/ADT/IntrusiveRefCntPtr.h"
0022 #include "llvm/ADT/SmallPtrSet.h"
0023 #include "llvm/ADT/SmallSet.h"
0024 #include "llvm/ADT/SmallVector.h"
0025 #include "llvm/Analysis/LazyCallGraph.h"
0026 #include "llvm/Analysis/LoopInfo.h"
0027 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
0028 #include "llvm/Analysis/PostDominators.h"
0029 #include "llvm/IR/BasicBlock.h"
0030 #include "llvm/IR/CFG.h"
0031 #include "llvm/IR/DebugInfoMetadata.h"
0032 #include "llvm/IR/DebugLoc.h"
0033 #include "llvm/IR/Dominators.h"
0034 #include "llvm/IR/Function.h"
0035 #include "llvm/IR/Instruction.h"
0036 #include "llvm/IR/Instructions.h"
0037 #include "llvm/IR/Module.h"
0038 #include "llvm/IR/PseudoProbe.h"
0039 #include "llvm/ProfileData/SampleProf.h"
0040 #include "llvm/ProfileData/SampleProfReader.h"
0041 #include "llvm/Support/CommandLine.h"
0042 #include "llvm/Support/GenericDomTree.h"
0043 #include "llvm/Support/raw_ostream.h"
0044 #include "llvm/Transforms/Utils/SampleProfileInference.h"
0045 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
0046 
0047 namespace llvm {
0048 using namespace sampleprof;
0049 using namespace sampleprofutil;
0050 using ProfileCount = Function::ProfileCount;
0051 
0052 namespace vfs {
0053 class FileSystem;
0054 } // namespace vfs
0055 
0056 #define DEBUG_TYPE "sample-profile-impl"
0057 
0058 namespace afdo_detail {
0059 
0060 template <typename BlockT> struct IRTraits;
0061 template <> struct IRTraits<BasicBlock> {
0062   using InstructionT = Instruction;
0063   using BasicBlockT = BasicBlock;
0064   using FunctionT = Function;
0065   using BlockFrequencyInfoT = BlockFrequencyInfo;
0066   using LoopT = Loop;
0067   using LoopInfoPtrT = std::unique_ptr<LoopInfo>;
0068   using DominatorTreePtrT = std::unique_ptr<DominatorTree>;
0069   using PostDominatorTreeT = PostDominatorTree;
0070   using PostDominatorTreePtrT = std::unique_ptr<PostDominatorTree>;
0071   using OptRemarkEmitterT = OptimizationRemarkEmitter;
0072   using OptRemarkAnalysisT = OptimizationRemarkAnalysis;
0073   using PredRangeT = pred_range;
0074   using SuccRangeT = succ_range;
0075   static Function &getFunction(Function &F) { return F; }
0076   static const BasicBlock *getEntryBB(const Function *F) {
0077     return &F->getEntryBlock();
0078   }
0079   static pred_range getPredecessors(BasicBlock *BB) { return predecessors(BB); }
0080   static succ_range getSuccessors(BasicBlock *BB) { return successors(BB); }
0081 };
0082 
0083 } // end namespace afdo_detail
0084 
0085 // This class serves sample counts correlation for SampleProfileLoader by
0086 // analyzing pseudo probes and their function descriptors injected by
0087 // SampleProfileProber.
0088 class PseudoProbeManager {
0089   DenseMap<uint64_t, PseudoProbeDescriptor> GUIDToProbeDescMap;
0090 
0091 public:
0092   PseudoProbeManager(const Module &M) {
0093     if (NamedMDNode *FuncInfo =
0094             M.getNamedMetadata(PseudoProbeDescMetadataName)) {
0095       for (const auto *Operand : FuncInfo->operands()) {
0096         const auto *MD = cast<MDNode>(Operand);
0097         auto GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0))
0098                         ->getZExtValue();
0099         auto Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1))
0100                         ->getZExtValue();
0101         GUIDToProbeDescMap.try_emplace(GUID, PseudoProbeDescriptor(GUID, Hash));
0102       }
0103     }
0104   }
0105 
0106   const PseudoProbeDescriptor *getDesc(uint64_t GUID) const {
0107     auto I = GUIDToProbeDescMap.find(GUID);
0108     return I == GUIDToProbeDescMap.end() ? nullptr : &I->second;
0109   }
0110 
0111   const PseudoProbeDescriptor *getDesc(StringRef FProfileName) const {
0112     return getDesc(Function::getGUID(FProfileName));
0113   }
0114 
0115   const PseudoProbeDescriptor *getDesc(const Function &F) const {
0116     return getDesc(Function::getGUID(FunctionSamples::getCanonicalFnName(F)));
0117   }
0118 
0119   bool profileIsHashMismatched(const PseudoProbeDescriptor &FuncDesc,
0120                                const FunctionSamples &Samples) const {
0121     return FuncDesc.getFunctionHash() != Samples.getFunctionHash();
0122   }
0123 
0124   bool moduleIsProbed(const Module &M) const {
0125     return M.getNamedMetadata(PseudoProbeDescMetadataName);
0126   }
0127 
0128   bool profileIsValid(const Function &F, const FunctionSamples &Samples) const {
0129     const auto *Desc = getDesc(F);
0130     bool IsAvailableExternallyLinkage =
0131         GlobalValue::isAvailableExternallyLinkage(F.getLinkage());
0132     // Always check the function attribute to determine checksum mismatch for
0133     // `available_externally` functions even if their desc are available. This
0134     // is because the desc is computed based on the original internal function
0135     // and it's substituted by the `available_externally` function during link
0136     // time. However, when unstable IR or ODR violation issue occurs, the
0137     // definitions of the same function across different translation units could
0138     // be different and result in different checksums. So we should use the
0139     // state from the new (available_externally) function, which is saved in its
0140     // attribute.
0141     // TODO: If the function's profile only exists as nested inlinee profile in
0142     // a different module, we don't have the attr mismatch state(unknown), we
0143     // need to fix it later.
0144     if (IsAvailableExternallyLinkage || !Desc)
0145       return !F.hasFnAttribute("profile-checksum-mismatch");
0146 
0147     return Desc && !profileIsHashMismatched(*Desc, Samples);
0148   }
0149 };
0150 
0151 
0152 
0153 extern cl::opt<bool> SampleProfileUseProfi;
0154 
0155 static inline bool skipProfileForFunction(const Function &F) {
0156   return F.isDeclaration() || !F.hasFnAttribute("use-sample-profile");
0157 }
0158 
0159 static inline void
0160 buildTopDownFuncOrder(LazyCallGraph &CG,
0161                       std::vector<Function *> &FunctionOrderList) {
0162   CG.buildRefSCCs();
0163   for (LazyCallGraph::RefSCC &RC : CG.postorder_ref_sccs()) {
0164     for (LazyCallGraph::SCC &C : RC) {
0165       for (LazyCallGraph::Node &N : C) {
0166         Function &F = N.getFunction();
0167         if (!skipProfileForFunction(F))
0168           FunctionOrderList.push_back(&F);
0169       }
0170     }
0171   }
0172   std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
0173 }
0174 
0175 template <typename FT> class SampleProfileLoaderBaseImpl {
0176 public:
0177   SampleProfileLoaderBaseImpl(std::string Name, std::string RemapName,
0178                               IntrusiveRefCntPtr<vfs::FileSystem> FS)
0179       : Filename(Name), RemappingFilename(RemapName), FS(std::move(FS)) {}
0180   void dump() { Reader->dump(); }
0181 
0182   using NodeRef = typename GraphTraits<FT *>::NodeRef;
0183   using BT = std::remove_pointer_t<NodeRef>;
0184   using InstructionT = typename afdo_detail::IRTraits<BT>::InstructionT;
0185   using BasicBlockT = typename afdo_detail::IRTraits<BT>::BasicBlockT;
0186   using BlockFrequencyInfoT =
0187       typename afdo_detail::IRTraits<BT>::BlockFrequencyInfoT;
0188   using FunctionT = typename afdo_detail::IRTraits<BT>::FunctionT;
0189   using LoopT = typename afdo_detail::IRTraits<BT>::LoopT;
0190   using LoopInfoPtrT = typename afdo_detail::IRTraits<BT>::LoopInfoPtrT;
0191   using DominatorTreePtrT =
0192       typename afdo_detail::IRTraits<BT>::DominatorTreePtrT;
0193   using PostDominatorTreePtrT =
0194       typename afdo_detail::IRTraits<BT>::PostDominatorTreePtrT;
0195   using PostDominatorTreeT =
0196       typename afdo_detail::IRTraits<BT>::PostDominatorTreeT;
0197   using OptRemarkEmitterT =
0198       typename afdo_detail::IRTraits<BT>::OptRemarkEmitterT;
0199   using OptRemarkAnalysisT =
0200       typename afdo_detail::IRTraits<BT>::OptRemarkAnalysisT;
0201   using PredRangeT = typename afdo_detail::IRTraits<BT>::PredRangeT;
0202   using SuccRangeT = typename afdo_detail::IRTraits<BT>::SuccRangeT;
0203 
0204   using BlockWeightMap = DenseMap<const BasicBlockT *, uint64_t>;
0205   using EquivalenceClassMap =
0206       DenseMap<const BasicBlockT *, const BasicBlockT *>;
0207   using Edge = std::pair<const BasicBlockT *, const BasicBlockT *>;
0208   using EdgeWeightMap = DenseMap<Edge, uint64_t>;
0209   using BlockEdgeMap =
0210       DenseMap<const BasicBlockT *, SmallVector<const BasicBlockT *, 8>>;
0211 
0212 protected:
0213   ~SampleProfileLoaderBaseImpl() = default;
0214   friend class SampleCoverageTracker;
0215 
0216   Function &getFunction(FunctionT &F) {
0217     return afdo_detail::IRTraits<BT>::getFunction(F);
0218   }
0219   const BasicBlockT *getEntryBB(const FunctionT *F) {
0220     return afdo_detail::IRTraits<BT>::getEntryBB(F);
0221   }
0222   PredRangeT getPredecessors(BasicBlockT *BB) {
0223     return afdo_detail::IRTraits<BT>::getPredecessors(BB);
0224   }
0225   SuccRangeT getSuccessors(BasicBlockT *BB) {
0226     return afdo_detail::IRTraits<BT>::getSuccessors(BB);
0227   }
0228 
0229   unsigned getFunctionLoc(FunctionT &Func);
0230   virtual ErrorOr<uint64_t> getInstWeight(const InstructionT &Inst);
0231   ErrorOr<uint64_t> getInstWeightImpl(const InstructionT &Inst);
0232   virtual ErrorOr<uint64_t> getProbeWeight(const InstructionT &Inst);
0233   ErrorOr<uint64_t> getBlockWeight(const BasicBlockT *BB);
0234   mutable DenseMap<const DILocation *, const FunctionSamples *>
0235       DILocation2SampleMap;
0236   virtual const FunctionSamples *
0237   findFunctionSamples(const InstructionT &I) const;
0238   void printEdgeWeight(raw_ostream &OS, Edge E);
0239   void printBlockWeight(raw_ostream &OS, const BasicBlockT *BB) const;
0240   void printBlockEquivalence(raw_ostream &OS, const BasicBlockT *BB);
0241   bool computeBlockWeights(FunctionT &F);
0242   void findEquivalenceClasses(FunctionT &F);
0243   void findEquivalencesFor(BasicBlockT *BB1,
0244                            ArrayRef<BasicBlockT *> Descendants,
0245                            PostDominatorTreeT *DomTree);
0246   void propagateWeights(FunctionT &F);
0247   void applyProfi(FunctionT &F, BlockEdgeMap &Successors,
0248                   BlockWeightMap &SampleBlockWeights,
0249                   BlockWeightMap &BlockWeights, EdgeWeightMap &EdgeWeights);
0250   uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
0251   void buildEdges(FunctionT &F);
0252   bool propagateThroughEdges(FunctionT &F, bool UpdateBlockCount);
0253   void clearFunctionData(bool ResetDT = true);
0254   void computeDominanceAndLoopInfo(FunctionT &F);
0255   bool
0256   computeAndPropagateWeights(FunctionT &F,
0257                              const DenseSet<GlobalValue::GUID> &InlinedGUIDs);
0258   void initWeightPropagation(FunctionT &F,
0259                              const DenseSet<GlobalValue::GUID> &InlinedGUIDs);
0260   void
0261   finalizeWeightPropagation(FunctionT &F,
0262                             const DenseSet<GlobalValue::GUID> &InlinedGUIDs);
0263   void emitCoverageRemarks(FunctionT &F);
0264 
0265   /// Map basic blocks to their computed weights.
0266   ///
0267   /// The weight of a basic block is defined to be the maximum
0268   /// of all the instruction weights in that block.
0269   BlockWeightMap BlockWeights;
0270 
0271   /// Map edges to their computed weights.
0272   ///
0273   /// Edge weights are computed by propagating basic block weights in
0274   /// SampleProfile::propagateWeights.
0275   EdgeWeightMap EdgeWeights;
0276 
0277   /// Set of visited blocks during propagation.
0278   SmallPtrSet<const BasicBlockT *, 32> VisitedBlocks;
0279 
0280   /// Set of visited edges during propagation.
0281   SmallSet<Edge, 32> VisitedEdges;
0282 
0283   /// Equivalence classes for block weights.
0284   ///
0285   /// Two blocks BB1 and BB2 are in the same equivalence class if they
0286   /// dominate and post-dominate each other, and they are in the same loop
0287   /// nest. When this happens, the two blocks are guaranteed to execute
0288   /// the same number of times.
0289   EquivalenceClassMap EquivalenceClass;
0290 
0291   /// Dominance, post-dominance and loop information.
0292   DominatorTreePtrT DT;
0293   PostDominatorTreePtrT PDT;
0294   LoopInfoPtrT LI;
0295 
0296   /// Predecessors for each basic block in the CFG.
0297   BlockEdgeMap Predecessors;
0298 
0299   /// Successors for each basic block in the CFG.
0300   BlockEdgeMap Successors;
0301 
0302   /// Profile coverage tracker.
0303   SampleCoverageTracker CoverageTracker;
0304 
0305   /// Profile reader object.
0306   std::unique_ptr<SampleProfileReader> Reader;
0307 
0308   /// Synthetic samples created by duplicating the samples of inlined functions
0309   /// from the original profile as if they were top level sample profiles.
0310   /// Use std::map because insertion may happen while its content is referenced.
0311   std::map<SampleContext, FunctionSamples> OutlineFunctionSamples;
0312 
0313   // A pseudo probe helper to correlate the imported sample counts.
0314   std::unique_ptr<PseudoProbeManager> ProbeManager;
0315 
0316   /// Samples collected for the body of this function.
0317   FunctionSamples *Samples = nullptr;
0318 
0319   /// Name of the profile file to load.
0320   std::string Filename;
0321 
0322   /// Name of the profile remapping file to load.
0323   std::string RemappingFilename;
0324 
0325   /// VirtualFileSystem to load profile files from.
0326   IntrusiveRefCntPtr<vfs::FileSystem> FS;
0327 
0328   /// Profile Summary Info computed from sample profile.
0329   ProfileSummaryInfo *PSI = nullptr;
0330 
0331   /// Optimization Remark Emitter used to emit diagnostic remarks.
0332   OptRemarkEmitterT *ORE = nullptr;
0333 };
0334 
0335 /// Clear all the per-function data used to load samples and propagate weights.
0336 template <typename BT>
0337 void SampleProfileLoaderBaseImpl<BT>::clearFunctionData(bool ResetDT) {
0338   BlockWeights.clear();
0339   EdgeWeights.clear();
0340   VisitedBlocks.clear();
0341   VisitedEdges.clear();
0342   EquivalenceClass.clear();
0343   if (ResetDT) {
0344     DT = nullptr;
0345     PDT = nullptr;
0346     LI = nullptr;
0347   }
0348   Predecessors.clear();
0349   Successors.clear();
0350   CoverageTracker.clear();
0351 }
0352 
0353 #ifndef NDEBUG
0354 /// Print the weight of edge \p E on stream \p OS.
0355 ///
0356 /// \param OS  Stream to emit the output to.
0357 /// \param E  Edge to print.
0358 template <typename BT>
0359 void SampleProfileLoaderBaseImpl<BT>::printEdgeWeight(raw_ostream &OS, Edge E) {
0360   OS << "weight[" << E.first->getName() << "->" << E.second->getName()
0361      << "]: " << EdgeWeights[E] << "\n";
0362 }
0363 
0364 /// Print the equivalence class of block \p BB on stream \p OS.
0365 ///
0366 /// \param OS  Stream to emit the output to.
0367 /// \param BB  Block to print.
0368 template <typename BT>
0369 void SampleProfileLoaderBaseImpl<BT>::printBlockEquivalence(
0370     raw_ostream &OS, const BasicBlockT *BB) {
0371   const BasicBlockT *Equiv = EquivalenceClass[BB];
0372   OS << "equivalence[" << BB->getName()
0373      << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
0374 }
0375 
0376 /// Print the weight of block \p BB on stream \p OS.
0377 ///
0378 /// \param OS  Stream to emit the output to.
0379 /// \param BB  Block to print.
0380 template <typename BT>
0381 void SampleProfileLoaderBaseImpl<BT>::printBlockWeight(
0382     raw_ostream &OS, const BasicBlockT *BB) const {
0383   const auto &I = BlockWeights.find(BB);
0384   uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
0385   OS << "weight[" << BB->getName() << "]: " << W << "\n";
0386 }
0387 #endif
0388 
0389 /// Get the weight for an instruction.
0390 ///
0391 /// The "weight" of an instruction \p Inst is the number of samples
0392 /// collected on that instruction at runtime. To retrieve it, we
0393 /// need to compute the line number of \p Inst relative to the start of its
0394 /// function. We use HeaderLineno to compute the offset. We then
0395 /// look up the samples collected for \p Inst using BodySamples.
0396 ///
0397 /// \param Inst Instruction to query.
0398 ///
0399 /// \returns the weight of \p Inst.
0400 template <typename BT>
0401 ErrorOr<uint64_t>
0402 SampleProfileLoaderBaseImpl<BT>::getInstWeight(const InstructionT &Inst) {
0403   if (FunctionSamples::ProfileIsProbeBased)
0404     return getProbeWeight(Inst);
0405   return getInstWeightImpl(Inst);
0406 }
0407 
0408 template <typename BT>
0409 ErrorOr<uint64_t>
0410 SampleProfileLoaderBaseImpl<BT>::getInstWeightImpl(const InstructionT &Inst) {
0411   const FunctionSamples *FS = findFunctionSamples(Inst);
0412   if (!FS)
0413     return std::error_code();
0414 
0415   const DebugLoc &DLoc = Inst.getDebugLoc();
0416   if (!DLoc)
0417     return std::error_code();
0418 
0419   const DILocation *DIL = DLoc;
0420   uint32_t LineOffset = FunctionSamples::getOffset(DIL);
0421   uint32_t Discriminator;
0422   if (EnableFSDiscriminator)
0423     Discriminator = DIL->getDiscriminator();
0424   else
0425     Discriminator = DIL->getBaseDiscriminator();
0426 
0427   ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
0428   if (R) {
0429     bool FirstMark =
0430         CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
0431     if (FirstMark) {
0432       ORE->emit([&]() {
0433         OptRemarkAnalysisT Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
0434         Remark << "Applied " << ore::NV("NumSamples", *R);
0435         Remark << " samples from profile (offset: ";
0436         Remark << ore::NV("LineOffset", LineOffset);
0437         if (Discriminator) {
0438           Remark << ".";
0439           Remark << ore::NV("Discriminator", Discriminator);
0440         }
0441         Remark << ")";
0442         return Remark;
0443       });
0444     }
0445     LLVM_DEBUG(dbgs() << "    " << DLoc.getLine() << "." << Discriminator << ":"
0446                       << Inst << " (line offset: " << LineOffset << "."
0447                       << Discriminator << " - weight: " << R.get() << ")\n");
0448   }
0449   return R;
0450 }
0451 
0452 template <typename BT>
0453 ErrorOr<uint64_t>
0454 SampleProfileLoaderBaseImpl<BT>::getProbeWeight(const InstructionT &Inst) {
0455   assert(FunctionSamples::ProfileIsProbeBased &&
0456          "Profile is not pseudo probe based");
0457   std::optional<PseudoProbe> Probe = extractProbe(Inst);
0458   // Ignore the non-probe instruction. If none of the instruction in the BB is
0459   // probe, we choose to infer the BB's weight.
0460   if (!Probe)
0461     return std::error_code();
0462 
0463   const FunctionSamples *FS = findFunctionSamples(Inst);
0464   if (!FS) {
0465     // If we can't find the function samples for a probe, it could be due to the
0466     // probe is later optimized away or the inlining context is mismatced. We
0467     // treat it as unknown, leaving it to profile inference instead of forcing a
0468     // zero count.
0469     return std::error_code();
0470   }
0471 
0472   auto R = FS->findSamplesAt(Probe->Id, Probe->Discriminator);
0473   if (R) {
0474     uint64_t Samples = R.get() * Probe->Factor;
0475     bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
0476     if (FirstMark) {
0477       ORE->emit([&]() {
0478         OptRemarkAnalysisT Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
0479         Remark << "Applied " << ore::NV("NumSamples", Samples);
0480         Remark << " samples from profile (ProbeId=";
0481         Remark << ore::NV("ProbeId", Probe->Id);
0482         if (Probe->Discriminator) {
0483           Remark << ".";
0484           Remark << ore::NV("Discriminator", Probe->Discriminator);
0485         }
0486         Remark << ", Factor=";
0487         Remark << ore::NV("Factor", Probe->Factor);
0488         Remark << ", OriginalSamples=";
0489         Remark << ore::NV("OriginalSamples", R.get());
0490         Remark << ")";
0491         return Remark;
0492       });
0493     }
0494     LLVM_DEBUG({dbgs() << "    " << Probe->Id;
0495       if (Probe->Discriminator)
0496         dbgs() << "." << Probe->Discriminator;
0497       dbgs() << ":" << Inst << " - weight: " << R.get()
0498              << " - factor: " << format("%0.2f", Probe->Factor) << ")\n";});
0499     return Samples;
0500   }
0501   return R;
0502 }
0503 
0504 /// Compute the weight of a basic block.
0505 ///
0506 /// The weight of basic block \p BB is the maximum weight of all the
0507 /// instructions in BB.
0508 ///
0509 /// \param BB The basic block to query.
0510 ///
0511 /// \returns the weight for \p BB.
0512 template <typename BT>
0513 ErrorOr<uint64_t>
0514 SampleProfileLoaderBaseImpl<BT>::getBlockWeight(const BasicBlockT *BB) {
0515   uint64_t Max = 0;
0516   bool HasWeight = false;
0517   for (auto &I : *BB) {
0518     const ErrorOr<uint64_t> &R = getInstWeight(I);
0519     if (R) {
0520       Max = std::max(Max, R.get());
0521       HasWeight = true;
0522     }
0523   }
0524   return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
0525 }
0526 
0527 /// Compute and store the weights of every basic block.
0528 ///
0529 /// This populates the BlockWeights map by computing
0530 /// the weights of every basic block in the CFG.
0531 ///
0532 /// \param F The function to query.
0533 template <typename BT>
0534 bool SampleProfileLoaderBaseImpl<BT>::computeBlockWeights(FunctionT &F) {
0535   bool Changed = false;
0536   LLVM_DEBUG(dbgs() << "Block weights\n");
0537   for (const auto &BB : F) {
0538     ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
0539     if (Weight) {
0540       BlockWeights[&BB] = Weight.get();
0541       VisitedBlocks.insert(&BB);
0542       Changed = true;
0543     }
0544     LLVM_DEBUG(printBlockWeight(dbgs(), &BB));
0545   }
0546 
0547   return Changed;
0548 }
0549 
0550 /// Get the FunctionSamples for an instruction.
0551 ///
0552 /// The FunctionSamples of an instruction \p Inst is the inlined instance
0553 /// in which that instruction is coming from. We traverse the inline stack
0554 /// of that instruction, and match it with the tree nodes in the profile.
0555 ///
0556 /// \param Inst Instruction to query.
0557 ///
0558 /// \returns the FunctionSamples pointer to the inlined instance.
0559 template <typename BT>
0560 const FunctionSamples *SampleProfileLoaderBaseImpl<BT>::findFunctionSamples(
0561     const InstructionT &Inst) const {
0562   const DILocation *DIL = Inst.getDebugLoc();
0563   if (!DIL)
0564     return Samples;
0565 
0566   auto it = DILocation2SampleMap.try_emplace(DIL, nullptr);
0567   if (it.second) {
0568     it.first->second = Samples->findFunctionSamples(DIL, Reader->getRemapper());
0569   }
0570   return it.first->second;
0571 }
0572 
0573 /// Find equivalence classes for the given block.
0574 ///
0575 /// This finds all the blocks that are guaranteed to execute the same
0576 /// number of times as \p BB1. To do this, it traverses all the
0577 /// descendants of \p BB1 in the dominator or post-dominator tree.
0578 ///
0579 /// A block BB2 will be in the same equivalence class as \p BB1 if
0580 /// the following holds:
0581 ///
0582 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
0583 ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
0584 ///    dominate BB1 in the post-dominator tree.
0585 ///
0586 /// 2- Both BB2 and \p BB1 must be in the same loop.
0587 ///
0588 /// For every block BB2 that meets those two requirements, we set BB2's
0589 /// equivalence class to \p BB1.
0590 ///
0591 /// \param BB1  Block to check.
0592 /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
0593 /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
0594 ///                 with blocks from \p BB1's dominator tree, then
0595 ///                 this is the post-dominator tree, and vice versa.
0596 template <typename BT>
0597 void SampleProfileLoaderBaseImpl<BT>::findEquivalencesFor(
0598     BasicBlockT *BB1, ArrayRef<BasicBlockT *> Descendants,
0599     PostDominatorTreeT *DomTree) {
0600   const BasicBlockT *EC = EquivalenceClass[BB1];
0601   uint64_t Weight = BlockWeights[EC];
0602   for (const auto *BB2 : Descendants) {
0603     bool IsDomParent = DomTree->dominates(BB2, BB1);
0604     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
0605     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
0606       EquivalenceClass[BB2] = EC;
0607       // If BB2 is visited, then the entire EC should be marked as visited.
0608       if (VisitedBlocks.count(BB2)) {
0609         VisitedBlocks.insert(EC);
0610       }
0611 
0612       // If BB2 is heavier than BB1, make BB2 have the same weight
0613       // as BB1.
0614       //
0615       // Note that we don't worry about the opposite situation here
0616       // (when BB2 is lighter than BB1). We will deal with this
0617       // during the propagation phase. Right now, we just want to
0618       // make sure that BB1 has the largest weight of all the
0619       // members of its equivalence set.
0620       Weight = std::max(Weight, BlockWeights[BB2]);
0621     }
0622   }
0623   const BasicBlockT *EntryBB = getEntryBB(EC->getParent());
0624   if (EC == EntryBB) {
0625     BlockWeights[EC] = Samples->getHeadSamples() + 1;
0626   } else {
0627     BlockWeights[EC] = Weight;
0628   }
0629 }
0630 
0631 /// Find equivalence classes.
0632 ///
0633 /// Since samples may be missing from blocks, we can fill in the gaps by setting
0634 /// the weights of all the blocks in the same equivalence class to the same
0635 /// weight. To compute the concept of equivalence, we use dominance and loop
0636 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
0637 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
0638 ///
0639 /// \param F The function to query.
0640 template <typename BT>
0641 void SampleProfileLoaderBaseImpl<BT>::findEquivalenceClasses(FunctionT &F) {
0642   SmallVector<BasicBlockT *, 8> DominatedBBs;
0643   LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n");
0644   // Find equivalence sets based on dominance and post-dominance information.
0645   for (auto &BB : F) {
0646     BasicBlockT *BB1 = &BB;
0647 
0648     // Compute BB1's equivalence class once.
0649     if (EquivalenceClass.count(BB1)) {
0650       LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
0651       continue;
0652     }
0653 
0654     // By default, blocks are in their own equivalence class.
0655     EquivalenceClass[BB1] = BB1;
0656 
0657     // Traverse all the blocks dominated by BB1. We are looking for
0658     // every basic block BB2 such that:
0659     //
0660     // 1- BB1 dominates BB2.
0661     // 2- BB2 post-dominates BB1.
0662     // 3- BB1 and BB2 are in the same loop nest.
0663     //
0664     // If all those conditions hold, it means that BB2 is executed
0665     // as many times as BB1, so they are placed in the same equivalence
0666     // class by making BB2's equivalence class be BB1.
0667     DominatedBBs.clear();
0668     DT->getDescendants(BB1, DominatedBBs);
0669     findEquivalencesFor(BB1, DominatedBBs, &*PDT);
0670 
0671     LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
0672   }
0673 
0674   // Assign weights to equivalence classes.
0675   //
0676   // All the basic blocks in the same equivalence class will execute
0677   // the same number of times. Since we know that the head block in
0678   // each equivalence class has the largest weight, assign that weight
0679   // to all the blocks in that equivalence class.
0680   LLVM_DEBUG(
0681       dbgs() << "\nAssign the same weight to all blocks in the same class\n");
0682   for (auto &BI : F) {
0683     const BasicBlockT *BB = &BI;
0684     const BasicBlockT *EquivBB = EquivalenceClass[BB];
0685     if (BB != EquivBB)
0686       BlockWeights[BB] = BlockWeights[EquivBB];
0687     LLVM_DEBUG(printBlockWeight(dbgs(), BB));
0688   }
0689 }
0690 
0691 /// Visit the given edge to decide if it has a valid weight.
0692 ///
0693 /// If \p E has not been visited before, we copy to \p UnknownEdge
0694 /// and increment the count of unknown edges.
0695 ///
0696 /// \param E  Edge to visit.
0697 /// \param NumUnknownEdges  Current number of unknown edges.
0698 /// \param UnknownEdge  Set if E has not been visited before.
0699 ///
0700 /// \returns E's weight, if known. Otherwise, return 0.
0701 template <typename BT>
0702 uint64_t SampleProfileLoaderBaseImpl<BT>::visitEdge(Edge E,
0703                                                     unsigned *NumUnknownEdges,
0704                                                     Edge *UnknownEdge) {
0705   if (!VisitedEdges.count(E)) {
0706     (*NumUnknownEdges)++;
0707     *UnknownEdge = E;
0708     return 0;
0709   }
0710 
0711   return EdgeWeights[E];
0712 }
0713 
0714 /// Propagate weights through incoming/outgoing edges.
0715 ///
0716 /// If the weight of a basic block is known, and there is only one edge
0717 /// with an unknown weight, we can calculate the weight of that edge.
0718 ///
0719 /// Similarly, if all the edges have a known count, we can calculate the
0720 /// count of the basic block, if needed.
0721 ///
0722 /// \param F  Function to process.
0723 /// \param UpdateBlockCount  Whether we should update basic block counts that
0724 ///                          has already been annotated.
0725 ///
0726 /// \returns  True if new weights were assigned to edges or blocks.
0727 template <typename BT>
0728 bool SampleProfileLoaderBaseImpl<BT>::propagateThroughEdges(
0729     FunctionT &F, bool UpdateBlockCount) {
0730   bool Changed = false;
0731   LLVM_DEBUG(dbgs() << "\nPropagation through edges\n");
0732   for (const auto &BI : F) {
0733     const BasicBlockT *BB = &BI;
0734     const BasicBlockT *EC = EquivalenceClass[BB];
0735 
0736     // Visit all the predecessor and successor edges to determine
0737     // which ones have a weight assigned already. Note that it doesn't
0738     // matter that we only keep track of a single unknown edge. The
0739     // only case we are interested in handling is when only a single
0740     // edge is unknown (see setEdgeOrBlockWeight).
0741     for (unsigned i = 0; i < 2; i++) {
0742       uint64_t TotalWeight = 0;
0743       unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
0744       Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
0745 
0746       if (i == 0) {
0747         // First, visit all predecessor edges.
0748         NumTotalEdges = Predecessors[BB].size();
0749         for (auto *Pred : Predecessors[BB]) {
0750           Edge E = std::make_pair(Pred, BB);
0751           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
0752           if (E.first == E.second)
0753             SelfReferentialEdge = E;
0754         }
0755         if (NumTotalEdges == 1) {
0756           SingleEdge = std::make_pair(Predecessors[BB][0], BB);
0757         }
0758       } else {
0759         // On the second round, visit all successor edges.
0760         NumTotalEdges = Successors[BB].size();
0761         for (auto *Succ : Successors[BB]) {
0762           Edge E = std::make_pair(BB, Succ);
0763           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
0764         }
0765         if (NumTotalEdges == 1) {
0766           SingleEdge = std::make_pair(BB, Successors[BB][0]);
0767         }
0768       }
0769 
0770       // After visiting all the edges, there are three cases that we
0771       // can handle immediately:
0772       //
0773       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
0774       //   In this case, we simply check that the sum of all the edges
0775       //   is the same as BB's weight. If not, we change BB's weight
0776       //   to match. Additionally, if BB had not been visited before,
0777       //   we mark it visited.
0778       //
0779       // - Only one edge is unknown and BB has already been visited.
0780       //   In this case, we can compute the weight of the edge by
0781       //   subtracting the total block weight from all the known
0782       //   edge weights. If the edges weight more than BB, then the
0783       //   edge of the last remaining edge is set to zero.
0784       //
0785       // - There exists a self-referential edge and the weight of BB is
0786       //   known. In this case, this edge can be based on BB's weight.
0787       //   We add up all the other known edges and set the weight on
0788       //   the self-referential edge as we did in the previous case.
0789       //
0790       // In any other case, we must continue iterating. Eventually,
0791       // all edges will get a weight, or iteration will stop when
0792       // it reaches SampleProfileMaxPropagateIterations.
0793       if (NumUnknownEdges <= 1) {
0794         uint64_t &BBWeight = BlockWeights[EC];
0795         if (NumUnknownEdges == 0) {
0796           if (!VisitedBlocks.count(EC)) {
0797             // If we already know the weight of all edges, the weight of the
0798             // basic block can be computed. It should be no larger than the sum
0799             // of all edge weights.
0800             if (TotalWeight > BBWeight) {
0801               BBWeight = TotalWeight;
0802               Changed = true;
0803               LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName()
0804                                 << " known. Set weight for block: ";
0805                          printBlockWeight(dbgs(), BB););
0806             }
0807           } else if (NumTotalEdges == 1 &&
0808                      EdgeWeights[SingleEdge] < BlockWeights[EC]) {
0809             // If there is only one edge for the visited basic block, use the
0810             // block weight to adjust edge weight if edge weight is smaller.
0811             EdgeWeights[SingleEdge] = BlockWeights[EC];
0812             Changed = true;
0813           }
0814         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
0815           // If there is a single unknown edge and the block has been
0816           // visited, then we can compute E's weight.
0817           if (BBWeight >= TotalWeight)
0818             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
0819           else
0820             EdgeWeights[UnknownEdge] = 0;
0821           const BasicBlockT *OtherEC;
0822           if (i == 0)
0823             OtherEC = EquivalenceClass[UnknownEdge.first];
0824           else
0825             OtherEC = EquivalenceClass[UnknownEdge.second];
0826           // Edge weights should never exceed the BB weights it connects.
0827           if (VisitedBlocks.count(OtherEC) &&
0828               EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
0829             EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
0830           VisitedEdges.insert(UnknownEdge);
0831           Changed = true;
0832           LLVM_DEBUG(dbgs() << "Set weight for edge: ";
0833                      printEdgeWeight(dbgs(), UnknownEdge));
0834         }
0835       } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
0836         // If a block Weights 0, all its in/out edges should weight 0.
0837         if (i == 0) {
0838           for (auto *Pred : Predecessors[BB]) {
0839             Edge E = std::make_pair(Pred, BB);
0840             EdgeWeights[E] = 0;
0841             VisitedEdges.insert(E);
0842           }
0843         } else {
0844           for (auto *Succ : Successors[BB]) {
0845             Edge E = std::make_pair(BB, Succ);
0846             EdgeWeights[E] = 0;
0847             VisitedEdges.insert(E);
0848           }
0849         }
0850       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
0851         uint64_t &BBWeight = BlockWeights[BB];
0852         // We have a self-referential edge and the weight of BB is known.
0853         if (BBWeight >= TotalWeight)
0854           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
0855         else
0856           EdgeWeights[SelfReferentialEdge] = 0;
0857         VisitedEdges.insert(SelfReferentialEdge);
0858         Changed = true;
0859         LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: ";
0860                    printEdgeWeight(dbgs(), SelfReferentialEdge));
0861       }
0862       if (UpdateBlockCount && TotalWeight > 0 &&
0863           VisitedBlocks.insert(EC).second) {
0864         BlockWeights[EC] = TotalWeight;
0865         Changed = true;
0866       }
0867     }
0868   }
0869 
0870   return Changed;
0871 }
0872 
0873 /// Build in/out edge lists for each basic block in the CFG.
0874 ///
0875 /// We are interested in unique edges. If a block B1 has multiple
0876 /// edges to another block B2, we only add a single B1->B2 edge.
0877 template <typename BT>
0878 void SampleProfileLoaderBaseImpl<BT>::buildEdges(FunctionT &F) {
0879   for (auto &BI : F) {
0880     BasicBlockT *B1 = &BI;
0881 
0882     // Add predecessors for B1.
0883     SmallPtrSet<BasicBlockT *, 16> Visited;
0884     if (!Predecessors[B1].empty())
0885       llvm_unreachable("Found a stale predecessors list in a basic block.");
0886     for (auto *B2 : getPredecessors(B1))
0887       if (Visited.insert(B2).second)
0888         Predecessors[B1].push_back(B2);
0889 
0890     // Add successors for B1.
0891     Visited.clear();
0892     if (!Successors[B1].empty())
0893       llvm_unreachable("Found a stale successors list in a basic block.");
0894     for (auto *B2 : getSuccessors(B1))
0895       if (Visited.insert(B2).second)
0896         Successors[B1].push_back(B2);
0897   }
0898 }
0899 
0900 /// Propagate weights into edges
0901 ///
0902 /// The following rules are applied to every block BB in the CFG:
0903 ///
0904 /// - If BB has a single predecessor/successor, then the weight
0905 ///   of that edge is the weight of the block.
0906 ///
0907 /// - If all incoming or outgoing edges are known except one, and the
0908 ///   weight of the block is already known, the weight of the unknown
0909 ///   edge will be the weight of the block minus the sum of all the known
0910 ///   edges. If the sum of all the known edges is larger than BB's weight,
0911 ///   we set the unknown edge weight to zero.
0912 ///
0913 /// - If there is a self-referential edge, and the weight of the block is
0914 ///   known, the weight for that edge is set to the weight of the block
0915 ///   minus the weight of the other incoming edges to that block (if
0916 ///   known).
0917 template <typename BT>
0918 void SampleProfileLoaderBaseImpl<BT>::propagateWeights(FunctionT &F) {
0919   // Flow-based profile inference is only usable with BasicBlock instantiation
0920   // of SampleProfileLoaderBaseImpl.
0921   if (SampleProfileUseProfi) {
0922     // Prepare block sample counts for inference.
0923     BlockWeightMap SampleBlockWeights;
0924     for (const auto &BI : F) {
0925       ErrorOr<uint64_t> Weight = getBlockWeight(&BI);
0926       if (Weight)
0927         SampleBlockWeights[&BI] = Weight.get();
0928     }
0929     // Fill in BlockWeights and EdgeWeights using an inference algorithm.
0930     applyProfi(F, Successors, SampleBlockWeights, BlockWeights, EdgeWeights);
0931   } else {
0932     bool Changed = true;
0933     unsigned I = 0;
0934 
0935     // If BB weight is larger than its corresponding loop's header BB weight,
0936     // use the BB weight to replace the loop header BB weight.
0937     for (auto &BI : F) {
0938       BasicBlockT *BB = &BI;
0939       LoopT *L = LI->getLoopFor(BB);
0940       if (!L) {
0941         continue;
0942       }
0943       BasicBlockT *Header = L->getHeader();
0944       if (Header && BlockWeights[BB] > BlockWeights[Header]) {
0945         BlockWeights[Header] = BlockWeights[BB];
0946       }
0947     }
0948 
0949     // Propagate until we converge or we go past the iteration limit.
0950     while (Changed && I++ < SampleProfileMaxPropagateIterations) {
0951       Changed = propagateThroughEdges(F, false);
0952     }
0953 
0954     // The first propagation propagates BB counts from annotated BBs to unknown
0955     // BBs. The 2nd propagation pass resets edges weights, and use all BB
0956     // weights to propagate edge weights.
0957     VisitedEdges.clear();
0958     Changed = true;
0959     while (Changed && I++ < SampleProfileMaxPropagateIterations) {
0960       Changed = propagateThroughEdges(F, false);
0961     }
0962 
0963     // The 3rd propagation pass allows adjust annotated BB weights that are
0964     // obviously wrong.
0965     Changed = true;
0966     while (Changed && I++ < SampleProfileMaxPropagateIterations) {
0967       Changed = propagateThroughEdges(F, true);
0968     }
0969   }
0970 }
0971 
0972 template <typename FT>
0973 void SampleProfileLoaderBaseImpl<FT>::applyProfi(
0974     FunctionT &F, BlockEdgeMap &Successors, BlockWeightMap &SampleBlockWeights,
0975     BlockWeightMap &BlockWeights, EdgeWeightMap &EdgeWeights) {
0976   auto Infer = SampleProfileInference<FT>(F, Successors, SampleBlockWeights);
0977   Infer.apply(BlockWeights, EdgeWeights);
0978 }
0979 
0980 /// Generate branch weight metadata for all branches in \p F.
0981 ///
0982 /// Branch weights are computed out of instruction samples using a
0983 /// propagation heuristic. Propagation proceeds in 3 phases:
0984 ///
0985 /// 1- Assignment of block weights. All the basic blocks in the function
0986 ///    are initial assigned the same weight as their most frequently
0987 ///    executed instruction.
0988 ///
0989 /// 2- Creation of equivalence classes. Since samples may be missing from
0990 ///    blocks, we can fill in the gaps by setting the weights of all the
0991 ///    blocks in the same equivalence class to the same weight. To compute
0992 ///    the concept of equivalence, we use dominance and loop information.
0993 ///    Two blocks B1 and B2 are in the same equivalence class if B1
0994 ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
0995 ///
0996 /// 3- Propagation of block weights into edges. This uses a simple
0997 ///    propagation heuristic. The following rules are applied to every
0998 ///    block BB in the CFG:
0999 ///
1000 ///    - If BB has a single predecessor/successor, then the weight
1001 ///      of that edge is the weight of the block.
1002 ///
1003 ///    - If all the edges are known except one, and the weight of the
1004 ///      block is already known, the weight of the unknown edge will
1005 ///      be the weight of the block minus the sum of all the known
1006 ///      edges. If the sum of all the known edges is larger than BB's weight,
1007 ///      we set the unknown edge weight to zero.
1008 ///
1009 ///    - If there is a self-referential edge, and the weight of the block is
1010 ///      known, the weight for that edge is set to the weight of the block
1011 ///      minus the weight of the other incoming edges to that block (if
1012 ///      known).
1013 ///
1014 /// Since this propagation is not guaranteed to finalize for every CFG, we
1015 /// only allow it to proceed for a limited number of iterations (controlled
1016 /// by -sample-profile-max-propagate-iterations).
1017 ///
1018 /// FIXME: Try to replace this propagation heuristic with a scheme
1019 /// that is guaranteed to finalize. A work-list approach similar to
1020 /// the standard value propagation algorithm used by SSA-CCP might
1021 /// work here.
1022 ///
1023 /// \param F The function to query.
1024 ///
1025 /// \returns true if \p F was modified. Returns false, otherwise.
1026 template <typename BT>
1027 bool SampleProfileLoaderBaseImpl<BT>::computeAndPropagateWeights(
1028     FunctionT &F, const DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1029   bool Changed = (InlinedGUIDs.size() != 0);
1030 
1031   // Compute basic block weights.
1032   Changed |= computeBlockWeights(F);
1033 
1034   if (Changed) {
1035     // Initialize propagation.
1036     initWeightPropagation(F, InlinedGUIDs);
1037 
1038     // Propagate weights to all edges.
1039     propagateWeights(F);
1040 
1041     // Post-process propagated weights.
1042     finalizeWeightPropagation(F, InlinedGUIDs);
1043   }
1044 
1045   return Changed;
1046 }
1047 
1048 template <typename BT>
1049 void SampleProfileLoaderBaseImpl<BT>::initWeightPropagation(
1050     FunctionT &F, const DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1051   // Add an entry count to the function using the samples gathered at the
1052   // function entry.
1053   // Sets the GUIDs that are inlined in the profiled binary. This is used
1054   // for ThinLink to make correct liveness analysis, and also make the IR
1055   // match the profiled binary before annotation.
1056   getFunction(F).setEntryCount(
1057       ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
1058       &InlinedGUIDs);
1059 
1060   if (!SampleProfileUseProfi) {
1061     // Compute dominance and loop info needed for propagation.
1062     computeDominanceAndLoopInfo(F);
1063 
1064     // Find equivalence classes.
1065     findEquivalenceClasses(F);
1066   }
1067 
1068   // Before propagation starts, build, for each block, a list of
1069   // unique predecessors and successors. This is necessary to handle
1070   // identical edges in multiway branches. Since we visit all blocks and all
1071   // edges of the CFG, it is cleaner to build these lists once at the start
1072   // of the pass.
1073   buildEdges(F);
1074 }
1075 
1076 template <typename BT>
1077 void SampleProfileLoaderBaseImpl<BT>::finalizeWeightPropagation(
1078     FunctionT &F, const DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1079   // If we utilize a flow-based count inference, then we trust the computed
1080   // counts and set the entry count as computed by the algorithm. This is
1081   // primarily done to sync the counts produced by profi and BFI inference,
1082   // which uses the entry count for mass propagation.
1083   // If profi produces a zero-value for the entry count, we fallback to
1084   // Samples->getHeadSamples() + 1 to avoid functions with zero count.
1085   if (SampleProfileUseProfi) {
1086     const BasicBlockT *EntryBB = getEntryBB(&F);
1087     ErrorOr<uint64_t> EntryWeight = getBlockWeight(EntryBB);
1088     if (BlockWeights[EntryBB] > 0) {
1089       getFunction(F).setEntryCount(
1090           ProfileCount(BlockWeights[EntryBB], Function::PCT_Real),
1091           &InlinedGUIDs);
1092     }
1093   }
1094 }
1095 
1096 template <typename BT>
1097 void SampleProfileLoaderBaseImpl<BT>::emitCoverageRemarks(FunctionT &F) {
1098   // If coverage checking was requested, compute it now.
1099   const Function &Func = getFunction(F);
1100   if (SampleProfileRecordCoverage) {
1101     unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
1102     unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
1103     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1104     if (Coverage < SampleProfileRecordCoverage) {
1105       Func.getContext().diagnose(DiagnosticInfoSampleProfile(
1106           Func.getSubprogram()->getFilename(), getFunctionLoc(F),
1107           Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1108               Twine(Coverage) + "%) were applied",
1109           DS_Warning));
1110     }
1111   }
1112 
1113   if (SampleProfileSampleCoverage) {
1114     uint64_t Used = CoverageTracker.getTotalUsedSamples();
1115     uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
1116     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1117     if (Coverage < SampleProfileSampleCoverage) {
1118       Func.getContext().diagnose(DiagnosticInfoSampleProfile(
1119           Func.getSubprogram()->getFilename(), getFunctionLoc(F),
1120           Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1121               Twine(Coverage) + "%) were applied",
1122           DS_Warning));
1123     }
1124   }
1125 }
1126 
1127 /// Get the line number for the function header.
1128 ///
1129 /// This looks up function \p F in the current compilation unit and
1130 /// retrieves the line number where the function is defined. This is
1131 /// line 0 for all the samples read from the profile file. Every line
1132 /// number is relative to this line.
1133 ///
1134 /// \param F  Function object to query.
1135 ///
1136 /// \returns the line number where \p F is defined. If it returns 0,
1137 ///          it means that there is no debug information available for \p F.
1138 template <typename BT>
1139 unsigned SampleProfileLoaderBaseImpl<BT>::getFunctionLoc(FunctionT &F) {
1140   const Function &Func = getFunction(F);
1141   if (DISubprogram *S = Func.getSubprogram())
1142     return S->getLine();
1143 
1144   if (NoWarnSampleUnused)
1145     return 0;
1146 
1147   // If the start of \p F is missing, emit a diagnostic to inform the user
1148   // about the missed opportunity.
1149   Func.getContext().diagnose(DiagnosticInfoSampleProfile(
1150       "No debug information found in function " + Func.getName() +
1151           ": Function profile not used",
1152       DS_Warning));
1153   return 0;
1154 }
1155 
1156 #undef DEBUG_TYPE
1157 
1158 } // namespace llvm
1159 #endif // LLVM_TRANSFORMS_UTILS_SAMPLEPROFILELOADERBASEIMPL_H