xref: /aosp_15_r20/external/llvm/lib/Transforms/IPO/SampleProfile.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                      The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file implements the SampleProfileLoader transformation. This pass
11*9880d681SAndroid Build Coastguard Worker // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
12*9880d681SAndroid Build Coastguard Worker // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
13*9880d681SAndroid Build Coastguard Worker // profile information in the given profile.
14*9880d681SAndroid Build Coastguard Worker //
15*9880d681SAndroid Build Coastguard Worker // This pass generates branch weight annotations on the IR:
16*9880d681SAndroid Build Coastguard Worker //
17*9880d681SAndroid Build Coastguard Worker // - prof: Represents branch weights. This annotation is added to branches
18*9880d681SAndroid Build Coastguard Worker //      to indicate the weights of each edge coming out of the branch.
19*9880d681SAndroid Build Coastguard Worker //      The weight of each edge is the weight of the target block for
20*9880d681SAndroid Build Coastguard Worker //      that edge. The weight of a block B is computed as the maximum
21*9880d681SAndroid Build Coastguard Worker //      number of samples found in B.
22*9880d681SAndroid Build Coastguard Worker //
23*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
24*9880d681SAndroid Build Coastguard Worker 
25*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/SampleProfile.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseMap.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallPtrSet.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallSet.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/StringRef.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/PostDominators.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DebugInfo.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DiagnosticInfo.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Function.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/InstIterator.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/MDBuilder.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Metadata.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/ProfileData/SampleProfReader.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/ErrorOr.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Format.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/IPO.h"
53*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Cloning.h"
54*9880d681SAndroid Build Coastguard Worker #include <cctype>
55*9880d681SAndroid Build Coastguard Worker 
56*9880d681SAndroid Build Coastguard Worker using namespace llvm;
57*9880d681SAndroid Build Coastguard Worker using namespace sampleprof;
58*9880d681SAndroid Build Coastguard Worker 
59*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "sample-profile"
60*9880d681SAndroid Build Coastguard Worker 
61*9880d681SAndroid Build Coastguard Worker // Command line option to specify the file to read samples from. This is
62*9880d681SAndroid Build Coastguard Worker // mainly used for debugging.
63*9880d681SAndroid Build Coastguard Worker static cl::opt<std::string> SampleProfileFile(
64*9880d681SAndroid Build Coastguard Worker     "sample-profile-file", cl::init(""), cl::value_desc("filename"),
65*9880d681SAndroid Build Coastguard Worker     cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
66*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
67*9880d681SAndroid Build Coastguard Worker     "sample-profile-max-propagate-iterations", cl::init(100),
68*9880d681SAndroid Build Coastguard Worker     cl::desc("Maximum number of iterations to go through when propagating "
69*9880d681SAndroid Build Coastguard Worker              "sample block/edge weights through the CFG."));
70*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned> SampleProfileRecordCoverage(
71*9880d681SAndroid Build Coastguard Worker     "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
72*9880d681SAndroid Build Coastguard Worker     cl::desc("Emit a warning if less than N% of records in the input profile "
73*9880d681SAndroid Build Coastguard Worker              "are matched to the IR."));
74*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned> SampleProfileSampleCoverage(
75*9880d681SAndroid Build Coastguard Worker     "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
76*9880d681SAndroid Build Coastguard Worker     cl::desc("Emit a warning if less than N% of samples in the input profile "
77*9880d681SAndroid Build Coastguard Worker              "are matched to the IR."));
78*9880d681SAndroid Build Coastguard Worker static cl::opt<double> SampleProfileHotThreshold(
79*9880d681SAndroid Build Coastguard Worker     "sample-profile-inline-hot-threshold", cl::init(0.1), cl::value_desc("N"),
80*9880d681SAndroid Build Coastguard Worker     cl::desc("Inlined functions that account for more than N% of all samples "
81*9880d681SAndroid Build Coastguard Worker              "collected in the parent function, will be inlined again."));
82*9880d681SAndroid Build Coastguard Worker 
83*9880d681SAndroid Build Coastguard Worker namespace {
84*9880d681SAndroid Build Coastguard Worker typedef DenseMap<const BasicBlock *, uint64_t> BlockWeightMap;
85*9880d681SAndroid Build Coastguard Worker typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap;
86*9880d681SAndroid Build Coastguard Worker typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
87*9880d681SAndroid Build Coastguard Worker typedef DenseMap<Edge, uint64_t> EdgeWeightMap;
88*9880d681SAndroid Build Coastguard Worker typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>
89*9880d681SAndroid Build Coastguard Worker     BlockEdgeMap;
90*9880d681SAndroid Build Coastguard Worker 
91*9880d681SAndroid Build Coastguard Worker /// \brief Sample profile pass.
92*9880d681SAndroid Build Coastguard Worker ///
93*9880d681SAndroid Build Coastguard Worker /// This pass reads profile data from the file specified by
94*9880d681SAndroid Build Coastguard Worker /// -sample-profile-file and annotates every affected function with the
95*9880d681SAndroid Build Coastguard Worker /// profile information found in that file.
96*9880d681SAndroid Build Coastguard Worker class SampleProfileLoader {
97*9880d681SAndroid Build Coastguard Worker public:
SampleProfileLoader(StringRef Name=SampleProfileFile)98*9880d681SAndroid Build Coastguard Worker   SampleProfileLoader(StringRef Name = SampleProfileFile)
99*9880d681SAndroid Build Coastguard Worker       : DT(nullptr), PDT(nullptr), LI(nullptr), ACT(nullptr), Reader(),
100*9880d681SAndroid Build Coastguard Worker         Samples(nullptr), Filename(Name), ProfileIsValid(false),
101*9880d681SAndroid Build Coastguard Worker         TotalCollectedSamples(0) {}
102*9880d681SAndroid Build Coastguard Worker 
103*9880d681SAndroid Build Coastguard Worker   bool doInitialization(Module &M);
104*9880d681SAndroid Build Coastguard Worker   bool runOnModule(Module &M);
setACT(AssumptionCacheTracker * A)105*9880d681SAndroid Build Coastguard Worker   void setACT(AssumptionCacheTracker *A) { ACT = A; }
106*9880d681SAndroid Build Coastguard Worker 
dump()107*9880d681SAndroid Build Coastguard Worker   void dump() { Reader->dump(); }
108*9880d681SAndroid Build Coastguard Worker 
109*9880d681SAndroid Build Coastguard Worker protected:
110*9880d681SAndroid Build Coastguard Worker   bool runOnFunction(Function &F);
111*9880d681SAndroid Build Coastguard Worker   unsigned getFunctionLoc(Function &F);
112*9880d681SAndroid Build Coastguard Worker   bool emitAnnotations(Function &F);
113*9880d681SAndroid Build Coastguard Worker   ErrorOr<uint64_t> getInstWeight(const Instruction &I) const;
114*9880d681SAndroid Build Coastguard Worker   ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB) const;
115*9880d681SAndroid Build Coastguard Worker   const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const;
116*9880d681SAndroid Build Coastguard Worker   const FunctionSamples *findFunctionSamples(const Instruction &I) const;
117*9880d681SAndroid Build Coastguard Worker   bool inlineHotFunctions(Function &F);
118*9880d681SAndroid Build Coastguard Worker   void printEdgeWeight(raw_ostream &OS, Edge E);
119*9880d681SAndroid Build Coastguard Worker   void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
120*9880d681SAndroid Build Coastguard Worker   void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
121*9880d681SAndroid Build Coastguard Worker   bool computeBlockWeights(Function &F);
122*9880d681SAndroid Build Coastguard Worker   void findEquivalenceClasses(Function &F);
123*9880d681SAndroid Build Coastguard Worker   void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
124*9880d681SAndroid Build Coastguard Worker                            DominatorTreeBase<BasicBlock> *DomTree);
125*9880d681SAndroid Build Coastguard Worker   void propagateWeights(Function &F);
126*9880d681SAndroid Build Coastguard Worker   uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
127*9880d681SAndroid Build Coastguard Worker   void buildEdges(Function &F);
128*9880d681SAndroid Build Coastguard Worker   bool propagateThroughEdges(Function &F);
129*9880d681SAndroid Build Coastguard Worker   void computeDominanceAndLoopInfo(Function &F);
130*9880d681SAndroid Build Coastguard Worker   unsigned getOffset(unsigned L, unsigned H) const;
131*9880d681SAndroid Build Coastguard Worker   void clearFunctionData();
132*9880d681SAndroid Build Coastguard Worker 
133*9880d681SAndroid Build Coastguard Worker   /// \brief Map basic blocks to their computed weights.
134*9880d681SAndroid Build Coastguard Worker   ///
135*9880d681SAndroid Build Coastguard Worker   /// The weight of a basic block is defined to be the maximum
136*9880d681SAndroid Build Coastguard Worker   /// of all the instruction weights in that block.
137*9880d681SAndroid Build Coastguard Worker   BlockWeightMap BlockWeights;
138*9880d681SAndroid Build Coastguard Worker 
139*9880d681SAndroid Build Coastguard Worker   /// \brief Map edges to their computed weights.
140*9880d681SAndroid Build Coastguard Worker   ///
141*9880d681SAndroid Build Coastguard Worker   /// Edge weights are computed by propagating basic block weights in
142*9880d681SAndroid Build Coastguard Worker   /// SampleProfile::propagateWeights.
143*9880d681SAndroid Build Coastguard Worker   EdgeWeightMap EdgeWeights;
144*9880d681SAndroid Build Coastguard Worker 
145*9880d681SAndroid Build Coastguard Worker   /// \brief Set of visited blocks during propagation.
146*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
147*9880d681SAndroid Build Coastguard Worker 
148*9880d681SAndroid Build Coastguard Worker   /// \brief Set of visited edges during propagation.
149*9880d681SAndroid Build Coastguard Worker   SmallSet<Edge, 32> VisitedEdges;
150*9880d681SAndroid Build Coastguard Worker 
151*9880d681SAndroid Build Coastguard Worker   /// \brief Equivalence classes for block weights.
152*9880d681SAndroid Build Coastguard Worker   ///
153*9880d681SAndroid Build Coastguard Worker   /// Two blocks BB1 and BB2 are in the same equivalence class if they
154*9880d681SAndroid Build Coastguard Worker   /// dominate and post-dominate each other, and they are in the same loop
155*9880d681SAndroid Build Coastguard Worker   /// nest. When this happens, the two blocks are guaranteed to execute
156*9880d681SAndroid Build Coastguard Worker   /// the same number of times.
157*9880d681SAndroid Build Coastguard Worker   EquivalenceClassMap EquivalenceClass;
158*9880d681SAndroid Build Coastguard Worker 
159*9880d681SAndroid Build Coastguard Worker   /// \brief Dominance, post-dominance and loop information.
160*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<DominatorTree> DT;
161*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT;
162*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<LoopInfo> LI;
163*9880d681SAndroid Build Coastguard Worker 
164*9880d681SAndroid Build Coastguard Worker   AssumptionCacheTracker *ACT;
165*9880d681SAndroid Build Coastguard Worker 
166*9880d681SAndroid Build Coastguard Worker   /// \brief Predecessors for each basic block in the CFG.
167*9880d681SAndroid Build Coastguard Worker   BlockEdgeMap Predecessors;
168*9880d681SAndroid Build Coastguard Worker 
169*9880d681SAndroid Build Coastguard Worker   /// \brief Successors for each basic block in the CFG.
170*9880d681SAndroid Build Coastguard Worker   BlockEdgeMap Successors;
171*9880d681SAndroid Build Coastguard Worker 
172*9880d681SAndroid Build Coastguard Worker   /// \brief Profile reader object.
173*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<SampleProfileReader> Reader;
174*9880d681SAndroid Build Coastguard Worker 
175*9880d681SAndroid Build Coastguard Worker   /// \brief Samples collected for the body of this function.
176*9880d681SAndroid Build Coastguard Worker   FunctionSamples *Samples;
177*9880d681SAndroid Build Coastguard Worker 
178*9880d681SAndroid Build Coastguard Worker   /// \brief Name of the profile file to load.
179*9880d681SAndroid Build Coastguard Worker   StringRef Filename;
180*9880d681SAndroid Build Coastguard Worker 
181*9880d681SAndroid Build Coastguard Worker   /// \brief Flag indicating whether the profile input loaded successfully.
182*9880d681SAndroid Build Coastguard Worker   bool ProfileIsValid;
183*9880d681SAndroid Build Coastguard Worker 
184*9880d681SAndroid Build Coastguard Worker   /// \brief Total number of samples collected in this profile.
185*9880d681SAndroid Build Coastguard Worker   ///
186*9880d681SAndroid Build Coastguard Worker   /// This is the sum of all the samples collected in all the functions executed
187*9880d681SAndroid Build Coastguard Worker   /// at runtime.
188*9880d681SAndroid Build Coastguard Worker   uint64_t TotalCollectedSamples;
189*9880d681SAndroid Build Coastguard Worker };
190*9880d681SAndroid Build Coastguard Worker 
191*9880d681SAndroid Build Coastguard Worker class SampleProfileLoaderLegacyPass : public ModulePass {
192*9880d681SAndroid Build Coastguard Worker public:
193*9880d681SAndroid Build Coastguard Worker   // Class identification, replacement for typeinfo
194*9880d681SAndroid Build Coastguard Worker   static char ID;
195*9880d681SAndroid Build Coastguard Worker 
SampleProfileLoaderLegacyPass(StringRef Name=SampleProfileFile)196*9880d681SAndroid Build Coastguard Worker   SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile)
197*9880d681SAndroid Build Coastguard Worker       : ModulePass(ID), SampleLoader(Name) {
198*9880d681SAndroid Build Coastguard Worker     initializeSampleProfileLoaderLegacyPassPass(
199*9880d681SAndroid Build Coastguard Worker         *PassRegistry::getPassRegistry());
200*9880d681SAndroid Build Coastguard Worker   }
201*9880d681SAndroid Build Coastguard Worker 
dump()202*9880d681SAndroid Build Coastguard Worker   void dump() { SampleLoader.dump(); }
203*9880d681SAndroid Build Coastguard Worker 
doInitialization(Module & M)204*9880d681SAndroid Build Coastguard Worker   bool doInitialization(Module &M) override {
205*9880d681SAndroid Build Coastguard Worker     return SampleLoader.doInitialization(M);
206*9880d681SAndroid Build Coastguard Worker   }
getPassName() const207*9880d681SAndroid Build Coastguard Worker   const char *getPassName() const override { return "Sample profile pass"; }
208*9880d681SAndroid Build Coastguard Worker   bool runOnModule(Module &M) override;
209*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const210*9880d681SAndroid Build Coastguard Worker   void getAnalysisUsage(AnalysisUsage &AU) const override {
211*9880d681SAndroid Build Coastguard Worker     AU.addRequired<AssumptionCacheTracker>();
212*9880d681SAndroid Build Coastguard Worker   }
213*9880d681SAndroid Build Coastguard Worker private:
214*9880d681SAndroid Build Coastguard Worker   SampleProfileLoader SampleLoader;
215*9880d681SAndroid Build Coastguard Worker };
216*9880d681SAndroid Build Coastguard Worker 
217*9880d681SAndroid Build Coastguard Worker class SampleCoverageTracker {
218*9880d681SAndroid Build Coastguard Worker public:
SampleCoverageTracker()219*9880d681SAndroid Build Coastguard Worker   SampleCoverageTracker() : SampleCoverage(), TotalUsedSamples(0) {}
220*9880d681SAndroid Build Coastguard Worker 
221*9880d681SAndroid Build Coastguard Worker   bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
222*9880d681SAndroid Build Coastguard Worker                        uint32_t Discriminator, uint64_t Samples);
223*9880d681SAndroid Build Coastguard Worker   unsigned computeCoverage(unsigned Used, unsigned Total) const;
224*9880d681SAndroid Build Coastguard Worker   unsigned countUsedRecords(const FunctionSamples *FS) const;
225*9880d681SAndroid Build Coastguard Worker   unsigned countBodyRecords(const FunctionSamples *FS) const;
getTotalUsedSamples() const226*9880d681SAndroid Build Coastguard Worker   uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
227*9880d681SAndroid Build Coastguard Worker   uint64_t countBodySamples(const FunctionSamples *FS) const;
clear()228*9880d681SAndroid Build Coastguard Worker   void clear() {
229*9880d681SAndroid Build Coastguard Worker     SampleCoverage.clear();
230*9880d681SAndroid Build Coastguard Worker     TotalUsedSamples = 0;
231*9880d681SAndroid Build Coastguard Worker   }
232*9880d681SAndroid Build Coastguard Worker 
233*9880d681SAndroid Build Coastguard Worker private:
234*9880d681SAndroid Build Coastguard Worker   typedef std::map<LineLocation, unsigned> BodySampleCoverageMap;
235*9880d681SAndroid Build Coastguard Worker   typedef DenseMap<const FunctionSamples *, BodySampleCoverageMap>
236*9880d681SAndroid Build Coastguard Worker       FunctionSamplesCoverageMap;
237*9880d681SAndroid Build Coastguard Worker 
238*9880d681SAndroid Build Coastguard Worker   /// Coverage map for sampling records.
239*9880d681SAndroid Build Coastguard Worker   ///
240*9880d681SAndroid Build Coastguard Worker   /// This map keeps a record of sampling records that have been matched to
241*9880d681SAndroid Build Coastguard Worker   /// an IR instruction. This is used to detect some form of staleness in
242*9880d681SAndroid Build Coastguard Worker   /// profiles (see flag -sample-profile-check-coverage).
243*9880d681SAndroid Build Coastguard Worker   ///
244*9880d681SAndroid Build Coastguard Worker   /// Each entry in the map corresponds to a FunctionSamples instance.  This is
245*9880d681SAndroid Build Coastguard Worker   /// another map that counts how many times the sample record at the
246*9880d681SAndroid Build Coastguard Worker   /// given location has been used.
247*9880d681SAndroid Build Coastguard Worker   FunctionSamplesCoverageMap SampleCoverage;
248*9880d681SAndroid Build Coastguard Worker 
249*9880d681SAndroid Build Coastguard Worker   /// Number of samples used from the profile.
250*9880d681SAndroid Build Coastguard Worker   ///
251*9880d681SAndroid Build Coastguard Worker   /// When a sampling record is used for the first time, the samples from
252*9880d681SAndroid Build Coastguard Worker   /// that record are added to this accumulator.  Coverage is later computed
253*9880d681SAndroid Build Coastguard Worker   /// based on the total number of samples available in this function and
254*9880d681SAndroid Build Coastguard Worker   /// its callsites.
255*9880d681SAndroid Build Coastguard Worker   ///
256*9880d681SAndroid Build Coastguard Worker   /// Note that this accumulator tracks samples used from a single function
257*9880d681SAndroid Build Coastguard Worker   /// and all the inlined callsites. Strictly, we should have a map of counters
258*9880d681SAndroid Build Coastguard Worker   /// keyed by FunctionSamples pointers, but these stats are cleared after
259*9880d681SAndroid Build Coastguard Worker   /// every function, so we just need to keep a single counter.
260*9880d681SAndroid Build Coastguard Worker   uint64_t TotalUsedSamples;
261*9880d681SAndroid Build Coastguard Worker };
262*9880d681SAndroid Build Coastguard Worker 
263*9880d681SAndroid Build Coastguard Worker SampleCoverageTracker CoverageTracker;
264*9880d681SAndroid Build Coastguard Worker 
265*9880d681SAndroid Build Coastguard Worker /// Return true if the given callsite is hot wrt to its caller.
266*9880d681SAndroid Build Coastguard Worker ///
267*9880d681SAndroid Build Coastguard Worker /// Functions that were inlined in the original binary will be represented
268*9880d681SAndroid Build Coastguard Worker /// in the inline stack in the sample profile. If the profile shows that
269*9880d681SAndroid Build Coastguard Worker /// the original inline decision was "good" (i.e., the callsite is executed
270*9880d681SAndroid Build Coastguard Worker /// frequently), then we will recreate the inline decision and apply the
271*9880d681SAndroid Build Coastguard Worker /// profile from the inlined callsite.
272*9880d681SAndroid Build Coastguard Worker ///
273*9880d681SAndroid Build Coastguard Worker /// To decide whether an inlined callsite is hot, we compute the fraction
274*9880d681SAndroid Build Coastguard Worker /// of samples used by the callsite with respect to the total number of samples
275*9880d681SAndroid Build Coastguard Worker /// collected in the caller.
276*9880d681SAndroid Build Coastguard Worker ///
277*9880d681SAndroid Build Coastguard Worker /// If that fraction is larger than the default given by
278*9880d681SAndroid Build Coastguard Worker /// SampleProfileHotThreshold, the callsite will be inlined again.
callsiteIsHot(const FunctionSamples * CallerFS,const FunctionSamples * CallsiteFS)279*9880d681SAndroid Build Coastguard Worker bool callsiteIsHot(const FunctionSamples *CallerFS,
280*9880d681SAndroid Build Coastguard Worker                    const FunctionSamples *CallsiteFS) {
281*9880d681SAndroid Build Coastguard Worker   if (!CallsiteFS)
282*9880d681SAndroid Build Coastguard Worker     return false; // The callsite was not inlined in the original binary.
283*9880d681SAndroid Build Coastguard Worker 
284*9880d681SAndroid Build Coastguard Worker   uint64_t ParentTotalSamples = CallerFS->getTotalSamples();
285*9880d681SAndroid Build Coastguard Worker   if (ParentTotalSamples == 0)
286*9880d681SAndroid Build Coastguard Worker     return false; // Avoid division by zero.
287*9880d681SAndroid Build Coastguard Worker 
288*9880d681SAndroid Build Coastguard Worker   uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
289*9880d681SAndroid Build Coastguard Worker   if (CallsiteTotalSamples == 0)
290*9880d681SAndroid Build Coastguard Worker     return false; // Callsite is trivially cold.
291*9880d681SAndroid Build Coastguard Worker 
292*9880d681SAndroid Build Coastguard Worker   double PercentSamples =
293*9880d681SAndroid Build Coastguard Worker       (double)CallsiteTotalSamples / (double)ParentTotalSamples * 100.0;
294*9880d681SAndroid Build Coastguard Worker   return PercentSamples >= SampleProfileHotThreshold;
295*9880d681SAndroid Build Coastguard Worker }
296*9880d681SAndroid Build Coastguard Worker }
297*9880d681SAndroid Build Coastguard Worker 
298*9880d681SAndroid Build Coastguard Worker /// Mark as used the sample record for the given function samples at
299*9880d681SAndroid Build Coastguard Worker /// (LineOffset, Discriminator).
300*9880d681SAndroid Build Coastguard Worker ///
301*9880d681SAndroid Build Coastguard Worker /// \returns true if this is the first time we mark the given record.
markSamplesUsed(const FunctionSamples * FS,uint32_t LineOffset,uint32_t Discriminator,uint64_t Samples)302*9880d681SAndroid Build Coastguard Worker bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
303*9880d681SAndroid Build Coastguard Worker                                             uint32_t LineOffset,
304*9880d681SAndroid Build Coastguard Worker                                             uint32_t Discriminator,
305*9880d681SAndroid Build Coastguard Worker                                             uint64_t Samples) {
306*9880d681SAndroid Build Coastguard Worker   LineLocation Loc(LineOffset, Discriminator);
307*9880d681SAndroid Build Coastguard Worker   unsigned &Count = SampleCoverage[FS][Loc];
308*9880d681SAndroid Build Coastguard Worker   bool FirstTime = (++Count == 1);
309*9880d681SAndroid Build Coastguard Worker   if (FirstTime)
310*9880d681SAndroid Build Coastguard Worker     TotalUsedSamples += Samples;
311*9880d681SAndroid Build Coastguard Worker   return FirstTime;
312*9880d681SAndroid Build Coastguard Worker }
313*9880d681SAndroid Build Coastguard Worker 
314*9880d681SAndroid Build Coastguard Worker /// Return the number of sample records that were applied from this profile.
315*9880d681SAndroid Build Coastguard Worker ///
316*9880d681SAndroid Build Coastguard Worker /// This count does not include records from cold inlined callsites.
317*9880d681SAndroid Build Coastguard Worker unsigned
countUsedRecords(const FunctionSamples * FS) const318*9880d681SAndroid Build Coastguard Worker SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS) const {
319*9880d681SAndroid Build Coastguard Worker   auto I = SampleCoverage.find(FS);
320*9880d681SAndroid Build Coastguard Worker 
321*9880d681SAndroid Build Coastguard Worker   // The size of the coverage map for FS represents the number of records
322*9880d681SAndroid Build Coastguard Worker   // that were marked used at least once.
323*9880d681SAndroid Build Coastguard Worker   unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
324*9880d681SAndroid Build Coastguard Worker 
325*9880d681SAndroid Build Coastguard Worker   // If there are inlined callsites in this function, count the samples found
326*9880d681SAndroid Build Coastguard Worker   // in the respective bodies. However, do not bother counting callees with 0
327*9880d681SAndroid Build Coastguard Worker   // total samples, these are callees that were never invoked at runtime.
328*9880d681SAndroid Build Coastguard Worker   for (const auto &I : FS->getCallsiteSamples()) {
329*9880d681SAndroid Build Coastguard Worker     const FunctionSamples *CalleeSamples = &I.second;
330*9880d681SAndroid Build Coastguard Worker     if (callsiteIsHot(FS, CalleeSamples))
331*9880d681SAndroid Build Coastguard Worker       Count += countUsedRecords(CalleeSamples);
332*9880d681SAndroid Build Coastguard Worker   }
333*9880d681SAndroid Build Coastguard Worker 
334*9880d681SAndroid Build Coastguard Worker   return Count;
335*9880d681SAndroid Build Coastguard Worker }
336*9880d681SAndroid Build Coastguard Worker 
337*9880d681SAndroid Build Coastguard Worker /// Return the number of sample records in the body of this profile.
338*9880d681SAndroid Build Coastguard Worker ///
339*9880d681SAndroid Build Coastguard Worker /// This count does not include records from cold inlined callsites.
340*9880d681SAndroid Build Coastguard Worker unsigned
countBodyRecords(const FunctionSamples * FS) const341*9880d681SAndroid Build Coastguard Worker SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS) const {
342*9880d681SAndroid Build Coastguard Worker   unsigned Count = FS->getBodySamples().size();
343*9880d681SAndroid Build Coastguard Worker 
344*9880d681SAndroid Build Coastguard Worker   // Only count records in hot callsites.
345*9880d681SAndroid Build Coastguard Worker   for (const auto &I : FS->getCallsiteSamples()) {
346*9880d681SAndroid Build Coastguard Worker     const FunctionSamples *CalleeSamples = &I.second;
347*9880d681SAndroid Build Coastguard Worker     if (callsiteIsHot(FS, CalleeSamples))
348*9880d681SAndroid Build Coastguard Worker       Count += countBodyRecords(CalleeSamples);
349*9880d681SAndroid Build Coastguard Worker   }
350*9880d681SAndroid Build Coastguard Worker 
351*9880d681SAndroid Build Coastguard Worker   return Count;
352*9880d681SAndroid Build Coastguard Worker }
353*9880d681SAndroid Build Coastguard Worker 
354*9880d681SAndroid Build Coastguard Worker /// Return the number of samples collected in the body of this profile.
355*9880d681SAndroid Build Coastguard Worker ///
356*9880d681SAndroid Build Coastguard Worker /// This count does not include samples from cold inlined callsites.
357*9880d681SAndroid Build Coastguard Worker uint64_t
countBodySamples(const FunctionSamples * FS) const358*9880d681SAndroid Build Coastguard Worker SampleCoverageTracker::countBodySamples(const FunctionSamples *FS) const {
359*9880d681SAndroid Build Coastguard Worker   uint64_t Total = 0;
360*9880d681SAndroid Build Coastguard Worker   for (const auto &I : FS->getBodySamples())
361*9880d681SAndroid Build Coastguard Worker     Total += I.second.getSamples();
362*9880d681SAndroid Build Coastguard Worker 
363*9880d681SAndroid Build Coastguard Worker   // Only count samples in hot callsites.
364*9880d681SAndroid Build Coastguard Worker   for (const auto &I : FS->getCallsiteSamples()) {
365*9880d681SAndroid Build Coastguard Worker     const FunctionSamples *CalleeSamples = &I.second;
366*9880d681SAndroid Build Coastguard Worker     if (callsiteIsHot(FS, CalleeSamples))
367*9880d681SAndroid Build Coastguard Worker       Total += countBodySamples(CalleeSamples);
368*9880d681SAndroid Build Coastguard Worker   }
369*9880d681SAndroid Build Coastguard Worker 
370*9880d681SAndroid Build Coastguard Worker   return Total;
371*9880d681SAndroid Build Coastguard Worker }
372*9880d681SAndroid Build Coastguard Worker 
373*9880d681SAndroid Build Coastguard Worker /// Return the fraction of sample records used in this profile.
374*9880d681SAndroid Build Coastguard Worker ///
375*9880d681SAndroid Build Coastguard Worker /// The returned value is an unsigned integer in the range 0-100 indicating
376*9880d681SAndroid Build Coastguard Worker /// the percentage of sample records that were used while applying this
377*9880d681SAndroid Build Coastguard Worker /// profile to the associated function.
computeCoverage(unsigned Used,unsigned Total) const378*9880d681SAndroid Build Coastguard Worker unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
379*9880d681SAndroid Build Coastguard Worker                                                 unsigned Total) const {
380*9880d681SAndroid Build Coastguard Worker   assert(Used <= Total &&
381*9880d681SAndroid Build Coastguard Worker          "number of used records cannot exceed the total number of records");
382*9880d681SAndroid Build Coastguard Worker   return Total > 0 ? Used * 100 / Total : 100;
383*9880d681SAndroid Build Coastguard Worker }
384*9880d681SAndroid Build Coastguard Worker 
385*9880d681SAndroid Build Coastguard Worker /// Clear all the per-function data used to load samples and propagate weights.
clearFunctionData()386*9880d681SAndroid Build Coastguard Worker void SampleProfileLoader::clearFunctionData() {
387*9880d681SAndroid Build Coastguard Worker   BlockWeights.clear();
388*9880d681SAndroid Build Coastguard Worker   EdgeWeights.clear();
389*9880d681SAndroid Build Coastguard Worker   VisitedBlocks.clear();
390*9880d681SAndroid Build Coastguard Worker   VisitedEdges.clear();
391*9880d681SAndroid Build Coastguard Worker   EquivalenceClass.clear();
392*9880d681SAndroid Build Coastguard Worker   DT = nullptr;
393*9880d681SAndroid Build Coastguard Worker   PDT = nullptr;
394*9880d681SAndroid Build Coastguard Worker   LI = nullptr;
395*9880d681SAndroid Build Coastguard Worker   Predecessors.clear();
396*9880d681SAndroid Build Coastguard Worker   Successors.clear();
397*9880d681SAndroid Build Coastguard Worker   CoverageTracker.clear();
398*9880d681SAndroid Build Coastguard Worker }
399*9880d681SAndroid Build Coastguard Worker 
400*9880d681SAndroid Build Coastguard Worker /// \brief Returns the offset of lineno \p L to head_lineno \p H
401*9880d681SAndroid Build Coastguard Worker ///
402*9880d681SAndroid Build Coastguard Worker /// \param L  Lineno
403*9880d681SAndroid Build Coastguard Worker /// \param H  Header lineno of the function
404*9880d681SAndroid Build Coastguard Worker ///
405*9880d681SAndroid Build Coastguard Worker /// \returns offset to the header lineno. 16 bits are used to represent offset.
406*9880d681SAndroid Build Coastguard Worker /// We assume that a single function will not exceed 65535 LOC.
getOffset(unsigned L,unsigned H) const407*9880d681SAndroid Build Coastguard Worker unsigned SampleProfileLoader::getOffset(unsigned L, unsigned H) const {
408*9880d681SAndroid Build Coastguard Worker   return (L - H) & 0xffff;
409*9880d681SAndroid Build Coastguard Worker }
410*9880d681SAndroid Build Coastguard Worker 
411*9880d681SAndroid Build Coastguard Worker /// \brief Print the weight of edge \p E on stream \p OS.
412*9880d681SAndroid Build Coastguard Worker ///
413*9880d681SAndroid Build Coastguard Worker /// \param OS  Stream to emit the output to.
414*9880d681SAndroid Build Coastguard Worker /// \param E  Edge to print.
printEdgeWeight(raw_ostream & OS,Edge E)415*9880d681SAndroid Build Coastguard Worker void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
416*9880d681SAndroid Build Coastguard Worker   OS << "weight[" << E.first->getName() << "->" << E.second->getName()
417*9880d681SAndroid Build Coastguard Worker      << "]: " << EdgeWeights[E] << "\n";
418*9880d681SAndroid Build Coastguard Worker }
419*9880d681SAndroid Build Coastguard Worker 
420*9880d681SAndroid Build Coastguard Worker /// \brief Print the equivalence class of block \p BB on stream \p OS.
421*9880d681SAndroid Build Coastguard Worker ///
422*9880d681SAndroid Build Coastguard Worker /// \param OS  Stream to emit the output to.
423*9880d681SAndroid Build Coastguard Worker /// \param BB  Block to print.
printBlockEquivalence(raw_ostream & OS,const BasicBlock * BB)424*9880d681SAndroid Build Coastguard Worker void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
425*9880d681SAndroid Build Coastguard Worker                                                 const BasicBlock *BB) {
426*9880d681SAndroid Build Coastguard Worker   const BasicBlock *Equiv = EquivalenceClass[BB];
427*9880d681SAndroid Build Coastguard Worker   OS << "equivalence[" << BB->getName()
428*9880d681SAndroid Build Coastguard Worker      << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
429*9880d681SAndroid Build Coastguard Worker }
430*9880d681SAndroid Build Coastguard Worker 
431*9880d681SAndroid Build Coastguard Worker /// \brief Print the weight of block \p BB on stream \p OS.
432*9880d681SAndroid Build Coastguard Worker ///
433*9880d681SAndroid Build Coastguard Worker /// \param OS  Stream to emit the output to.
434*9880d681SAndroid Build Coastguard Worker /// \param BB  Block to print.
printBlockWeight(raw_ostream & OS,const BasicBlock * BB) const435*9880d681SAndroid Build Coastguard Worker void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
436*9880d681SAndroid Build Coastguard Worker                                            const BasicBlock *BB) const {
437*9880d681SAndroid Build Coastguard Worker   const auto &I = BlockWeights.find(BB);
438*9880d681SAndroid Build Coastguard Worker   uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
439*9880d681SAndroid Build Coastguard Worker   OS << "weight[" << BB->getName() << "]: " << W << "\n";
440*9880d681SAndroid Build Coastguard Worker }
441*9880d681SAndroid Build Coastguard Worker 
442*9880d681SAndroid Build Coastguard Worker /// \brief Get the weight for an instruction.
443*9880d681SAndroid Build Coastguard Worker ///
444*9880d681SAndroid Build Coastguard Worker /// The "weight" of an instruction \p Inst is the number of samples
445*9880d681SAndroid Build Coastguard Worker /// collected on that instruction at runtime. To retrieve it, we
446*9880d681SAndroid Build Coastguard Worker /// need to compute the line number of \p Inst relative to the start of its
447*9880d681SAndroid Build Coastguard Worker /// function. We use HeaderLineno to compute the offset. We then
448*9880d681SAndroid Build Coastguard Worker /// look up the samples collected for \p Inst using BodySamples.
449*9880d681SAndroid Build Coastguard Worker ///
450*9880d681SAndroid Build Coastguard Worker /// \param Inst Instruction to query.
451*9880d681SAndroid Build Coastguard Worker ///
452*9880d681SAndroid Build Coastguard Worker /// \returns the weight of \p Inst.
453*9880d681SAndroid Build Coastguard Worker ErrorOr<uint64_t>
getInstWeight(const Instruction & Inst) const454*9880d681SAndroid Build Coastguard Worker SampleProfileLoader::getInstWeight(const Instruction &Inst) const {
455*9880d681SAndroid Build Coastguard Worker   const DebugLoc &DLoc = Inst.getDebugLoc();
456*9880d681SAndroid Build Coastguard Worker   if (!DLoc)
457*9880d681SAndroid Build Coastguard Worker     return std::error_code();
458*9880d681SAndroid Build Coastguard Worker 
459*9880d681SAndroid Build Coastguard Worker   const FunctionSamples *FS = findFunctionSamples(Inst);
460*9880d681SAndroid Build Coastguard Worker   if (!FS)
461*9880d681SAndroid Build Coastguard Worker     return std::error_code();
462*9880d681SAndroid Build Coastguard Worker 
463*9880d681SAndroid Build Coastguard Worker   // Ignore all dbg_value intrinsics.
464*9880d681SAndroid Build Coastguard Worker   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Inst);
465*9880d681SAndroid Build Coastguard Worker   if (II && II->getIntrinsicID() == Intrinsic::dbg_value)
466*9880d681SAndroid Build Coastguard Worker     return std::error_code();
467*9880d681SAndroid Build Coastguard Worker 
468*9880d681SAndroid Build Coastguard Worker   const DILocation *DIL = DLoc;
469*9880d681SAndroid Build Coastguard Worker   unsigned Lineno = DLoc.getLine();
470*9880d681SAndroid Build Coastguard Worker   unsigned HeaderLineno = DIL->getScope()->getSubprogram()->getLine();
471*9880d681SAndroid Build Coastguard Worker 
472*9880d681SAndroid Build Coastguard Worker   uint32_t LineOffset = getOffset(Lineno, HeaderLineno);
473*9880d681SAndroid Build Coastguard Worker   uint32_t Discriminator = DIL->getDiscriminator();
474*9880d681SAndroid Build Coastguard Worker   ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
475*9880d681SAndroid Build Coastguard Worker   if (R) {
476*9880d681SAndroid Build Coastguard Worker     bool FirstMark =
477*9880d681SAndroid Build Coastguard Worker         CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
478*9880d681SAndroid Build Coastguard Worker     if (FirstMark) {
479*9880d681SAndroid Build Coastguard Worker       const Function *F = Inst.getParent()->getParent();
480*9880d681SAndroid Build Coastguard Worker       LLVMContext &Ctx = F->getContext();
481*9880d681SAndroid Build Coastguard Worker       emitOptimizationRemark(
482*9880d681SAndroid Build Coastguard Worker           Ctx, DEBUG_TYPE, *F, DLoc,
483*9880d681SAndroid Build Coastguard Worker           Twine("Applied ") + Twine(*R) + " samples from profile (offset: " +
484*9880d681SAndroid Build Coastguard Worker               Twine(LineOffset) +
485*9880d681SAndroid Build Coastguard Worker               ((Discriminator) ? Twine(".") + Twine(Discriminator) : "") + ")");
486*9880d681SAndroid Build Coastguard Worker     }
487*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "    " << Lineno << "." << DIL->getDiscriminator() << ":"
488*9880d681SAndroid Build Coastguard Worker                  << Inst << " (line offset: " << Lineno - HeaderLineno << "."
489*9880d681SAndroid Build Coastguard Worker                  << DIL->getDiscriminator() << " - weight: " << R.get()
490*9880d681SAndroid Build Coastguard Worker                  << ")\n");
491*9880d681SAndroid Build Coastguard Worker   } else {
492*9880d681SAndroid Build Coastguard Worker     // If a call instruction is inlined in profile, but not inlined here,
493*9880d681SAndroid Build Coastguard Worker     // it means that the inlined callsite has no sample, thus the call
494*9880d681SAndroid Build Coastguard Worker     // instruction should have 0 count.
495*9880d681SAndroid Build Coastguard Worker     const CallInst *CI = dyn_cast<CallInst>(&Inst);
496*9880d681SAndroid Build Coastguard Worker     if (CI && findCalleeFunctionSamples(*CI))
497*9880d681SAndroid Build Coastguard Worker       R = 0;
498*9880d681SAndroid Build Coastguard Worker   }
499*9880d681SAndroid Build Coastguard Worker   return R;
500*9880d681SAndroid Build Coastguard Worker }
501*9880d681SAndroid Build Coastguard Worker 
502*9880d681SAndroid Build Coastguard Worker /// \brief Compute the weight of a basic block.
503*9880d681SAndroid Build Coastguard Worker ///
504*9880d681SAndroid Build Coastguard Worker /// The weight of basic block \p BB is the maximum weight of all the
505*9880d681SAndroid Build Coastguard Worker /// instructions in BB.
506*9880d681SAndroid Build Coastguard Worker ///
507*9880d681SAndroid Build Coastguard Worker /// \param BB The basic block to query.
508*9880d681SAndroid Build Coastguard Worker ///
509*9880d681SAndroid Build Coastguard Worker /// \returns the weight for \p BB.
510*9880d681SAndroid Build Coastguard Worker ErrorOr<uint64_t>
getBlockWeight(const BasicBlock * BB) const511*9880d681SAndroid Build Coastguard Worker SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const {
512*9880d681SAndroid Build Coastguard Worker   DenseMap<uint64_t, uint64_t> CM;
513*9880d681SAndroid Build Coastguard Worker   for (auto &I : BB->getInstList()) {
514*9880d681SAndroid Build Coastguard Worker     const ErrorOr<uint64_t> &R = getInstWeight(I);
515*9880d681SAndroid Build Coastguard Worker     if (R) CM[R.get()]++;
516*9880d681SAndroid Build Coastguard Worker   }
517*9880d681SAndroid Build Coastguard Worker   if (CM.size() == 0) return std::error_code();
518*9880d681SAndroid Build Coastguard Worker   uint64_t W = 0, C = 0;
519*9880d681SAndroid Build Coastguard Worker   for (const auto &C_W : CM) {
520*9880d681SAndroid Build Coastguard Worker     if (C_W.second == W) {
521*9880d681SAndroid Build Coastguard Worker       C = std::max(C, C_W.first);
522*9880d681SAndroid Build Coastguard Worker     } else if (C_W.second > W) {
523*9880d681SAndroid Build Coastguard Worker       C = C_W.first;
524*9880d681SAndroid Build Coastguard Worker       W = C_W.second;
525*9880d681SAndroid Build Coastguard Worker     }
526*9880d681SAndroid Build Coastguard Worker   }
527*9880d681SAndroid Build Coastguard Worker   return C;
528*9880d681SAndroid Build Coastguard Worker }
529*9880d681SAndroid Build Coastguard Worker 
530*9880d681SAndroid Build Coastguard Worker /// \brief Compute and store the weights of every basic block.
531*9880d681SAndroid Build Coastguard Worker ///
532*9880d681SAndroid Build Coastguard Worker /// This populates the BlockWeights map by computing
533*9880d681SAndroid Build Coastguard Worker /// the weights of every basic block in the CFG.
534*9880d681SAndroid Build Coastguard Worker ///
535*9880d681SAndroid Build Coastguard Worker /// \param F The function to query.
computeBlockWeights(Function & F)536*9880d681SAndroid Build Coastguard Worker bool SampleProfileLoader::computeBlockWeights(Function &F) {
537*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
538*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Block weights\n");
539*9880d681SAndroid Build Coastguard Worker   for (const auto &BB : F) {
540*9880d681SAndroid Build Coastguard Worker     ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
541*9880d681SAndroid Build Coastguard Worker     if (Weight) {
542*9880d681SAndroid Build Coastguard Worker       BlockWeights[&BB] = Weight.get();
543*9880d681SAndroid Build Coastguard Worker       VisitedBlocks.insert(&BB);
544*9880d681SAndroid Build Coastguard Worker       Changed = true;
545*9880d681SAndroid Build Coastguard Worker     }
546*9880d681SAndroid Build Coastguard Worker     DEBUG(printBlockWeight(dbgs(), &BB));
547*9880d681SAndroid Build Coastguard Worker   }
548*9880d681SAndroid Build Coastguard Worker 
549*9880d681SAndroid Build Coastguard Worker   return Changed;
550*9880d681SAndroid Build Coastguard Worker }
551*9880d681SAndroid Build Coastguard Worker 
552*9880d681SAndroid Build Coastguard Worker /// \brief Get the FunctionSamples for a call instruction.
553*9880d681SAndroid Build Coastguard Worker ///
554*9880d681SAndroid Build Coastguard Worker /// The FunctionSamples of a call instruction \p Inst is the inlined
555*9880d681SAndroid Build Coastguard Worker /// instance in which that call instruction is calling to. It contains
556*9880d681SAndroid Build Coastguard Worker /// all samples that resides in the inlined instance. We first find the
557*9880d681SAndroid Build Coastguard Worker /// inlined instance in which the call instruction is from, then we
558*9880d681SAndroid Build Coastguard Worker /// traverse its children to find the callsite with the matching
559*9880d681SAndroid Build Coastguard Worker /// location and callee function name.
560*9880d681SAndroid Build Coastguard Worker ///
561*9880d681SAndroid Build Coastguard Worker /// \param Inst Call instruction to query.
562*9880d681SAndroid Build Coastguard Worker ///
563*9880d681SAndroid Build Coastguard Worker /// \returns The FunctionSamples pointer to the inlined instance.
564*9880d681SAndroid Build Coastguard Worker const FunctionSamples *
findCalleeFunctionSamples(const CallInst & Inst) const565*9880d681SAndroid Build Coastguard Worker SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const {
566*9880d681SAndroid Build Coastguard Worker   const DILocation *DIL = Inst.getDebugLoc();
567*9880d681SAndroid Build Coastguard Worker   if (!DIL) {
568*9880d681SAndroid Build Coastguard Worker     return nullptr;
569*9880d681SAndroid Build Coastguard Worker   }
570*9880d681SAndroid Build Coastguard Worker   DISubprogram *SP = DIL->getScope()->getSubprogram();
571*9880d681SAndroid Build Coastguard Worker   if (!SP)
572*9880d681SAndroid Build Coastguard Worker     return nullptr;
573*9880d681SAndroid Build Coastguard Worker 
574*9880d681SAndroid Build Coastguard Worker   const FunctionSamples *FS = findFunctionSamples(Inst);
575*9880d681SAndroid Build Coastguard Worker   if (FS == nullptr)
576*9880d681SAndroid Build Coastguard Worker     return nullptr;
577*9880d681SAndroid Build Coastguard Worker 
578*9880d681SAndroid Build Coastguard Worker   return FS->findFunctionSamplesAt(LineLocation(
579*9880d681SAndroid Build Coastguard Worker       getOffset(DIL->getLine(), SP->getLine()), DIL->getDiscriminator()));
580*9880d681SAndroid Build Coastguard Worker }
581*9880d681SAndroid Build Coastguard Worker 
582*9880d681SAndroid Build Coastguard Worker /// \brief Get the FunctionSamples for an instruction.
583*9880d681SAndroid Build Coastguard Worker ///
584*9880d681SAndroid Build Coastguard Worker /// The FunctionSamples of an instruction \p Inst is the inlined instance
585*9880d681SAndroid Build Coastguard Worker /// in which that instruction is coming from. We traverse the inline stack
586*9880d681SAndroid Build Coastguard Worker /// of that instruction, and match it with the tree nodes in the profile.
587*9880d681SAndroid Build Coastguard Worker ///
588*9880d681SAndroid Build Coastguard Worker /// \param Inst Instruction to query.
589*9880d681SAndroid Build Coastguard Worker ///
590*9880d681SAndroid Build Coastguard Worker /// \returns the FunctionSamples pointer to the inlined instance.
591*9880d681SAndroid Build Coastguard Worker const FunctionSamples *
findFunctionSamples(const Instruction & Inst) const592*9880d681SAndroid Build Coastguard Worker SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
593*9880d681SAndroid Build Coastguard Worker   SmallVector<LineLocation, 10> S;
594*9880d681SAndroid Build Coastguard Worker   const DILocation *DIL = Inst.getDebugLoc();
595*9880d681SAndroid Build Coastguard Worker   if (!DIL) {
596*9880d681SAndroid Build Coastguard Worker     return Samples;
597*9880d681SAndroid Build Coastguard Worker   }
598*9880d681SAndroid Build Coastguard Worker   for (DIL = DIL->getInlinedAt(); DIL; DIL = DIL->getInlinedAt()) {
599*9880d681SAndroid Build Coastguard Worker     DISubprogram *SP = DIL->getScope()->getSubprogram();
600*9880d681SAndroid Build Coastguard Worker     if (!SP)
601*9880d681SAndroid Build Coastguard Worker       return nullptr;
602*9880d681SAndroid Build Coastguard Worker     S.push_back(LineLocation(getOffset(DIL->getLine(), SP->getLine()),
603*9880d681SAndroid Build Coastguard Worker                              DIL->getDiscriminator()));
604*9880d681SAndroid Build Coastguard Worker   }
605*9880d681SAndroid Build Coastguard Worker   if (S.size() == 0)
606*9880d681SAndroid Build Coastguard Worker     return Samples;
607*9880d681SAndroid Build Coastguard Worker   const FunctionSamples *FS = Samples;
608*9880d681SAndroid Build Coastguard Worker   for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) {
609*9880d681SAndroid Build Coastguard Worker     FS = FS->findFunctionSamplesAt(S[i]);
610*9880d681SAndroid Build Coastguard Worker   }
611*9880d681SAndroid Build Coastguard Worker   return FS;
612*9880d681SAndroid Build Coastguard Worker }
613*9880d681SAndroid Build Coastguard Worker 
614*9880d681SAndroid Build Coastguard Worker 
615*9880d681SAndroid Build Coastguard Worker /// \brief Iteratively inline hot callsites of a function.
616*9880d681SAndroid Build Coastguard Worker ///
617*9880d681SAndroid Build Coastguard Worker /// Iteratively traverse all callsites of the function \p F, and find if
618*9880d681SAndroid Build Coastguard Worker /// the corresponding inlined instance exists and is hot in profile. If
619*9880d681SAndroid Build Coastguard Worker /// it is hot enough, inline the callsites and adds new callsites of the
620*9880d681SAndroid Build Coastguard Worker /// callee into the caller.
621*9880d681SAndroid Build Coastguard Worker ///
622*9880d681SAndroid Build Coastguard Worker /// TODO: investigate the possibility of not invoking InlineFunction directly.
623*9880d681SAndroid Build Coastguard Worker ///
624*9880d681SAndroid Build Coastguard Worker /// \param F function to perform iterative inlining.
625*9880d681SAndroid Build Coastguard Worker ///
626*9880d681SAndroid Build Coastguard Worker /// \returns True if there is any inline happened.
inlineHotFunctions(Function & F)627*9880d681SAndroid Build Coastguard Worker bool SampleProfileLoader::inlineHotFunctions(Function &F) {
628*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
629*9880d681SAndroid Build Coastguard Worker   LLVMContext &Ctx = F.getContext();
630*9880d681SAndroid Build Coastguard Worker   while (true) {
631*9880d681SAndroid Build Coastguard Worker     bool LocalChanged = false;
632*9880d681SAndroid Build Coastguard Worker     SmallVector<CallInst *, 10> CIS;
633*9880d681SAndroid Build Coastguard Worker     for (auto &BB : F) {
634*9880d681SAndroid Build Coastguard Worker       for (auto &I : BB.getInstList()) {
635*9880d681SAndroid Build Coastguard Worker         CallInst *CI = dyn_cast<CallInst>(&I);
636*9880d681SAndroid Build Coastguard Worker         if (CI && callsiteIsHot(Samples, findCalleeFunctionSamples(*CI)))
637*9880d681SAndroid Build Coastguard Worker           CIS.push_back(CI);
638*9880d681SAndroid Build Coastguard Worker       }
639*9880d681SAndroid Build Coastguard Worker     }
640*9880d681SAndroid Build Coastguard Worker     for (auto CI : CIS) {
641*9880d681SAndroid Build Coastguard Worker       InlineFunctionInfo IFI(nullptr, ACT);
642*9880d681SAndroid Build Coastguard Worker       Function *CalledFunction = CI->getCalledFunction();
643*9880d681SAndroid Build Coastguard Worker       DebugLoc DLoc = CI->getDebugLoc();
644*9880d681SAndroid Build Coastguard Worker       uint64_t NumSamples = findCalleeFunctionSamples(*CI)->getTotalSamples();
645*9880d681SAndroid Build Coastguard Worker       if (InlineFunction(CI, IFI)) {
646*9880d681SAndroid Build Coastguard Worker         LocalChanged = true;
647*9880d681SAndroid Build Coastguard Worker         emitOptimizationRemark(Ctx, DEBUG_TYPE, F, DLoc,
648*9880d681SAndroid Build Coastguard Worker                                Twine("inlined hot callee '") +
649*9880d681SAndroid Build Coastguard Worker                                    CalledFunction->getName() + "' with " +
650*9880d681SAndroid Build Coastguard Worker                                    Twine(NumSamples) + " samples into '" +
651*9880d681SAndroid Build Coastguard Worker                                    F.getName() + "'");
652*9880d681SAndroid Build Coastguard Worker       }
653*9880d681SAndroid Build Coastguard Worker     }
654*9880d681SAndroid Build Coastguard Worker     if (LocalChanged) {
655*9880d681SAndroid Build Coastguard Worker       Changed = true;
656*9880d681SAndroid Build Coastguard Worker     } else {
657*9880d681SAndroid Build Coastguard Worker       break;
658*9880d681SAndroid Build Coastguard Worker     }
659*9880d681SAndroid Build Coastguard Worker   }
660*9880d681SAndroid Build Coastguard Worker   return Changed;
661*9880d681SAndroid Build Coastguard Worker }
662*9880d681SAndroid Build Coastguard Worker 
663*9880d681SAndroid Build Coastguard Worker /// \brief Find equivalence classes for the given block.
664*9880d681SAndroid Build Coastguard Worker ///
665*9880d681SAndroid Build Coastguard Worker /// This finds all the blocks that are guaranteed to execute the same
666*9880d681SAndroid Build Coastguard Worker /// number of times as \p BB1. To do this, it traverses all the
667*9880d681SAndroid Build Coastguard Worker /// descendants of \p BB1 in the dominator or post-dominator tree.
668*9880d681SAndroid Build Coastguard Worker ///
669*9880d681SAndroid Build Coastguard Worker /// A block BB2 will be in the same equivalence class as \p BB1 if
670*9880d681SAndroid Build Coastguard Worker /// the following holds:
671*9880d681SAndroid Build Coastguard Worker ///
672*9880d681SAndroid Build Coastguard Worker /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
673*9880d681SAndroid Build Coastguard Worker ///    is a descendant of \p BB1 in the dominator tree, then BB2 should
674*9880d681SAndroid Build Coastguard Worker ///    dominate BB1 in the post-dominator tree.
675*9880d681SAndroid Build Coastguard Worker ///
676*9880d681SAndroid Build Coastguard Worker /// 2- Both BB2 and \p BB1 must be in the same loop.
677*9880d681SAndroid Build Coastguard Worker ///
678*9880d681SAndroid Build Coastguard Worker /// For every block BB2 that meets those two requirements, we set BB2's
679*9880d681SAndroid Build Coastguard Worker /// equivalence class to \p BB1.
680*9880d681SAndroid Build Coastguard Worker ///
681*9880d681SAndroid Build Coastguard Worker /// \param BB1  Block to check.
682*9880d681SAndroid Build Coastguard Worker /// \param Descendants  Descendants of \p BB1 in either the dom or pdom tree.
683*9880d681SAndroid Build Coastguard Worker /// \param DomTree  Opposite dominator tree. If \p Descendants is filled
684*9880d681SAndroid Build Coastguard Worker ///                 with blocks from \p BB1's dominator tree, then
685*9880d681SAndroid Build Coastguard Worker ///                 this is the post-dominator tree, and vice versa.
findEquivalencesFor(BasicBlock * BB1,ArrayRef<BasicBlock * > Descendants,DominatorTreeBase<BasicBlock> * DomTree)686*9880d681SAndroid Build Coastguard Worker void SampleProfileLoader::findEquivalencesFor(
687*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
688*9880d681SAndroid Build Coastguard Worker     DominatorTreeBase<BasicBlock> *DomTree) {
689*9880d681SAndroid Build Coastguard Worker   const BasicBlock *EC = EquivalenceClass[BB1];
690*9880d681SAndroid Build Coastguard Worker   uint64_t Weight = BlockWeights[EC];
691*9880d681SAndroid Build Coastguard Worker   for (const auto *BB2 : Descendants) {
692*9880d681SAndroid Build Coastguard Worker     bool IsDomParent = DomTree->dominates(BB2, BB1);
693*9880d681SAndroid Build Coastguard Worker     bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
694*9880d681SAndroid Build Coastguard Worker     if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
695*9880d681SAndroid Build Coastguard Worker       EquivalenceClass[BB2] = EC;
696*9880d681SAndroid Build Coastguard Worker 
697*9880d681SAndroid Build Coastguard Worker       // If BB2 is heavier than BB1, make BB2 have the same weight
698*9880d681SAndroid Build Coastguard Worker       // as BB1.
699*9880d681SAndroid Build Coastguard Worker       //
700*9880d681SAndroid Build Coastguard Worker       // Note that we don't worry about the opposite situation here
701*9880d681SAndroid Build Coastguard Worker       // (when BB2 is lighter than BB1). We will deal with this
702*9880d681SAndroid Build Coastguard Worker       // during the propagation phase. Right now, we just want to
703*9880d681SAndroid Build Coastguard Worker       // make sure that BB1 has the largest weight of all the
704*9880d681SAndroid Build Coastguard Worker       // members of its equivalence set.
705*9880d681SAndroid Build Coastguard Worker       Weight = std::max(Weight, BlockWeights[BB2]);
706*9880d681SAndroid Build Coastguard Worker     }
707*9880d681SAndroid Build Coastguard Worker   }
708*9880d681SAndroid Build Coastguard Worker   BlockWeights[EC] = Weight;
709*9880d681SAndroid Build Coastguard Worker }
710*9880d681SAndroid Build Coastguard Worker 
711*9880d681SAndroid Build Coastguard Worker /// \brief Find equivalence classes.
712*9880d681SAndroid Build Coastguard Worker ///
713*9880d681SAndroid Build Coastguard Worker /// Since samples may be missing from blocks, we can fill in the gaps by setting
714*9880d681SAndroid Build Coastguard Worker /// the weights of all the blocks in the same equivalence class to the same
715*9880d681SAndroid Build Coastguard Worker /// weight. To compute the concept of equivalence, we use dominance and loop
716*9880d681SAndroid Build Coastguard Worker /// information. Two blocks B1 and B2 are in the same equivalence class if B1
717*9880d681SAndroid Build Coastguard Worker /// dominates B2, B2 post-dominates B1 and both are in the same loop.
718*9880d681SAndroid Build Coastguard Worker ///
719*9880d681SAndroid Build Coastguard Worker /// \param F The function to query.
findEquivalenceClasses(Function & F)720*9880d681SAndroid Build Coastguard Worker void SampleProfileLoader::findEquivalenceClasses(Function &F) {
721*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock *, 8> DominatedBBs;
722*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "\nBlock equivalence classes\n");
723*9880d681SAndroid Build Coastguard Worker   // Find equivalence sets based on dominance and post-dominance information.
724*9880d681SAndroid Build Coastguard Worker   for (auto &BB : F) {
725*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB1 = &BB;
726*9880d681SAndroid Build Coastguard Worker 
727*9880d681SAndroid Build Coastguard Worker     // Compute BB1's equivalence class once.
728*9880d681SAndroid Build Coastguard Worker     if (EquivalenceClass.count(BB1)) {
729*9880d681SAndroid Build Coastguard Worker       DEBUG(printBlockEquivalence(dbgs(), BB1));
730*9880d681SAndroid Build Coastguard Worker       continue;
731*9880d681SAndroid Build Coastguard Worker     }
732*9880d681SAndroid Build Coastguard Worker 
733*9880d681SAndroid Build Coastguard Worker     // By default, blocks are in their own equivalence class.
734*9880d681SAndroid Build Coastguard Worker     EquivalenceClass[BB1] = BB1;
735*9880d681SAndroid Build Coastguard Worker 
736*9880d681SAndroid Build Coastguard Worker     // Traverse all the blocks dominated by BB1. We are looking for
737*9880d681SAndroid Build Coastguard Worker     // every basic block BB2 such that:
738*9880d681SAndroid Build Coastguard Worker     //
739*9880d681SAndroid Build Coastguard Worker     // 1- BB1 dominates BB2.
740*9880d681SAndroid Build Coastguard Worker     // 2- BB2 post-dominates BB1.
741*9880d681SAndroid Build Coastguard Worker     // 3- BB1 and BB2 are in the same loop nest.
742*9880d681SAndroid Build Coastguard Worker     //
743*9880d681SAndroid Build Coastguard Worker     // If all those conditions hold, it means that BB2 is executed
744*9880d681SAndroid Build Coastguard Worker     // as many times as BB1, so they are placed in the same equivalence
745*9880d681SAndroid Build Coastguard Worker     // class by making BB2's equivalence class be BB1.
746*9880d681SAndroid Build Coastguard Worker     DominatedBBs.clear();
747*9880d681SAndroid Build Coastguard Worker     DT->getDescendants(BB1, DominatedBBs);
748*9880d681SAndroid Build Coastguard Worker     findEquivalencesFor(BB1, DominatedBBs, PDT.get());
749*9880d681SAndroid Build Coastguard Worker 
750*9880d681SAndroid Build Coastguard Worker     DEBUG(printBlockEquivalence(dbgs(), BB1));
751*9880d681SAndroid Build Coastguard Worker   }
752*9880d681SAndroid Build Coastguard Worker 
753*9880d681SAndroid Build Coastguard Worker   // Assign weights to equivalence classes.
754*9880d681SAndroid Build Coastguard Worker   //
755*9880d681SAndroid Build Coastguard Worker   // All the basic blocks in the same equivalence class will execute
756*9880d681SAndroid Build Coastguard Worker   // the same number of times. Since we know that the head block in
757*9880d681SAndroid Build Coastguard Worker   // each equivalence class has the largest weight, assign that weight
758*9880d681SAndroid Build Coastguard Worker   // to all the blocks in that equivalence class.
759*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
760*9880d681SAndroid Build Coastguard Worker   for (auto &BI : F) {
761*9880d681SAndroid Build Coastguard Worker     const BasicBlock *BB = &BI;
762*9880d681SAndroid Build Coastguard Worker     const BasicBlock *EquivBB = EquivalenceClass[BB];
763*9880d681SAndroid Build Coastguard Worker     if (BB != EquivBB)
764*9880d681SAndroid Build Coastguard Worker       BlockWeights[BB] = BlockWeights[EquivBB];
765*9880d681SAndroid Build Coastguard Worker     DEBUG(printBlockWeight(dbgs(), BB));
766*9880d681SAndroid Build Coastguard Worker   }
767*9880d681SAndroid Build Coastguard Worker }
768*9880d681SAndroid Build Coastguard Worker 
769*9880d681SAndroid Build Coastguard Worker /// \brief Visit the given edge to decide if it has a valid weight.
770*9880d681SAndroid Build Coastguard Worker ///
771*9880d681SAndroid Build Coastguard Worker /// If \p E has not been visited before, we copy to \p UnknownEdge
772*9880d681SAndroid Build Coastguard Worker /// and increment the count of unknown edges.
773*9880d681SAndroid Build Coastguard Worker ///
774*9880d681SAndroid Build Coastguard Worker /// \param E  Edge to visit.
775*9880d681SAndroid Build Coastguard Worker /// \param NumUnknownEdges  Current number of unknown edges.
776*9880d681SAndroid Build Coastguard Worker /// \param UnknownEdge  Set if E has not been visited before.
777*9880d681SAndroid Build Coastguard Worker ///
778*9880d681SAndroid Build Coastguard Worker /// \returns E's weight, if known. Otherwise, return 0.
visitEdge(Edge E,unsigned * NumUnknownEdges,Edge * UnknownEdge)779*9880d681SAndroid Build Coastguard Worker uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
780*9880d681SAndroid Build Coastguard Worker                                         Edge *UnknownEdge) {
781*9880d681SAndroid Build Coastguard Worker   if (!VisitedEdges.count(E)) {
782*9880d681SAndroid Build Coastguard Worker     (*NumUnknownEdges)++;
783*9880d681SAndroid Build Coastguard Worker     *UnknownEdge = E;
784*9880d681SAndroid Build Coastguard Worker     return 0;
785*9880d681SAndroid Build Coastguard Worker   }
786*9880d681SAndroid Build Coastguard Worker 
787*9880d681SAndroid Build Coastguard Worker   return EdgeWeights[E];
788*9880d681SAndroid Build Coastguard Worker }
789*9880d681SAndroid Build Coastguard Worker 
790*9880d681SAndroid Build Coastguard Worker /// \brief Propagate weights through incoming/outgoing edges.
791*9880d681SAndroid Build Coastguard Worker ///
792*9880d681SAndroid Build Coastguard Worker /// If the weight of a basic block is known, and there is only one edge
793*9880d681SAndroid Build Coastguard Worker /// with an unknown weight, we can calculate the weight of that edge.
794*9880d681SAndroid Build Coastguard Worker ///
795*9880d681SAndroid Build Coastguard Worker /// Similarly, if all the edges have a known count, we can calculate the
796*9880d681SAndroid Build Coastguard Worker /// count of the basic block, if needed.
797*9880d681SAndroid Build Coastguard Worker ///
798*9880d681SAndroid Build Coastguard Worker /// \param F  Function to process.
799*9880d681SAndroid Build Coastguard Worker ///
800*9880d681SAndroid Build Coastguard Worker /// \returns  True if new weights were assigned to edges or blocks.
propagateThroughEdges(Function & F)801*9880d681SAndroid Build Coastguard Worker bool SampleProfileLoader::propagateThroughEdges(Function &F) {
802*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
803*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "\nPropagation through edges\n");
804*9880d681SAndroid Build Coastguard Worker   for (const auto &BI : F) {
805*9880d681SAndroid Build Coastguard Worker     const BasicBlock *BB = &BI;
806*9880d681SAndroid Build Coastguard Worker     const BasicBlock *EC = EquivalenceClass[BB];
807*9880d681SAndroid Build Coastguard Worker 
808*9880d681SAndroid Build Coastguard Worker     // Visit all the predecessor and successor edges to determine
809*9880d681SAndroid Build Coastguard Worker     // which ones have a weight assigned already. Note that it doesn't
810*9880d681SAndroid Build Coastguard Worker     // matter that we only keep track of a single unknown edge. The
811*9880d681SAndroid Build Coastguard Worker     // only case we are interested in handling is when only a single
812*9880d681SAndroid Build Coastguard Worker     // edge is unknown (see setEdgeOrBlockWeight).
813*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0; i < 2; i++) {
814*9880d681SAndroid Build Coastguard Worker       uint64_t TotalWeight = 0;
815*9880d681SAndroid Build Coastguard Worker       unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
816*9880d681SAndroid Build Coastguard Worker       Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
817*9880d681SAndroid Build Coastguard Worker 
818*9880d681SAndroid Build Coastguard Worker       if (i == 0) {
819*9880d681SAndroid Build Coastguard Worker         // First, visit all predecessor edges.
820*9880d681SAndroid Build Coastguard Worker         NumTotalEdges = Predecessors[BB].size();
821*9880d681SAndroid Build Coastguard Worker         for (auto *Pred : Predecessors[BB]) {
822*9880d681SAndroid Build Coastguard Worker           Edge E = std::make_pair(Pred, BB);
823*9880d681SAndroid Build Coastguard Worker           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
824*9880d681SAndroid Build Coastguard Worker           if (E.first == E.second)
825*9880d681SAndroid Build Coastguard Worker             SelfReferentialEdge = E;
826*9880d681SAndroid Build Coastguard Worker         }
827*9880d681SAndroid Build Coastguard Worker         if (NumTotalEdges == 1) {
828*9880d681SAndroid Build Coastguard Worker           SingleEdge = std::make_pair(Predecessors[BB][0], BB);
829*9880d681SAndroid Build Coastguard Worker         }
830*9880d681SAndroid Build Coastguard Worker       } else {
831*9880d681SAndroid Build Coastguard Worker         // On the second round, visit all successor edges.
832*9880d681SAndroid Build Coastguard Worker         NumTotalEdges = Successors[BB].size();
833*9880d681SAndroid Build Coastguard Worker         for (auto *Succ : Successors[BB]) {
834*9880d681SAndroid Build Coastguard Worker           Edge E = std::make_pair(BB, Succ);
835*9880d681SAndroid Build Coastguard Worker           TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
836*9880d681SAndroid Build Coastguard Worker         }
837*9880d681SAndroid Build Coastguard Worker         if (NumTotalEdges == 1) {
838*9880d681SAndroid Build Coastguard Worker           SingleEdge = std::make_pair(BB, Successors[BB][0]);
839*9880d681SAndroid Build Coastguard Worker         }
840*9880d681SAndroid Build Coastguard Worker       }
841*9880d681SAndroid Build Coastguard Worker 
842*9880d681SAndroid Build Coastguard Worker       // After visiting all the edges, there are three cases that we
843*9880d681SAndroid Build Coastguard Worker       // can handle immediately:
844*9880d681SAndroid Build Coastguard Worker       //
845*9880d681SAndroid Build Coastguard Worker       // - All the edge weights are known (i.e., NumUnknownEdges == 0).
846*9880d681SAndroid Build Coastguard Worker       //   In this case, we simply check that the sum of all the edges
847*9880d681SAndroid Build Coastguard Worker       //   is the same as BB's weight. If not, we change BB's weight
848*9880d681SAndroid Build Coastguard Worker       //   to match. Additionally, if BB had not been visited before,
849*9880d681SAndroid Build Coastguard Worker       //   we mark it visited.
850*9880d681SAndroid Build Coastguard Worker       //
851*9880d681SAndroid Build Coastguard Worker       // - Only one edge is unknown and BB has already been visited.
852*9880d681SAndroid Build Coastguard Worker       //   In this case, we can compute the weight of the edge by
853*9880d681SAndroid Build Coastguard Worker       //   subtracting the total block weight from all the known
854*9880d681SAndroid Build Coastguard Worker       //   edge weights. If the edges weight more than BB, then the
855*9880d681SAndroid Build Coastguard Worker       //   edge of the last remaining edge is set to zero.
856*9880d681SAndroid Build Coastguard Worker       //
857*9880d681SAndroid Build Coastguard Worker       // - There exists a self-referential edge and the weight of BB is
858*9880d681SAndroid Build Coastguard Worker       //   known. In this case, this edge can be based on BB's weight.
859*9880d681SAndroid Build Coastguard Worker       //   We add up all the other known edges and set the weight on
860*9880d681SAndroid Build Coastguard Worker       //   the self-referential edge as we did in the previous case.
861*9880d681SAndroid Build Coastguard Worker       //
862*9880d681SAndroid Build Coastguard Worker       // In any other case, we must continue iterating. Eventually,
863*9880d681SAndroid Build Coastguard Worker       // all edges will get a weight, or iteration will stop when
864*9880d681SAndroid Build Coastguard Worker       // it reaches SampleProfileMaxPropagateIterations.
865*9880d681SAndroid Build Coastguard Worker       if (NumUnknownEdges <= 1) {
866*9880d681SAndroid Build Coastguard Worker         uint64_t &BBWeight = BlockWeights[EC];
867*9880d681SAndroid Build Coastguard Worker         if (NumUnknownEdges == 0) {
868*9880d681SAndroid Build Coastguard Worker           if (!VisitedBlocks.count(EC)) {
869*9880d681SAndroid Build Coastguard Worker             // If we already know the weight of all edges, the weight of the
870*9880d681SAndroid Build Coastguard Worker             // basic block can be computed. It should be no larger than the sum
871*9880d681SAndroid Build Coastguard Worker             // of all edge weights.
872*9880d681SAndroid Build Coastguard Worker             if (TotalWeight > BBWeight) {
873*9880d681SAndroid Build Coastguard Worker               BBWeight = TotalWeight;
874*9880d681SAndroid Build Coastguard Worker               Changed = true;
875*9880d681SAndroid Build Coastguard Worker               DEBUG(dbgs() << "All edge weights for " << BB->getName()
876*9880d681SAndroid Build Coastguard Worker                            << " known. Set weight for block: ";
877*9880d681SAndroid Build Coastguard Worker                     printBlockWeight(dbgs(), BB););
878*9880d681SAndroid Build Coastguard Worker             }
879*9880d681SAndroid Build Coastguard Worker           } else if (NumTotalEdges == 1 &&
880*9880d681SAndroid Build Coastguard Worker                      EdgeWeights[SingleEdge] < BlockWeights[EC]) {
881*9880d681SAndroid Build Coastguard Worker             // If there is only one edge for the visited basic block, use the
882*9880d681SAndroid Build Coastguard Worker             // block weight to adjust edge weight if edge weight is smaller.
883*9880d681SAndroid Build Coastguard Worker             EdgeWeights[SingleEdge] = BlockWeights[EC];
884*9880d681SAndroid Build Coastguard Worker             Changed = true;
885*9880d681SAndroid Build Coastguard Worker           }
886*9880d681SAndroid Build Coastguard Worker         } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
887*9880d681SAndroid Build Coastguard Worker           // If there is a single unknown edge and the block has been
888*9880d681SAndroid Build Coastguard Worker           // visited, then we can compute E's weight.
889*9880d681SAndroid Build Coastguard Worker           if (BBWeight >= TotalWeight)
890*9880d681SAndroid Build Coastguard Worker             EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
891*9880d681SAndroid Build Coastguard Worker           else
892*9880d681SAndroid Build Coastguard Worker             EdgeWeights[UnknownEdge] = 0;
893*9880d681SAndroid Build Coastguard Worker           VisitedEdges.insert(UnknownEdge);
894*9880d681SAndroid Build Coastguard Worker           Changed = true;
895*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "Set weight for edge: ";
896*9880d681SAndroid Build Coastguard Worker                 printEdgeWeight(dbgs(), UnknownEdge));
897*9880d681SAndroid Build Coastguard Worker         }
898*9880d681SAndroid Build Coastguard Worker       } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
899*9880d681SAndroid Build Coastguard Worker         uint64_t &BBWeight = BlockWeights[BB];
900*9880d681SAndroid Build Coastguard Worker         // We have a self-referential edge and the weight of BB is known.
901*9880d681SAndroid Build Coastguard Worker         if (BBWeight >= TotalWeight)
902*9880d681SAndroid Build Coastguard Worker           EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
903*9880d681SAndroid Build Coastguard Worker         else
904*9880d681SAndroid Build Coastguard Worker           EdgeWeights[SelfReferentialEdge] = 0;
905*9880d681SAndroid Build Coastguard Worker         VisitedEdges.insert(SelfReferentialEdge);
906*9880d681SAndroid Build Coastguard Worker         Changed = true;
907*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "Set self-referential edge weight to: ";
908*9880d681SAndroid Build Coastguard Worker               printEdgeWeight(dbgs(), SelfReferentialEdge));
909*9880d681SAndroid Build Coastguard Worker       }
910*9880d681SAndroid Build Coastguard Worker     }
911*9880d681SAndroid Build Coastguard Worker   }
912*9880d681SAndroid Build Coastguard Worker 
913*9880d681SAndroid Build Coastguard Worker   return Changed;
914*9880d681SAndroid Build Coastguard Worker }
915*9880d681SAndroid Build Coastguard Worker 
916*9880d681SAndroid Build Coastguard Worker /// \brief Build in/out edge lists for each basic block in the CFG.
917*9880d681SAndroid Build Coastguard Worker ///
918*9880d681SAndroid Build Coastguard Worker /// We are interested in unique edges. If a block B1 has multiple
919*9880d681SAndroid Build Coastguard Worker /// edges to another block B2, we only add a single B1->B2 edge.
buildEdges(Function & F)920*9880d681SAndroid Build Coastguard Worker void SampleProfileLoader::buildEdges(Function &F) {
921*9880d681SAndroid Build Coastguard Worker   for (auto &BI : F) {
922*9880d681SAndroid Build Coastguard Worker     BasicBlock *B1 = &BI;
923*9880d681SAndroid Build Coastguard Worker 
924*9880d681SAndroid Build Coastguard Worker     // Add predecessors for B1.
925*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<BasicBlock *, 16> Visited;
926*9880d681SAndroid Build Coastguard Worker     if (!Predecessors[B1].empty())
927*9880d681SAndroid Build Coastguard Worker       llvm_unreachable("Found a stale predecessors list in a basic block.");
928*9880d681SAndroid Build Coastguard Worker     for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
929*9880d681SAndroid Build Coastguard Worker       BasicBlock *B2 = *PI;
930*9880d681SAndroid Build Coastguard Worker       if (Visited.insert(B2).second)
931*9880d681SAndroid Build Coastguard Worker         Predecessors[B1].push_back(B2);
932*9880d681SAndroid Build Coastguard Worker     }
933*9880d681SAndroid Build Coastguard Worker 
934*9880d681SAndroid Build Coastguard Worker     // Add successors for B1.
935*9880d681SAndroid Build Coastguard Worker     Visited.clear();
936*9880d681SAndroid Build Coastguard Worker     if (!Successors[B1].empty())
937*9880d681SAndroid Build Coastguard Worker       llvm_unreachable("Found a stale successors list in a basic block.");
938*9880d681SAndroid Build Coastguard Worker     for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
939*9880d681SAndroid Build Coastguard Worker       BasicBlock *B2 = *SI;
940*9880d681SAndroid Build Coastguard Worker       if (Visited.insert(B2).second)
941*9880d681SAndroid Build Coastguard Worker         Successors[B1].push_back(B2);
942*9880d681SAndroid Build Coastguard Worker     }
943*9880d681SAndroid Build Coastguard Worker   }
944*9880d681SAndroid Build Coastguard Worker }
945*9880d681SAndroid Build Coastguard Worker 
946*9880d681SAndroid Build Coastguard Worker /// \brief Propagate weights into edges
947*9880d681SAndroid Build Coastguard Worker ///
948*9880d681SAndroid Build Coastguard Worker /// The following rules are applied to every block BB in the CFG:
949*9880d681SAndroid Build Coastguard Worker ///
950*9880d681SAndroid Build Coastguard Worker /// - If BB has a single predecessor/successor, then the weight
951*9880d681SAndroid Build Coastguard Worker ///   of that edge is the weight of the block.
952*9880d681SAndroid Build Coastguard Worker ///
953*9880d681SAndroid Build Coastguard Worker /// - If all incoming or outgoing edges are known except one, and the
954*9880d681SAndroid Build Coastguard Worker ///   weight of the block is already known, the weight of the unknown
955*9880d681SAndroid Build Coastguard Worker ///   edge will be the weight of the block minus the sum of all the known
956*9880d681SAndroid Build Coastguard Worker ///   edges. If the sum of all the known edges is larger than BB's weight,
957*9880d681SAndroid Build Coastguard Worker ///   we set the unknown edge weight to zero.
958*9880d681SAndroid Build Coastguard Worker ///
959*9880d681SAndroid Build Coastguard Worker /// - If there is a self-referential edge, and the weight of the block is
960*9880d681SAndroid Build Coastguard Worker ///   known, the weight for that edge is set to the weight of the block
961*9880d681SAndroid Build Coastguard Worker ///   minus the weight of the other incoming edges to that block (if
962*9880d681SAndroid Build Coastguard Worker ///   known).
propagateWeights(Function & F)963*9880d681SAndroid Build Coastguard Worker void SampleProfileLoader::propagateWeights(Function &F) {
964*9880d681SAndroid Build Coastguard Worker   bool Changed = true;
965*9880d681SAndroid Build Coastguard Worker   unsigned I = 0;
966*9880d681SAndroid Build Coastguard Worker 
967*9880d681SAndroid Build Coastguard Worker   // Add an entry count to the function using the samples gathered
968*9880d681SAndroid Build Coastguard Worker   // at the function entry.
969*9880d681SAndroid Build Coastguard Worker   F.setEntryCount(Samples->getHeadSamples());
970*9880d681SAndroid Build Coastguard Worker 
971*9880d681SAndroid Build Coastguard Worker   // Before propagation starts, build, for each block, a list of
972*9880d681SAndroid Build Coastguard Worker   // unique predecessors and successors. This is necessary to handle
973*9880d681SAndroid Build Coastguard Worker   // identical edges in multiway branches. Since we visit all blocks and all
974*9880d681SAndroid Build Coastguard Worker   // edges of the CFG, it is cleaner to build these lists once at the start
975*9880d681SAndroid Build Coastguard Worker   // of the pass.
976*9880d681SAndroid Build Coastguard Worker   buildEdges(F);
977*9880d681SAndroid Build Coastguard Worker 
978*9880d681SAndroid Build Coastguard Worker   // Propagate until we converge or we go past the iteration limit.
979*9880d681SAndroid Build Coastguard Worker   while (Changed && I++ < SampleProfileMaxPropagateIterations) {
980*9880d681SAndroid Build Coastguard Worker     Changed = propagateThroughEdges(F);
981*9880d681SAndroid Build Coastguard Worker   }
982*9880d681SAndroid Build Coastguard Worker 
983*9880d681SAndroid Build Coastguard Worker   // Generate MD_prof metadata for every branch instruction using the
984*9880d681SAndroid Build Coastguard Worker   // edge weights computed during propagation.
985*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
986*9880d681SAndroid Build Coastguard Worker   LLVMContext &Ctx = F.getContext();
987*9880d681SAndroid Build Coastguard Worker   MDBuilder MDB(Ctx);
988*9880d681SAndroid Build Coastguard Worker   for (auto &BI : F) {
989*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB = &BI;
990*9880d681SAndroid Build Coastguard Worker 
991*9880d681SAndroid Build Coastguard Worker     if (BlockWeights[BB]) {
992*9880d681SAndroid Build Coastguard Worker       for (auto &I : BB->getInstList()) {
993*9880d681SAndroid Build Coastguard Worker         if (CallInst *CI = dyn_cast<CallInst>(&I)) {
994*9880d681SAndroid Build Coastguard Worker           if (!dyn_cast<IntrinsicInst>(&I)) {
995*9880d681SAndroid Build Coastguard Worker             SmallVector<uint32_t, 1> Weights;
996*9880d681SAndroid Build Coastguard Worker             Weights.push_back(BlockWeights[BB]);
997*9880d681SAndroid Build Coastguard Worker             CI->setMetadata(LLVMContext::MD_prof,
998*9880d681SAndroid Build Coastguard Worker                             MDB.createBranchWeights(Weights));
999*9880d681SAndroid Build Coastguard Worker           }
1000*9880d681SAndroid Build Coastguard Worker         }
1001*9880d681SAndroid Build Coastguard Worker       }
1002*9880d681SAndroid Build Coastguard Worker     }
1003*9880d681SAndroid Build Coastguard Worker     TerminatorInst *TI = BB->getTerminator();
1004*9880d681SAndroid Build Coastguard Worker     if (TI->getNumSuccessors() == 1)
1005*9880d681SAndroid Build Coastguard Worker       continue;
1006*9880d681SAndroid Build Coastguard Worker     if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1007*9880d681SAndroid Build Coastguard Worker       continue;
1008*9880d681SAndroid Build Coastguard Worker 
1009*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "\nGetting weights for branch at line "
1010*9880d681SAndroid Build Coastguard Worker                  << TI->getDebugLoc().getLine() << ".\n");
1011*9880d681SAndroid Build Coastguard Worker     SmallVector<uint32_t, 4> Weights;
1012*9880d681SAndroid Build Coastguard Worker     uint32_t MaxWeight = 0;
1013*9880d681SAndroid Build Coastguard Worker     DebugLoc MaxDestLoc;
1014*9880d681SAndroid Build Coastguard Worker     for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1015*9880d681SAndroid Build Coastguard Worker       BasicBlock *Succ = TI->getSuccessor(I);
1016*9880d681SAndroid Build Coastguard Worker       Edge E = std::make_pair(BB, Succ);
1017*9880d681SAndroid Build Coastguard Worker       uint64_t Weight = EdgeWeights[E];
1018*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1019*9880d681SAndroid Build Coastguard Worker       // Use uint32_t saturated arithmetic to adjust the incoming weights,
1020*9880d681SAndroid Build Coastguard Worker       // if needed. Sample counts in profiles are 64-bit unsigned values,
1021*9880d681SAndroid Build Coastguard Worker       // but internally branch weights are expressed as 32-bit values.
1022*9880d681SAndroid Build Coastguard Worker       if (Weight > std::numeric_limits<uint32_t>::max()) {
1023*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1024*9880d681SAndroid Build Coastguard Worker         Weight = std::numeric_limits<uint32_t>::max();
1025*9880d681SAndroid Build Coastguard Worker       }
1026*9880d681SAndroid Build Coastguard Worker       Weights.push_back(static_cast<uint32_t>(Weight));
1027*9880d681SAndroid Build Coastguard Worker       if (Weight != 0) {
1028*9880d681SAndroid Build Coastguard Worker         if (Weight > MaxWeight) {
1029*9880d681SAndroid Build Coastguard Worker           MaxWeight = Weight;
1030*9880d681SAndroid Build Coastguard Worker           MaxDestLoc = Succ->getFirstNonPHIOrDbgOrLifetime()->getDebugLoc();
1031*9880d681SAndroid Build Coastguard Worker         }
1032*9880d681SAndroid Build Coastguard Worker       }
1033*9880d681SAndroid Build Coastguard Worker     }
1034*9880d681SAndroid Build Coastguard Worker 
1035*9880d681SAndroid Build Coastguard Worker     // Only set weights if there is at least one non-zero weight.
1036*9880d681SAndroid Build Coastguard Worker     // In any other case, let the analyzer set weights.
1037*9880d681SAndroid Build Coastguard Worker     if (MaxWeight > 0) {
1038*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1039*9880d681SAndroid Build Coastguard Worker       TI->setMetadata(llvm::LLVMContext::MD_prof,
1040*9880d681SAndroid Build Coastguard Worker                       MDB.createBranchWeights(Weights));
1041*9880d681SAndroid Build Coastguard Worker       DebugLoc BranchLoc = TI->getDebugLoc();
1042*9880d681SAndroid Build Coastguard Worker       emitOptimizationRemark(
1043*9880d681SAndroid Build Coastguard Worker           Ctx, DEBUG_TYPE, F, MaxDestLoc,
1044*9880d681SAndroid Build Coastguard Worker           Twine("most popular destination for conditional branches at ") +
1045*9880d681SAndroid Build Coastguard Worker               ((BranchLoc) ? Twine(BranchLoc->getFilename() + ":" +
1046*9880d681SAndroid Build Coastguard Worker                                    Twine(BranchLoc.getLine()) + ":" +
1047*9880d681SAndroid Build Coastguard Worker                                    Twine(BranchLoc.getCol()))
1048*9880d681SAndroid Build Coastguard Worker                            : Twine("<UNKNOWN LOCATION>")));
1049*9880d681SAndroid Build Coastguard Worker     } else {
1050*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1051*9880d681SAndroid Build Coastguard Worker     }
1052*9880d681SAndroid Build Coastguard Worker   }
1053*9880d681SAndroid Build Coastguard Worker }
1054*9880d681SAndroid Build Coastguard Worker 
1055*9880d681SAndroid Build Coastguard Worker /// \brief Get the line number for the function header.
1056*9880d681SAndroid Build Coastguard Worker ///
1057*9880d681SAndroid Build Coastguard Worker /// This looks up function \p F in the current compilation unit and
1058*9880d681SAndroid Build Coastguard Worker /// retrieves the line number where the function is defined. This is
1059*9880d681SAndroid Build Coastguard Worker /// line 0 for all the samples read from the profile file. Every line
1060*9880d681SAndroid Build Coastguard Worker /// number is relative to this line.
1061*9880d681SAndroid Build Coastguard Worker ///
1062*9880d681SAndroid Build Coastguard Worker /// \param F  Function object to query.
1063*9880d681SAndroid Build Coastguard Worker ///
1064*9880d681SAndroid Build Coastguard Worker /// \returns the line number where \p F is defined. If it returns 0,
1065*9880d681SAndroid Build Coastguard Worker ///          it means that there is no debug information available for \p F.
getFunctionLoc(Function & F)1066*9880d681SAndroid Build Coastguard Worker unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1067*9880d681SAndroid Build Coastguard Worker   if (DISubprogram *S = F.getSubprogram())
1068*9880d681SAndroid Build Coastguard Worker     return S->getLine();
1069*9880d681SAndroid Build Coastguard Worker 
1070*9880d681SAndroid Build Coastguard Worker   // If the start of \p F is missing, emit a diagnostic to inform the user
1071*9880d681SAndroid Build Coastguard Worker   // about the missed opportunity.
1072*9880d681SAndroid Build Coastguard Worker   F.getContext().diagnose(DiagnosticInfoSampleProfile(
1073*9880d681SAndroid Build Coastguard Worker       "No debug information found in function " + F.getName() +
1074*9880d681SAndroid Build Coastguard Worker           ": Function profile not used",
1075*9880d681SAndroid Build Coastguard Worker       DS_Warning));
1076*9880d681SAndroid Build Coastguard Worker   return 0;
1077*9880d681SAndroid Build Coastguard Worker }
1078*9880d681SAndroid Build Coastguard Worker 
computeDominanceAndLoopInfo(Function & F)1079*9880d681SAndroid Build Coastguard Worker void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1080*9880d681SAndroid Build Coastguard Worker   DT.reset(new DominatorTree);
1081*9880d681SAndroid Build Coastguard Worker   DT->recalculate(F);
1082*9880d681SAndroid Build Coastguard Worker 
1083*9880d681SAndroid Build Coastguard Worker   PDT.reset(new DominatorTreeBase<BasicBlock>(true));
1084*9880d681SAndroid Build Coastguard Worker   PDT->recalculate(F);
1085*9880d681SAndroid Build Coastguard Worker 
1086*9880d681SAndroid Build Coastguard Worker   LI.reset(new LoopInfo);
1087*9880d681SAndroid Build Coastguard Worker   LI->analyze(*DT);
1088*9880d681SAndroid Build Coastguard Worker }
1089*9880d681SAndroid Build Coastguard Worker 
1090*9880d681SAndroid Build Coastguard Worker /// \brief Generate branch weight metadata for all branches in \p F.
1091*9880d681SAndroid Build Coastguard Worker ///
1092*9880d681SAndroid Build Coastguard Worker /// Branch weights are computed out of instruction samples using a
1093*9880d681SAndroid Build Coastguard Worker /// propagation heuristic. Propagation proceeds in 3 phases:
1094*9880d681SAndroid Build Coastguard Worker ///
1095*9880d681SAndroid Build Coastguard Worker /// 1- Assignment of block weights. All the basic blocks in the function
1096*9880d681SAndroid Build Coastguard Worker ///    are initial assigned the same weight as their most frequently
1097*9880d681SAndroid Build Coastguard Worker ///    executed instruction.
1098*9880d681SAndroid Build Coastguard Worker ///
1099*9880d681SAndroid Build Coastguard Worker /// 2- Creation of equivalence classes. Since samples may be missing from
1100*9880d681SAndroid Build Coastguard Worker ///    blocks, we can fill in the gaps by setting the weights of all the
1101*9880d681SAndroid Build Coastguard Worker ///    blocks in the same equivalence class to the same weight. To compute
1102*9880d681SAndroid Build Coastguard Worker ///    the concept of equivalence, we use dominance and loop information.
1103*9880d681SAndroid Build Coastguard Worker ///    Two blocks B1 and B2 are in the same equivalence class if B1
1104*9880d681SAndroid Build Coastguard Worker ///    dominates B2, B2 post-dominates B1 and both are in the same loop.
1105*9880d681SAndroid Build Coastguard Worker ///
1106*9880d681SAndroid Build Coastguard Worker /// 3- Propagation of block weights into edges. This uses a simple
1107*9880d681SAndroid Build Coastguard Worker ///    propagation heuristic. The following rules are applied to every
1108*9880d681SAndroid Build Coastguard Worker ///    block BB in the CFG:
1109*9880d681SAndroid Build Coastguard Worker ///
1110*9880d681SAndroid Build Coastguard Worker ///    - If BB has a single predecessor/successor, then the weight
1111*9880d681SAndroid Build Coastguard Worker ///      of that edge is the weight of the block.
1112*9880d681SAndroid Build Coastguard Worker ///
1113*9880d681SAndroid Build Coastguard Worker ///    - If all the edges are known except one, and the weight of the
1114*9880d681SAndroid Build Coastguard Worker ///      block is already known, the weight of the unknown edge will
1115*9880d681SAndroid Build Coastguard Worker ///      be the weight of the block minus the sum of all the known
1116*9880d681SAndroid Build Coastguard Worker ///      edges. If the sum of all the known edges is larger than BB's weight,
1117*9880d681SAndroid Build Coastguard Worker ///      we set the unknown edge weight to zero.
1118*9880d681SAndroid Build Coastguard Worker ///
1119*9880d681SAndroid Build Coastguard Worker ///    - If there is a self-referential edge, and the weight of the block is
1120*9880d681SAndroid Build Coastguard Worker ///      known, the weight for that edge is set to the weight of the block
1121*9880d681SAndroid Build Coastguard Worker ///      minus the weight of the other incoming edges to that block (if
1122*9880d681SAndroid Build Coastguard Worker ///      known).
1123*9880d681SAndroid Build Coastguard Worker ///
1124*9880d681SAndroid Build Coastguard Worker /// Since this propagation is not guaranteed to finalize for every CFG, we
1125*9880d681SAndroid Build Coastguard Worker /// only allow it to proceed for a limited number of iterations (controlled
1126*9880d681SAndroid Build Coastguard Worker /// by -sample-profile-max-propagate-iterations).
1127*9880d681SAndroid Build Coastguard Worker ///
1128*9880d681SAndroid Build Coastguard Worker /// FIXME: Try to replace this propagation heuristic with a scheme
1129*9880d681SAndroid Build Coastguard Worker /// that is guaranteed to finalize. A work-list approach similar to
1130*9880d681SAndroid Build Coastguard Worker /// the standard value propagation algorithm used by SSA-CCP might
1131*9880d681SAndroid Build Coastguard Worker /// work here.
1132*9880d681SAndroid Build Coastguard Worker ///
1133*9880d681SAndroid Build Coastguard Worker /// Once all the branch weights are computed, we emit the MD_prof
1134*9880d681SAndroid Build Coastguard Worker /// metadata on BB using the computed values for each of its branches.
1135*9880d681SAndroid Build Coastguard Worker ///
1136*9880d681SAndroid Build Coastguard Worker /// \param F The function to query.
1137*9880d681SAndroid Build Coastguard Worker ///
1138*9880d681SAndroid Build Coastguard Worker /// \returns true if \p F was modified. Returns false, otherwise.
emitAnnotations(Function & F)1139*9880d681SAndroid Build Coastguard Worker bool SampleProfileLoader::emitAnnotations(Function &F) {
1140*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
1141*9880d681SAndroid Build Coastguard Worker 
1142*9880d681SAndroid Build Coastguard Worker   if (getFunctionLoc(F) == 0)
1143*9880d681SAndroid Build Coastguard Worker     return false;
1144*9880d681SAndroid Build Coastguard Worker 
1145*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
1146*9880d681SAndroid Build Coastguard Worker                << ": " << getFunctionLoc(F) << "\n");
1147*9880d681SAndroid Build Coastguard Worker 
1148*9880d681SAndroid Build Coastguard Worker   Changed |= inlineHotFunctions(F);
1149*9880d681SAndroid Build Coastguard Worker 
1150*9880d681SAndroid Build Coastguard Worker   // Compute basic block weights.
1151*9880d681SAndroid Build Coastguard Worker   Changed |= computeBlockWeights(F);
1152*9880d681SAndroid Build Coastguard Worker 
1153*9880d681SAndroid Build Coastguard Worker   if (Changed) {
1154*9880d681SAndroid Build Coastguard Worker     // Compute dominance and loop info needed for propagation.
1155*9880d681SAndroid Build Coastguard Worker     computeDominanceAndLoopInfo(F);
1156*9880d681SAndroid Build Coastguard Worker 
1157*9880d681SAndroid Build Coastguard Worker     // Find equivalence classes.
1158*9880d681SAndroid Build Coastguard Worker     findEquivalenceClasses(F);
1159*9880d681SAndroid Build Coastguard Worker 
1160*9880d681SAndroid Build Coastguard Worker     // Propagate weights to all edges.
1161*9880d681SAndroid Build Coastguard Worker     propagateWeights(F);
1162*9880d681SAndroid Build Coastguard Worker   }
1163*9880d681SAndroid Build Coastguard Worker 
1164*9880d681SAndroid Build Coastguard Worker   // If coverage checking was requested, compute it now.
1165*9880d681SAndroid Build Coastguard Worker   if (SampleProfileRecordCoverage) {
1166*9880d681SAndroid Build Coastguard Worker     unsigned Used = CoverageTracker.countUsedRecords(Samples);
1167*9880d681SAndroid Build Coastguard Worker     unsigned Total = CoverageTracker.countBodyRecords(Samples);
1168*9880d681SAndroid Build Coastguard Worker     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1169*9880d681SAndroid Build Coastguard Worker     if (Coverage < SampleProfileRecordCoverage) {
1170*9880d681SAndroid Build Coastguard Worker       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1171*9880d681SAndroid Build Coastguard Worker           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1172*9880d681SAndroid Build Coastguard Worker           Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1173*9880d681SAndroid Build Coastguard Worker               Twine(Coverage) + "%) were applied",
1174*9880d681SAndroid Build Coastguard Worker           DS_Warning));
1175*9880d681SAndroid Build Coastguard Worker     }
1176*9880d681SAndroid Build Coastguard Worker   }
1177*9880d681SAndroid Build Coastguard Worker 
1178*9880d681SAndroid Build Coastguard Worker   if (SampleProfileSampleCoverage) {
1179*9880d681SAndroid Build Coastguard Worker     uint64_t Used = CoverageTracker.getTotalUsedSamples();
1180*9880d681SAndroid Build Coastguard Worker     uint64_t Total = CoverageTracker.countBodySamples(Samples);
1181*9880d681SAndroid Build Coastguard Worker     unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1182*9880d681SAndroid Build Coastguard Worker     if (Coverage < SampleProfileSampleCoverage) {
1183*9880d681SAndroid Build Coastguard Worker       F.getContext().diagnose(DiagnosticInfoSampleProfile(
1184*9880d681SAndroid Build Coastguard Worker           F.getSubprogram()->getFilename(), getFunctionLoc(F),
1185*9880d681SAndroid Build Coastguard Worker           Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1186*9880d681SAndroid Build Coastguard Worker               Twine(Coverage) + "%) were applied",
1187*9880d681SAndroid Build Coastguard Worker           DS_Warning));
1188*9880d681SAndroid Build Coastguard Worker     }
1189*9880d681SAndroid Build Coastguard Worker   }
1190*9880d681SAndroid Build Coastguard Worker   return Changed;
1191*9880d681SAndroid Build Coastguard Worker }
1192*9880d681SAndroid Build Coastguard Worker 
1193*9880d681SAndroid Build Coastguard Worker char SampleProfileLoaderLegacyPass::ID = 0;
1194*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1195*9880d681SAndroid Build Coastguard Worker                 "Sample Profile loader", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)1196*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1197*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1198*9880d681SAndroid Build Coastguard Worker                 "Sample Profile loader", false, false)
1199*9880d681SAndroid Build Coastguard Worker 
1200*9880d681SAndroid Build Coastguard Worker bool SampleProfileLoader::doInitialization(Module &M) {
1201*9880d681SAndroid Build Coastguard Worker   auto &Ctx = M.getContext();
1202*9880d681SAndroid Build Coastguard Worker   auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
1203*9880d681SAndroid Build Coastguard Worker   if (std::error_code EC = ReaderOrErr.getError()) {
1204*9880d681SAndroid Build Coastguard Worker     std::string Msg = "Could not open profile: " + EC.message();
1205*9880d681SAndroid Build Coastguard Worker     Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1206*9880d681SAndroid Build Coastguard Worker     return false;
1207*9880d681SAndroid Build Coastguard Worker   }
1208*9880d681SAndroid Build Coastguard Worker   Reader = std::move(ReaderOrErr.get());
1209*9880d681SAndroid Build Coastguard Worker   ProfileIsValid = (Reader->read() == sampleprof_error::success);
1210*9880d681SAndroid Build Coastguard Worker   return true;
1211*9880d681SAndroid Build Coastguard Worker }
1212*9880d681SAndroid Build Coastguard Worker 
createSampleProfileLoaderPass()1213*9880d681SAndroid Build Coastguard Worker ModulePass *llvm::createSampleProfileLoaderPass() {
1214*9880d681SAndroid Build Coastguard Worker   return new SampleProfileLoaderLegacyPass(SampleProfileFile);
1215*9880d681SAndroid Build Coastguard Worker }
1216*9880d681SAndroid Build Coastguard Worker 
createSampleProfileLoaderPass(StringRef Name)1217*9880d681SAndroid Build Coastguard Worker ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1218*9880d681SAndroid Build Coastguard Worker   return new SampleProfileLoaderLegacyPass(Name);
1219*9880d681SAndroid Build Coastguard Worker }
1220*9880d681SAndroid Build Coastguard Worker 
runOnModule(Module & M)1221*9880d681SAndroid Build Coastguard Worker bool SampleProfileLoader::runOnModule(Module &M) {
1222*9880d681SAndroid Build Coastguard Worker   if (!ProfileIsValid)
1223*9880d681SAndroid Build Coastguard Worker     return false;
1224*9880d681SAndroid Build Coastguard Worker 
1225*9880d681SAndroid Build Coastguard Worker   // Compute the total number of samples collected in this profile.
1226*9880d681SAndroid Build Coastguard Worker   for (const auto &I : Reader->getProfiles())
1227*9880d681SAndroid Build Coastguard Worker     TotalCollectedSamples += I.second.getTotalSamples();
1228*9880d681SAndroid Build Coastguard Worker 
1229*9880d681SAndroid Build Coastguard Worker   bool retval = false;
1230*9880d681SAndroid Build Coastguard Worker   for (auto &F : M)
1231*9880d681SAndroid Build Coastguard Worker     if (!F.isDeclaration()) {
1232*9880d681SAndroid Build Coastguard Worker       clearFunctionData();
1233*9880d681SAndroid Build Coastguard Worker       retval |= runOnFunction(F);
1234*9880d681SAndroid Build Coastguard Worker     }
1235*9880d681SAndroid Build Coastguard Worker   M.setProfileSummary(Reader->getSummary().getMD(M.getContext()));
1236*9880d681SAndroid Build Coastguard Worker   return retval;
1237*9880d681SAndroid Build Coastguard Worker }
1238*9880d681SAndroid Build Coastguard Worker 
runOnModule(Module & M)1239*9880d681SAndroid Build Coastguard Worker bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1240*9880d681SAndroid Build Coastguard Worker   // FIXME: pass in AssumptionCache correctly for the new pass manager.
1241*9880d681SAndroid Build Coastguard Worker   SampleLoader.setACT(&getAnalysis<AssumptionCacheTracker>());
1242*9880d681SAndroid Build Coastguard Worker   return SampleLoader.runOnModule(M);
1243*9880d681SAndroid Build Coastguard Worker }
1244*9880d681SAndroid Build Coastguard Worker 
runOnFunction(Function & F)1245*9880d681SAndroid Build Coastguard Worker bool SampleProfileLoader::runOnFunction(Function &F) {
1246*9880d681SAndroid Build Coastguard Worker   F.setEntryCount(0);
1247*9880d681SAndroid Build Coastguard Worker   Samples = Reader->getSamplesFor(F);
1248*9880d681SAndroid Build Coastguard Worker   if (!Samples->empty())
1249*9880d681SAndroid Build Coastguard Worker     return emitAnnotations(F);
1250*9880d681SAndroid Build Coastguard Worker   return false;
1251*9880d681SAndroid Build Coastguard Worker }
1252*9880d681SAndroid Build Coastguard Worker 
run(Module & M,AnalysisManager<Module> & AM)1253*9880d681SAndroid Build Coastguard Worker PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1254*9880d681SAndroid Build Coastguard Worker                                                AnalysisManager<Module> &AM) {
1255*9880d681SAndroid Build Coastguard Worker 
1256*9880d681SAndroid Build Coastguard Worker   SampleProfileLoader SampleLoader(SampleProfileFile);
1257*9880d681SAndroid Build Coastguard Worker 
1258*9880d681SAndroid Build Coastguard Worker   SampleLoader.doInitialization(M);
1259*9880d681SAndroid Build Coastguard Worker 
1260*9880d681SAndroid Build Coastguard Worker   if (!SampleLoader.runOnModule(M))
1261*9880d681SAndroid Build Coastguard Worker     return PreservedAnalyses::all();
1262*9880d681SAndroid Build Coastguard Worker 
1263*9880d681SAndroid Build Coastguard Worker   return PreservedAnalyses::none();
1264*9880d681SAndroid Build Coastguard Worker }
1265