blob: 1c53a82cf8a98cc22efdfebd7fe7ebbc77a802ff [file] [log] [blame]
Diego Novillo8d6568b2013-11-13 12:22:21 +00001//===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SampleProfileLoader transformation. This pass
11// reads a profile file generated by a sampling profiler (e.g. Linux Perf -
12// http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
13// profile information in the given profile.
14//
15// This pass generates branch weight annotations on the IR:
16//
17// - prof: Represents branch weights. This annotation is added to branches
18// to indicate the weights of each edge coming out of the branch.
19// The weight of each edge is the weight of the target block for
20// that edge. The weight of a block B is computed as the maximum
21// number of samples found in B.
22//
23//===----------------------------------------------------------------------===//
24
David Blaikie301627f2018-03-22 22:42:44 +000025#include "llvm/Transforms/IPO/SampleProfile.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000026#include "llvm/ADT/ArrayRef.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000027#include "llvm/ADT/DenseMap.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000028#include "llvm/ADT/DenseSet.h"
29#include "llvm/ADT/None.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000030#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000031#include "llvm/ADT/SmallSet.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000032#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringMap.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000034#include "llvm/ADT/StringRef.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000035#include "llvm/ADT/Twine.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000036#include "llvm/Analysis/AssumptionCache.h"
Dehao Chen3a81f842017-09-14 17:29:56 +000037#include "llvm/Analysis/InlineCost.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000038#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000039#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Jakub Kuderskief33edd2018-05-23 17:29:21 +000040#include "llvm/Analysis/PostDominators.h"
Wei Mi0c2f6be2018-05-10 23:02:27 +000041#include "llvm/Analysis/ProfileSummaryInfo.h"
Dehao Chen3a81f842017-09-14 17:29:56 +000042#include "llvm/Analysis/TargetTransformInfo.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000043#include "llvm/IR/BasicBlock.h"
44#include "llvm/IR/CFG.h"
45#include "llvm/IR/CallSite.h"
46#include "llvm/IR/DebugInfoMetadata.h"
47#include "llvm/IR/DebugLoc.h"
Diego Novilloa32aa322014-03-14 21:58:59 +000048#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000049#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000050#include "llvm/IR/Function.h"
Dehao Chen77079002017-01-20 22:56:07 +000051#include "llvm/IR/GlobalValue.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000052#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000054#include "llvm/IR/Instructions.h"
Xinliang David Lid38392e2016-05-27 23:20:16 +000055#include "llvm/IR/IntrinsicInst.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000056#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000057#include "llvm/IR/MDBuilder.h"
58#include "llvm/IR/Module.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000059#include "llvm/IR/PassManager.h"
Dehao Chen1ea8bd82017-04-17 22:23:05 +000060#include "llvm/IR/ValueSymbolTable.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000061#include "llvm/Pass.h"
Dehao Chen77079002017-01-20 22:56:07 +000062#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000063#include "llvm/ProfileData/SampleProf.h"
Diego Novillode1ab262014-09-09 12:40:50 +000064#include "llvm/ProfileData/SampleProfReader.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000065#include "llvm/Support/Casting.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000066#include "llvm/Support/CommandLine.h"
67#include "llvm/Support/Debug.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000068#include "llvm/Support/ErrorHandling.h"
Dehao Chen8e7df832015-09-29 18:28:15 +000069#include "llvm/Support/ErrorOr.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000070#include "llvm/Support/GenericDomTree.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000071#include "llvm/Support/raw_ostream.h"
Diego Novillo4d711132015-08-25 15:25:11 +000072#include "llvm/Transforms/IPO.h"
Dehao Chen274df5e2017-01-31 17:49:37 +000073#include "llvm/Transforms/Instrumentation.h"
Matthew Simpsone363d2c2017-12-06 21:22:54 +000074#include "llvm/Transforms/Utils/CallPromotionUtils.h"
Dehao Chen57d1dda2016-03-03 18:09:32 +000075#include "llvm/Transforms/Utils/Cloning.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000076#include <algorithm>
77#include <cassert>
78#include <cstdint>
79#include <functional>
80#include <limits>
81#include <map>
82#include <memory>
83#include <string>
84#include <system_error>
85#include <utility>
86#include <vector>
Diego Novillo8d6568b2013-11-13 12:22:21 +000087
88using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000089using namespace sampleprof;
Easwaran Ramane5b8de22018-01-17 22:24:23 +000090using ProfileCount = Function::ProfileCount;
Chandler Carruth964daaa2014-04-22 02:55:47 +000091#define DEBUG_TYPE "sample-profile"
92
Diego Novillo8d6568b2013-11-13 12:22:21 +000093// Command line option to specify the file to read samples from. This is
94// mainly used for debugging.
95static cl::opt<std::string> SampleProfileFile(
96 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
97 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
Eugene Zelenkof27d1612017-10-19 21:21:30 +000098
Diego Novillo0accb3d2014-01-10 23:23:46 +000099static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
100 "sample-profile-max-propagate-iterations", cl::init(100),
101 cl::desc("Maximum number of iterations to go through when propagating "
102 "sample block/edge weights through the CFG."));
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000103
Diego Novillo243ea6a2015-11-23 20:12:21 +0000104static cl::opt<unsigned> SampleProfileRecordCoverage(
105 "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
106 cl::desc("Emit a warning if less than N% of records in the input profile "
107 "are matched to the IR."));
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000108
Diego Novillo243ea6a2015-11-23 20:12:21 +0000109static cl::opt<unsigned> SampleProfileSampleCoverage(
110 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000111 cl::desc("Emit a warning if less than N% of samples in the input profile "
112 "are matched to the IR."));
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000113
Diego Novillo8d6568b2013-11-13 12:22:21 +0000114namespace {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000115
116using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
117using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
118using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
119using EdgeWeightMap = DenseMap<Edge, uint64_t>;
120using BlockEdgeMap =
121 DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000122
Dehao Chen0f35fa92016-12-13 22:13:18 +0000123class SampleCoverageTracker {
124public:
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000125 SampleCoverageTracker() = default;
Dehao Chen0f35fa92016-12-13 22:13:18 +0000126
127 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
128 uint32_t Discriminator, uint64_t Samples);
129 unsigned computeCoverage(unsigned Used, unsigned Total) const;
Wei Mi0c2f6be2018-05-10 23:02:27 +0000130 unsigned countUsedRecords(const FunctionSamples *FS,
131 ProfileSummaryInfo *PSI) const;
132 unsigned countBodyRecords(const FunctionSamples *FS,
133 ProfileSummaryInfo *PSI) const;
Dehao Chen0f35fa92016-12-13 22:13:18 +0000134 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
Wei Mi0c2f6be2018-05-10 23:02:27 +0000135 uint64_t countBodySamples(const FunctionSamples *FS,
136 ProfileSummaryInfo *PSI) const;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000137
Dehao Chen0f35fa92016-12-13 22:13:18 +0000138 void clear() {
139 SampleCoverage.clear();
140 TotalUsedSamples = 0;
141 }
142
143private:
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000144 using BodySampleCoverageMap = std::map<LineLocation, unsigned>;
145 using FunctionSamplesCoverageMap =
146 DenseMap<const FunctionSamples *, BodySampleCoverageMap>;
Dehao Chen0f35fa92016-12-13 22:13:18 +0000147
148 /// Coverage map for sampling records.
149 ///
150 /// This map keeps a record of sampling records that have been matched to
151 /// an IR instruction. This is used to detect some form of staleness in
152 /// profiles (see flag -sample-profile-check-coverage).
153 ///
154 /// Each entry in the map corresponds to a FunctionSamples instance. This is
155 /// another map that counts how many times the sample record at the
156 /// given location has been used.
157 FunctionSamplesCoverageMap SampleCoverage;
158
159 /// Number of samples used from the profile.
160 ///
161 /// When a sampling record is used for the first time, the samples from
162 /// that record are added to this accumulator. Coverage is later computed
163 /// based on the total number of samples available in this function and
164 /// its callsites.
165 ///
166 /// Note that this accumulator tracks samples used from a single function
167 /// and all the inlined callsites. Strictly, we should have a map of counters
168 /// keyed by FunctionSamples pointers, but these stats are cleared after
169 /// every function, so we just need to keep a single counter.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000170 uint64_t TotalUsedSamples = 0;
Dehao Chen0f35fa92016-12-13 22:13:18 +0000171};
172
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000173/// Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000174///
Diego Novillode1ab262014-09-09 12:40:50 +0000175/// This pass reads profile data from the file specified by
176/// -sample-profile-file and annotates every affected function with the
177/// profile information found in that file.
Xinliang David Lie897edb2016-05-27 22:30:44 +0000178class SampleProfileLoader {
Diego Novilloc0dd1032013-11-26 20:37:33 +0000179public:
Dehao Chenf3ed14d2017-09-12 21:55:55 +0000180 SampleProfileLoader(
Dehao Chend26dae02017-10-01 05:24:51 +0000181 StringRef Name, bool IsThinLTOPreLink,
Dehao Chen3a81f842017-09-14 17:29:56 +0000182 std::function<AssumptionCache &(Function &)> GetAssumptionCache,
183 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo)
Benjamin Kramer24cb28b2017-12-28 18:10:41 +0000184 : GetAC(std::move(GetAssumptionCache)),
185 GetTTI(std::move(GetTargetTransformInfo)), Filename(Name),
186 IsThinLTOPreLink(IsThinLTOPreLink) {}
Diego Novillode1ab262014-09-09 12:40:50 +0000187
Xinliang David Lie897edb2016-05-27 22:30:44 +0000188 bool doInitialization(Module &M);
Wei Mi0c2f6be2018-05-10 23:02:27 +0000189 bool runOnModule(Module &M, ModuleAnalysisManager *AM,
190 ProfileSummaryInfo *_PSI);
Diego Novillode1ab262014-09-09 12:40:50 +0000191
192 void dump() { Reader->dump(); }
193
Diego Novillode1ab262014-09-09 12:40:50 +0000194protected:
Eli Friedman51cf2602017-08-11 21:12:04 +0000195 bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000196 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000197 bool emitAnnotations(Function &F);
Dehao Chen0f35fa92016-12-13 22:13:18 +0000198 ErrorOr<uint64_t> getInstWeight(const Instruction &I);
199 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB);
Dehao Chen41cde0b2016-09-18 23:11:37 +0000200 const FunctionSamples *findCalleeFunctionSamples(const Instruction &I) const;
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000201 std::vector<const FunctionSamples *>
Dehao Chen3f56a052017-10-10 21:13:50 +0000202 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
Dehao Chen67226882015-09-30 00:42:46 +0000203 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
Dehao Chen4f5d8302017-09-30 20:46:15 +0000204 bool inlineCallInstruction(Instruction *I);
Dehao Chena60cdd32017-02-28 18:09:44 +0000205 bool inlineHotFunctions(Function &F,
Dehao Chenc6c051f2017-11-01 20:26:47 +0000206 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000207 void printEdgeWeight(raw_ostream &OS, Edge E);
Dehao Chen8e7df832015-09-29 18:28:15 +0000208 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
209 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000210 bool computeBlockWeights(Function &F);
211 void findEquivalenceClasses(Function &F);
Jakub Kuderskib292c222017-07-14 18:26:09 +0000212 template <bool IsPostDom>
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000213 void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Jakub Kuderskib292c222017-07-14 18:26:09 +0000214 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree);
215
Diego Novillo0accb3d2014-01-10 23:23:46 +0000216 void propagateWeights(Function &F);
Diego Novillo38be3332015-10-15 16:36:21 +0000217 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000218 void buildEdges(Function &F);
Dehao Chenc0a1e432016-08-12 16:22:12 +0000219 bool propagateThroughEdges(Function &F, bool UpdateBlockCount);
Diego Novillo7732ae42015-08-26 20:00:27 +0000220 void computeDominanceAndLoopInfo(Function &F);
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000221 void clearFunctionData();
Diego Novilloc0dd1032013-11-26 20:37:33 +0000222
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000223 /// Map basic blocks to their computed weights.
Diego Novilloc0dd1032013-11-26 20:37:33 +0000224 ///
225 /// The weight of a basic block is defined to be the maximum
226 /// of all the instruction weights in that block.
227 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000228
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000229 /// Map edges to their computed weights.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000230 ///
231 /// Edge weights are computed by propagating basic block weights in
232 /// SampleProfile::propagateWeights.
233 EdgeWeightMap EdgeWeights;
234
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000235 /// Set of visited blocks during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000236 SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000237
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000238 /// Set of visited edges during propagation.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000239 SmallSet<Edge, 32> VisitedEdges;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000240
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000241 /// Equivalence classes for block weights.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000242 ///
243 /// Two blocks BB1 and BB2 are in the same equivalence class if they
244 /// dominate and post-dominate each other, and they are in the same loop
245 /// nest. When this happens, the two blocks are guaranteed to execute
246 /// the same number of times.
247 EquivalenceClassMap EquivalenceClass;
248
Dehao Chen1ea8bd82017-04-17 22:23:05 +0000249 /// Map from function name to Function *. Used to find the function from
250 /// the function name. If the function name contains suffix, additional
251 /// entry is added to map from the stripped name to the function if there
252 /// is one-to-one mapping.
253 StringMap<Function *> SymbolMap;
254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000255 /// Dominance, post-dominance and loop information.
Diego Novillo7732ae42015-08-26 20:00:27 +0000256 std::unique_ptr<DominatorTree> DT;
Jakub Kuderskief33edd2018-05-23 17:29:21 +0000257 std::unique_ptr<PostDominatorTree> PDT;
Diego Novillo7732ae42015-08-26 20:00:27 +0000258 std::unique_ptr<LoopInfo> LI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000259
Dehao Chenf3ed14d2017-09-12 21:55:55 +0000260 std::function<AssumptionCache &(Function &)> GetAC;
Dehao Chen3a81f842017-09-14 17:29:56 +0000261 std::function<TargetTransformInfo &(Function &)> GetTTI;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000262
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000263 /// Predecessors for each basic block in the CFG.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000264 BlockEdgeMap Predecessors;
265
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000266 /// Successors for each basic block in the CFG.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000267 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000268
Dehao Chen0f35fa92016-12-13 22:13:18 +0000269 SampleCoverageTracker CoverageTracker;
270
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000271 /// Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000272 std::unique_ptr<SampleProfileReader> Reader;
273
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000274 /// Samples collected for the body of this function.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000275 FunctionSamples *Samples = nullptr;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000276
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000277 /// Name of the profile file to load.
Dehao Chenfb699612016-12-14 22:03:08 +0000278 std::string Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000279
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000280 /// Flag indicating whether the profile input loaded successfully.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000281 bool ProfileIsValid = false;
Diego Novillo84f06cc2015-11-27 23:14:51 +0000282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000283 /// Flag indicating if the pass is invoked in ThinLTO compile phase.
Dehao Chend26dae02017-10-01 05:24:51 +0000284 ///
285 /// In this phase, in annotation, we should not promote indirect calls.
286 /// Instead, we will mark GUIDs that needs to be annotated to the function.
287 bool IsThinLTOPreLink;
288
Wei Mi0c2f6be2018-05-10 23:02:27 +0000289 /// Profile Summary Info computed from sample profile.
290 ProfileSummaryInfo *PSI = nullptr;
291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292 /// Total number of samples collected in this profile.
Diego Novillo84f06cc2015-11-27 23:14:51 +0000293 ///
294 /// This is the sum of all the samples collected in all the functions executed
295 /// at runtime.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000296 uint64_t TotalCollectedSamples = 0;
Eli Friedman51cf2602017-08-11 21:12:04 +0000297
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000298 /// Optimization Remark Emitter used to emit diagnostic remarks.
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000299 OptimizationRemarkEmitter *ORE = nullptr;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000300};
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000301
Xinliang David Lie897edb2016-05-27 22:30:44 +0000302class SampleProfileLoaderLegacyPass : public ModulePass {
303public:
304 // Class identification, replacement for typeinfo
305 static char ID;
306
Dehao Chend26dae02017-10-01 05:24:51 +0000307 SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile,
308 bool IsThinLTOPreLink = false)
309 : ModulePass(ID), SampleLoader(Name, IsThinLTOPreLink,
Dehao Chenf3ed14d2017-09-12 21:55:55 +0000310 [&](Function &F) -> AssumptionCache & {
311 return ACT->getAssumptionCache(F);
Dehao Chen3a81f842017-09-14 17:29:56 +0000312 },
313 [&](Function &F) -> TargetTransformInfo & {
314 return TTIWP->getTTI(F);
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000315 }) {
Xinliang David Lie897edb2016-05-27 22:30:44 +0000316 initializeSampleProfileLoaderLegacyPassPass(
317 *PassRegistry::getPassRegistry());
318 }
319
320 void dump() { SampleLoader.dump(); }
321
322 bool doInitialization(Module &M) override {
323 return SampleLoader.doInitialization(M);
324 }
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000325
Mehdi Amini117296c2016-10-01 02:56:57 +0000326 StringRef getPassName() const override { return "Sample profile pass"; }
Xinliang David Lie897edb2016-05-27 22:30:44 +0000327 bool runOnModule(Module &M) override;
328
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000329 void getAnalysisUsage(AnalysisUsage &AU) const override {
330 AU.addRequired<AssumptionCacheTracker>();
Dehao Chen3a81f842017-09-14 17:29:56 +0000331 AU.addRequired<TargetTransformInfoWrapperPass>();
Wei Mi0c2f6be2018-05-10 23:02:27 +0000332 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000333 }
334
Xinliang David Lie897edb2016-05-27 22:30:44 +0000335private:
336 SampleProfileLoader SampleLoader;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000337 AssumptionCacheTracker *ACT = nullptr;
338 TargetTransformInfoWrapperPass *TTIWP = nullptr;
Xinliang David Lie897edb2016-05-27 22:30:44 +0000339};
340
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000341} // end anonymous namespace
342
Wei Mi0c2f6be2018-05-10 23:02:27 +0000343/// Return true if the given callsite is hot wrt to hot cutoff threshold.
Diego Novillo0b6985a2015-11-24 22:38:37 +0000344///
345/// Functions that were inlined in the original binary will be represented
346/// in the inline stack in the sample profile. If the profile shows that
347/// the original inline decision was "good" (i.e., the callsite is executed
348/// frequently), then we will recreate the inline decision and apply the
349/// profile from the inlined callsite.
350///
Wei Mi0c2f6be2018-05-10 23:02:27 +0000351/// To decide whether an inlined callsite is hot, we compare the callsite
352/// sample count with the hot cutoff computed by ProfileSummaryInfo, it is
353/// regarded as hot if the count is above the cutoff value.
354static bool callsiteIsHot(const FunctionSamples *CallsiteFS,
355 ProfileSummaryInfo *PSI) {
Diego Novillo0b6985a2015-11-24 22:38:37 +0000356 if (!CallsiteFS)
357 return false; // The callsite was not inlined in the original binary.
358
Wei Mi0c2f6be2018-05-10 23:02:27 +0000359 assert(PSI && "PSI is expected to be non null");
Diego Novillo0b6985a2015-11-24 22:38:37 +0000360 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
Wei Mi0c2f6be2018-05-10 23:02:27 +0000361 return PSI->isHotCount(CallsiteTotalSamples);
Diego Novillo0b6985a2015-11-24 22:38:37 +0000362}
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000363
364/// Mark as used the sample record for the given function samples at
365/// (LineOffset, Discriminator).
Diego Novillof9ed08e2015-10-31 21:53:58 +0000366///
367/// \returns true if this is the first time we mark the given record.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000368bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000369 uint32_t LineOffset,
Diego Novillo243ea6a2015-11-23 20:12:21 +0000370 uint32_t Discriminator,
371 uint64_t Samples) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000372 LineLocation Loc(LineOffset, Discriminator);
Diego Novillo243ea6a2015-11-23 20:12:21 +0000373 unsigned &Count = SampleCoverage[FS][Loc];
374 bool FirstTime = (++Count == 1);
375 if (FirstTime)
376 TotalUsedSamples += Samples;
377 return FirstTime;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000378}
379
380/// Return the number of sample records that were applied from this profile.
Diego Novillo0b6985a2015-11-24 22:38:37 +0000381///
382/// This count does not include records from cold inlined callsites.
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000383unsigned
Wei Mi0c2f6be2018-05-10 23:02:27 +0000384SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS,
385 ProfileSummaryInfo *PSI) const {
Diego Novillo243ea6a2015-11-23 20:12:21 +0000386 auto I = SampleCoverage.find(FS);
Diego Novillo5fb49e52015-11-20 21:46:38 +0000387
Diego Novillo243ea6a2015-11-23 20:12:21 +0000388 // The size of the coverage map for FS represents the number of records
Diego Novillo5fb49e52015-11-20 21:46:38 +0000389 // that were marked used at least once.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000390 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
Diego Novillo5fb49e52015-11-20 21:46:38 +0000391
392 // If there are inlined callsites in this function, count the samples found
393 // in the respective bodies. However, do not bother counting callees with 0
394 // total samples, these are callees that were never invoked at runtime.
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000395 for (const auto &I : FS->getCallsiteSamples())
396 for (const auto &J : I.second) {
397 const FunctionSamples *CalleeSamples = &J.second;
Wei Mi0c2f6be2018-05-10 23:02:27 +0000398 if (callsiteIsHot(CalleeSamples, PSI))
399 Count += countUsedRecords(CalleeSamples, PSI);
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000400 }
Diego Novillo5fb49e52015-11-20 21:46:38 +0000401
Diego Novillof9ed08e2015-10-31 21:53:58 +0000402 return Count;
403}
404
405/// Return the number of sample records in the body of this profile.
406///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000407/// This count does not include records from cold inlined callsites.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000408unsigned
Wei Mi0c2f6be2018-05-10 23:02:27 +0000409SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS,
410 ProfileSummaryInfo *PSI) const {
Diego Novillo243ea6a2015-11-23 20:12:21 +0000411 unsigned Count = FS->getBodySamples().size();
Diego Novillo5fb49e52015-11-20 21:46:38 +0000412
Diego Novillo0b6985a2015-11-24 22:38:37 +0000413 // Only count records in hot callsites.
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000414 for (const auto &I : FS->getCallsiteSamples())
415 for (const auto &J : I.second) {
416 const FunctionSamples *CalleeSamples = &J.second;
Wei Mi0c2f6be2018-05-10 23:02:27 +0000417 if (callsiteIsHot(CalleeSamples, PSI))
418 Count += countBodyRecords(CalleeSamples, PSI);
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000419 }
Diego Novillo5fb49e52015-11-20 21:46:38 +0000420
Diego Novillof9ed08e2015-10-31 21:53:58 +0000421 return Count;
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000422}
423
Diego Novillo243ea6a2015-11-23 20:12:21 +0000424/// Return the number of samples collected in the body of this profile.
425///
Diego Novillo0b6985a2015-11-24 22:38:37 +0000426/// This count does not include samples from cold inlined callsites.
Diego Novillo243ea6a2015-11-23 20:12:21 +0000427uint64_t
Wei Mi0c2f6be2018-05-10 23:02:27 +0000428SampleCoverageTracker::countBodySamples(const FunctionSamples *FS,
429 ProfileSummaryInfo *PSI) const {
Diego Novillo243ea6a2015-11-23 20:12:21 +0000430 uint64_t Total = 0;
431 for (const auto &I : FS->getBodySamples())
432 Total += I.second.getSamples();
433
Diego Novillo0b6985a2015-11-24 22:38:37 +0000434 // Only count samples in hot callsites.
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000435 for (const auto &I : FS->getCallsiteSamples())
436 for (const auto &J : I.second) {
437 const FunctionSamples *CalleeSamples = &J.second;
Wei Mi0c2f6be2018-05-10 23:02:27 +0000438 if (callsiteIsHot(CalleeSamples, PSI))
439 Total += countBodySamples(CalleeSamples, PSI);
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000440 }
Diego Novillo243ea6a2015-11-23 20:12:21 +0000441
442 return Total;
443}
444
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000445/// Return the fraction of sample records used in this profile.
446///
447/// The returned value is an unsigned integer in the range 0-100 indicating
448/// the percentage of sample records that were used while applying this
449/// profile to the associated function.
Diego Novillof9ed08e2015-10-31 21:53:58 +0000450unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
451 unsigned Total) const {
452 assert(Used <= Total &&
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000453 "number of used records cannot exceed the total number of records");
Diego Novillof9ed08e2015-10-31 21:53:58 +0000454 return Total > 0 ? Used * 100 / Total : 100;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000455}
Diego Novillo8d6568b2013-11-13 12:22:21 +0000456
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000457/// Clear all the per-function data used to load samples and propagate weights.
458void SampleProfileLoader::clearFunctionData() {
459 BlockWeights.clear();
460 EdgeWeights.clear();
461 VisitedBlocks.clear();
462 VisitedEdges.clear();
463 EquivalenceClass.clear();
464 DT = nullptr;
465 PDT = nullptr;
466 LI = nullptr;
467 Predecessors.clear();
468 Successors.clear();
Diego Novillo1ca881c2015-11-23 16:30:17 +0000469 CoverageTracker.clear();
Diego Novilloa8a3bd22015-10-28 17:40:22 +0000470}
471
Florian Hahn6b3216a2017-07-31 10:07:49 +0000472#ifndef NDEBUG
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000473/// Print the weight of edge \p E on stream \p OS.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000474///
475/// \param OS Stream to emit the output to.
476/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000477void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000478 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
479 << "]: " << EdgeWeights[E] << "\n";
480}
481
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000482/// Print the equivalence class of block \p BB on stream \p OS.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000483///
484/// \param OS Stream to emit the output to.
485/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000486void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
Dehao Chen8e7df832015-09-29 18:28:15 +0000487 const BasicBlock *BB) {
488 const BasicBlock *Equiv = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000489 OS << "equivalence[" << BB->getName()
490 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
491}
492
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000493/// Print the weight of block \p BB on stream \p OS.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000494///
495/// \param OS Stream to emit the output to.
496/// \param BB Block to print.
Dehao Chen8e7df832015-09-29 18:28:15 +0000497void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
498 const BasicBlock *BB) const {
499 const auto &I = BlockWeights.find(BB);
Diego Novillo38be3332015-10-15 16:36:21 +0000500 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
Dehao Chen8e7df832015-09-29 18:28:15 +0000501 OS << "weight[" << BB->getName() << "]: " << W << "\n";
Diego Novillo0accb3d2014-01-10 23:23:46 +0000502}
Florian Hahn6b3216a2017-07-31 10:07:49 +0000503#endif
Diego Novillo0accb3d2014-01-10 23:23:46 +0000504
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000505/// Get the weight for an instruction.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000506///
507/// The "weight" of an instruction \p Inst is the number of samples
508/// collected on that instruction at runtime. To retrieve it, we
509/// need to compute the line number of \p Inst relative to the start of its
510/// function. We use HeaderLineno to compute the offset. We then
511/// look up the samples collected for \p Inst using BodySamples.
512///
513/// \param Inst Instruction to query.
514///
Dehao Chen8e7df832015-09-29 18:28:15 +0000515/// \returns the weight of \p Inst.
Dehao Chen94f369f2017-01-19 23:20:31 +0000516ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000517 const DebugLoc &DLoc = Inst.getDebugLoc();
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +0000518 if (!DLoc)
Dehao Chen8e7df832015-09-29 18:28:15 +0000519 return std::error_code();
Duncan P. N. Exon Smith41a15462015-03-20 00:56:55 +0000520
Dehao Chen67226882015-09-30 00:42:46 +0000521 const FunctionSamples *FS = findFunctionSamples(Inst);
522 if (!FS)
523 return std::error_code();
Dehao Chen41dc5a62015-10-09 16:50:16 +0000524
Dehao Chenc0a1e432016-08-12 16:22:12 +0000525 // Ignore all intrinsics and branch instructions.
526 // Branch instruction usually contains debug info from sources outside of
527 // the residing basic block, thus we ignore them during annotation.
528 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst))
Dehao Chena8bae822016-04-20 23:36:23 +0000529 return std::error_code();
530
Dehao Chen16f01fb2017-10-05 20:15:29 +0000531 // If a direct call/invoke instruction is inlined in profile
532 // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
Dehao Chenc0a1e432016-08-12 16:22:12 +0000533 // it means that the inlined callsite has no sample, thus the call
534 // instruction should have 0 count.
Dehao Chenc632a392017-03-06 17:49:59 +0000535 if ((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
Dehao Chen16f01fb2017-10-05 20:15:29 +0000536 !ImmutableCallSite(&Inst).isIndirectCall() &&
Dehao Chenc632a392017-03-06 17:49:59 +0000537 findCalleeFunctionSamples(Inst))
Dehao Chen41cde0b2016-09-18 23:11:37 +0000538 return 0;
Dehao Chenc0a1e432016-08-12 16:22:12 +0000539
Dehao Chen41dc5a62015-10-09 16:50:16 +0000540 const DILocation *DIL = DLoc;
Mircea Trofin56950972018-02-22 06:42:57 +0000541 uint32_t LineOffset = FunctionSamples::getOffset(DIL);
Dehao Chen533bc6e2017-02-23 18:27:45 +0000542 uint32_t Discriminator = DIL->getBaseDiscriminator();
Dehao Chenc632a392017-03-06 17:49:59 +0000543 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000544 if (R) {
Diego Novillof9ed08e2015-10-31 21:53:58 +0000545 bool FirstMark =
Diego Novillo243ea6a2015-11-23 20:12:21 +0000546 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
Diego Novillof9ed08e2015-10-31 21:53:58 +0000547 if (FirstMark) {
Vivek Pandya95906582017-10-11 17:12:59 +0000548 ORE->emit([&]() {
549 OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
550 Remark << "Applied " << ore::NV("NumSamples", *R);
551 Remark << " samples from profile (offset: ";
552 Remark << ore::NV("LineOffset", LineOffset);
553 if (Discriminator) {
554 Remark << ".";
555 Remark << ore::NV("Discriminator", Discriminator);
556 }
557 Remark << ")";
558 return Remark;
559 });
Diego Novillof9ed08e2015-10-31 21:53:58 +0000560 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000561 LLVM_DEBUG(dbgs() << " " << DLoc.getLine() << "."
562 << DIL->getBaseDiscriminator() << ":" << Inst
563 << " (line offset: " << LineOffset << "."
564 << DIL->getBaseDiscriminator() << " - weight: " << R.get()
565 << ")\n");
Diego Novillo748b3ffe2015-10-28 22:30:25 +0000566 }
Dehao Chen8e7df832015-09-29 18:28:15 +0000567 return R;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000568}
569
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000570/// Compute the weight of a basic block.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000571///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000572/// The weight of basic block \p BB is the maximum weight of all the
Dehao Chen8e7df832015-09-29 18:28:15 +0000573/// instructions in BB.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000574///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000575/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000576///
Dehao Chen8e7df832015-09-29 18:28:15 +0000577/// \returns the weight for \p BB.
Dehao Chen94f369f2017-01-19 23:20:31 +0000578ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) {
Dehao Chen160fbc32016-09-21 16:26:51 +0000579 uint64_t Max = 0;
580 bool HasWeight = false;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000581 for (auto &I : BB->getInstList()) {
Diego Novillo38be3332015-10-15 16:36:21 +0000582 const ErrorOr<uint64_t> &R = getInstWeight(I);
Dehao Chen160fbc32016-09-21 16:26:51 +0000583 if (R) {
584 Max = std::max(Max, R.get());
585 HasWeight = true;
Dehao Chen8e7df832015-09-29 18:28:15 +0000586 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000587 }
Dehao Chen160fbc32016-09-21 16:26:51 +0000588 return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000589}
590
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000591/// Compute and store the weights of every basic block.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000592///
593/// This populates the BlockWeights map by computing
594/// the weights of every basic block in the CFG.
595///
596/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000597bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000598 bool Changed = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000599 LLVM_DEBUG(dbgs() << "Block weights\n");
Dehao Chen8e7df832015-09-29 18:28:15 +0000600 for (const auto &BB : F) {
Diego Novillo38be3332015-10-15 16:36:21 +0000601 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000602 if (Weight) {
603 BlockWeights[&BB] = Weight.get();
Dehao Chen7c41dd62015-10-01 00:26:56 +0000604 VisitedBlocks.insert(&BB);
Dehao Chen8e7df832015-09-29 18:28:15 +0000605 Changed = true;
606 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000607 LLVM_DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000608 }
609
610 return Changed;
611}
612
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000613/// Get the FunctionSamples for a call instruction.
Dehao Chen67226882015-09-30 00:42:46 +0000614///
Dehao Chen41cde0b2016-09-18 23:11:37 +0000615/// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
Dehao Chen67226882015-09-30 00:42:46 +0000616/// instance in which that call instruction is calling to. It contains
617/// all samples that resides in the inlined instance. We first find the
618/// inlined instance in which the call instruction is from, then we
619/// traverse its children to find the callsite with the matching
Dehao Chen41cde0b2016-09-18 23:11:37 +0000620/// location.
Dehao Chen67226882015-09-30 00:42:46 +0000621///
Dehao Chen41cde0b2016-09-18 23:11:37 +0000622/// \param Inst Call/Invoke instruction to query.
Dehao Chen67226882015-09-30 00:42:46 +0000623///
624/// \returns The FunctionSamples pointer to the inlined instance.
625const FunctionSamples *
Dehao Chen41cde0b2016-09-18 23:11:37 +0000626SampleProfileLoader::findCalleeFunctionSamples(const Instruction &Inst) const {
Dehao Chen67226882015-09-30 00:42:46 +0000627 const DILocation *DIL = Inst.getDebugLoc();
628 if (!DIL) {
629 return nullptr;
630 }
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000631
632 StringRef CalleeName;
633 if (const CallInst *CI = dyn_cast<CallInst>(&Inst))
634 if (Function *Callee = CI->getCalledFunction())
635 CalleeName = Callee->getName();
636
Dehao Chen67226882015-09-30 00:42:46 +0000637 const FunctionSamples *FS = findFunctionSamples(Inst);
638 if (FS == nullptr)
639 return nullptr;
640
Mircea Trofin56950972018-02-22 06:42:57 +0000641 return FS->findFunctionSamplesAt(LineLocation(FunctionSamples::getOffset(DIL),
642 DIL->getBaseDiscriminator()),
643 CalleeName);
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000644}
645
646/// Returns a vector of FunctionSamples that are the indirect call targets
Dehao Chen3f56a052017-10-10 21:13:50 +0000647/// of \p Inst. The vector is sorted by the total number of samples. Stores
648/// the total call count of the indirect call in \p Sum.
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000649std::vector<const FunctionSamples *>
650SampleProfileLoader::findIndirectCallFunctionSamples(
Dehao Chen3f56a052017-10-10 21:13:50 +0000651 const Instruction &Inst, uint64_t &Sum) const {
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000652 const DILocation *DIL = Inst.getDebugLoc();
653 std::vector<const FunctionSamples *> R;
654
655 if (!DIL) {
656 return R;
657 }
658
659 const FunctionSamples *FS = findFunctionSamples(Inst);
660 if (FS == nullptr)
661 return R;
662
Mircea Trofin56950972018-02-22 06:42:57 +0000663 uint32_t LineOffset = FunctionSamples::getOffset(DIL);
Dehao Chen3f56a052017-10-10 21:13:50 +0000664 uint32_t Discriminator = DIL->getBaseDiscriminator();
665
666 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
667 Sum = 0;
668 if (T)
669 for (const auto &T_C : T.get())
670 Sum += T_C.second;
Mircea Trofin56950972018-02-22 06:42:57 +0000671 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(LineLocation(
672 FunctionSamples::getOffset(DIL), DIL->getBaseDiscriminator()))) {
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000673 if (M->empty())
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000674 return R;
675 for (const auto &NameFS : *M) {
Dehao Chen3f56a052017-10-10 21:13:50 +0000676 Sum += NameFS.second.getEntrySamples();
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000677 R.push_back(&NameFS.second);
678 }
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000679 llvm::sort(R.begin(), R.end(),
680 [](const FunctionSamples *L, const FunctionSamples *R) {
681 return L->getEntrySamples() > R->getEntrySamples();
682 });
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000683 }
684 return R;
Dehao Chen67226882015-09-30 00:42:46 +0000685}
686
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000687/// Get the FunctionSamples for an instruction.
Dehao Chen67226882015-09-30 00:42:46 +0000688///
689/// The FunctionSamples of an instruction \p Inst is the inlined instance
690/// in which that instruction is coming from. We traverse the inline stack
691/// of that instruction, and match it with the tree nodes in the profile.
692///
693/// \param Inst Instruction to query.
694///
695/// \returns the FunctionSamples pointer to the inlined instance.
696const FunctionSamples *
697SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000698 SmallVector<std::pair<LineLocation, StringRef>, 10> S;
Dehao Chen67226882015-09-30 00:42:46 +0000699 const DILocation *DIL = Inst.getDebugLoc();
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000700 if (!DIL)
Dehao Chen67226882015-09-30 00:42:46 +0000701 return Samples;
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000702
Mircea Trofin56950972018-02-22 06:42:57 +0000703 return Samples->findFunctionSamples(DIL);
Dehao Chen67226882015-09-30 00:42:46 +0000704}
705
Dehao Chen4f5d8302017-09-30 20:46:15 +0000706bool SampleProfileLoader::inlineCallInstruction(Instruction *I) {
707 assert(isa<CallInst>(I) || isa<InvokeInst>(I));
708 CallSite CS(I);
709 Function *CalledFunction = CS.getCalledFunction();
710 assert(CalledFunction);
711 DebugLoc DLoc = I->getDebugLoc();
712 BasicBlock *BB = I->getParent();
713 InlineParams Params = getInlineParams();
714 Params.ComputeFullInlineCost = true;
715 // Checks if there is anything in the reachable portion of the callee at
716 // this callsite that makes this inlining potentially illegal. Need to
717 // set ComputeFullInlineCost, otherwise getInlineCost may return early
718 // when cost exceeds threshold without checking all IRs in the callee.
719 // The acutal cost does not matter because we only checks isNever() to
720 // see if it is legal to inline the callsite.
721 InlineCost Cost = getInlineCost(CS, Params, GetTTI(*CalledFunction), GetAC,
722 None, nullptr, nullptr);
723 if (Cost.isNever()) {
724 ORE->emit(OptimizationRemark(DEBUG_TYPE, "Not inline", DLoc, BB)
725 << "incompatible inlining");
726 return false;
727 }
728 InlineFunctionInfo IFI(nullptr, &GetAC);
729 if (InlineFunction(CS, IFI)) {
730 // The call to InlineFunction erases I, so we can't pass it here.
731 ORE->emit(OptimizationRemark(DEBUG_TYPE, "HotInline", DLoc, BB)
732 << "inlined hot callee '" << ore::NV("Callee", CalledFunction)
733 << "' into '" << ore::NV("Caller", BB->getParent()) << "'");
734 return true;
735 }
736 return false;
737}
738
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000739/// Iteratively inline hot callsites of a function.
Dehao Chen67226882015-09-30 00:42:46 +0000740///
741/// Iteratively traverse all callsites of the function \p F, and find if
742/// the corresponding inlined instance exists and is hot in profile. If
743/// it is hot enough, inline the callsites and adds new callsites of the
Dehao Chen274df5e2017-01-31 17:49:37 +0000744/// callee into the caller. If the call is an indirect call, first promote
745/// it to direct call. Each indirect call is limited with a single target.
Dehao Chen67226882015-09-30 00:42:46 +0000746///
747/// \param F function to perform iterative inlining.
Dehao Chenc6c051f2017-11-01 20:26:47 +0000748/// \param InlinedGUIDs a set to be updated to include all GUIDs that are
749/// inlined in the profiled binary.
Dehao Chen67226882015-09-30 00:42:46 +0000750///
751/// \returns True if there is any inline happened.
Dehao Chena60cdd32017-02-28 18:09:44 +0000752bool SampleProfileLoader::inlineHotFunctions(
Dehao Chenc6c051f2017-11-01 20:26:47 +0000753 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
Dehao Chen274df5e2017-01-31 17:49:37 +0000754 DenseSet<Instruction *> PromotedInsns;
Dehao Chen67226882015-09-30 00:42:46 +0000755 bool Changed = false;
756 while (true) {
757 bool LocalChanged = false;
Dehao Chen41cde0b2016-09-18 23:11:37 +0000758 SmallVector<Instruction *, 10> CIS;
Dehao Chen67226882015-09-30 00:42:46 +0000759 for (auto &BB : F) {
Dehao Chen20866ed2016-09-19 18:38:14 +0000760 bool Hot = false;
761 SmallVector<Instruction *, 10> Candidates;
Dehao Chen67226882015-09-30 00:42:46 +0000762 for (auto &I : BB.getInstList()) {
Dehao Chen41cde0b2016-09-18 23:11:37 +0000763 const FunctionSamples *FS = nullptr;
764 if ((isa<CallInst>(I) || isa<InvokeInst>(I)) &&
Andrea Di Biagioe3edef02017-04-18 10:08:53 +0000765 !isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(I))) {
Dehao Chen20866ed2016-09-19 18:38:14 +0000766 Candidates.push_back(&I);
Wei Mi0c2f6be2018-05-10 23:02:27 +0000767 if (callsiteIsHot(FS, PSI))
Dehao Chen20866ed2016-09-19 18:38:14 +0000768 Hot = true;
Dehao Chen41cde0b2016-09-18 23:11:37 +0000769 }
Dehao Chen67226882015-09-30 00:42:46 +0000770 }
Dehao Chen20866ed2016-09-19 18:38:14 +0000771 if (Hot) {
772 CIS.insert(CIS.begin(), Candidates.begin(), Candidates.end());
773 }
Dehao Chen67226882015-09-30 00:42:46 +0000774 }
Dehao Chen41cde0b2016-09-18 23:11:37 +0000775 for (auto I : CIS) {
Dehao Chen274df5e2017-01-31 17:49:37 +0000776 Function *CalledFunction = CallSite(I).getCalledFunction();
Dehao Chen50f2aa12017-06-21 17:57:43 +0000777 // Do not inline recursive calls.
778 if (CalledFunction == &F)
779 continue;
Dehao Chen4f5d8302017-09-30 20:46:15 +0000780 if (CallSite(I).isIndirectCall()) {
781 if (PromotedInsns.count(I))
782 continue;
Dehao Chen3f56a052017-10-10 21:13:50 +0000783 uint64_t Sum;
784 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
Dehao Chend26dae02017-10-01 05:24:51 +0000785 if (IsThinLTOPreLink) {
Dehao Chenc6c051f2017-11-01 20:26:47 +0000786 FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
Wei Mi0c2f6be2018-05-10 23:02:27 +0000787 PSI->getOrCompHotCountThreshold());
Dehao Chend26dae02017-10-01 05:24:51 +0000788 continue;
789 }
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000790 auto CalleeFunctionName = FS->getName();
Dehao Chene2a428b2017-06-08 20:11:57 +0000791 // If it is a recursive call, we do not inline it as it could bloat
792 // the code exponentially. There is way to better handle this, e.g.
793 // clone the caller first, and inline the cloned caller if it is
Dehao Chen4f5d8302017-09-30 20:46:15 +0000794 // recursive. As llvm does not inline recursive calls, we will
795 // simply ignore it instead of handling it explicitly.
Dehao Chene2a428b2017-06-08 20:11:57 +0000796 if (CalleeFunctionName == F.getName())
797 continue;
Dehao Chen4f5d8302017-09-30 20:46:15 +0000798
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000799 const char *Reason = "Callee function not available";
Dehao Chen1ea8bd82017-04-17 22:23:05 +0000800 auto R = SymbolMap.find(CalleeFunctionName);
Dehao Chen4f5d8302017-09-30 20:46:15 +0000801 if (R != SymbolMap.end() && R->getValue() &&
802 !R->getValue()->isDeclaration() &&
803 R->getValue()->getSubprogram() &&
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000804 isLegalToPromote(CallSite(I), R->getValue(), &Reason)) {
Dehao Chen3f56a052017-10-10 21:13:50 +0000805 uint64_t C = FS->getEntrySamples();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000806 Instruction *DI =
807 pgo::promoteIndirectCall(I, R->getValue(), C, Sum, false, ORE);
Dehao Chen3f56a052017-10-10 21:13:50 +0000808 Sum -= C;
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000809 PromotedInsns.insert(I);
Dehao Chen4f5d8302017-09-30 20:46:15 +0000810 // If profile mismatches, we should not attempt to inline DI.
811 if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) &&
812 inlineCallInstruction(DI))
813 LocalChanged = true;
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000814 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000815 LLVM_DEBUG(dbgs()
816 << "\nFailed to promote indirect call to "
817 << CalleeFunctionName << " because " << Reason << "\n");
Dehao Chen2c7ca9b2017-04-13 19:52:10 +0000818 }
Dehao Chen274df5e2017-01-31 17:49:37 +0000819 }
Dehao Chen4f5d8302017-09-30 20:46:15 +0000820 } else if (CalledFunction && CalledFunction->getSubprogram() &&
821 !CalledFunction->isDeclaration()) {
822 if (inlineCallInstruction(I))
823 LocalChanged = true;
Dehao Chend26dae02017-10-01 05:24:51 +0000824 } else if (IsThinLTOPreLink) {
Dehao Chenc6c051f2017-11-01 20:26:47 +0000825 findCalleeFunctionSamples(*I)->findInlinedFunctions(
Wei Mi0c2f6be2018-05-10 23:02:27 +0000826 InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
Diego Novillo7963ea12015-10-26 18:52:53 +0000827 }
Dehao Chen67226882015-09-30 00:42:46 +0000828 }
829 if (LocalChanged) {
830 Changed = true;
831 } else {
832 break;
833 }
834 }
835 return Changed;
836}
837
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000838/// Find equivalence classes for the given block.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000839///
840/// This finds all the blocks that are guaranteed to execute the same
Eric Christopher572e03a2015-06-19 01:53:21 +0000841/// number of times as \p BB1. To do this, it traverses all the
Diego Novillo0accb3d2014-01-10 23:23:46 +0000842/// descendants of \p BB1 in the dominator or post-dominator tree.
843///
844/// A block BB2 will be in the same equivalence class as \p BB1 if
845/// the following holds:
846///
847/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
848/// is a descendant of \p BB1 in the dominator tree, then BB2 should
849/// dominate BB1 in the post-dominator tree.
850///
851/// 2- Both BB2 and \p BB1 must be in the same loop.
852///
853/// For every block BB2 that meets those two requirements, we set BB2's
854/// equivalence class to \p BB1.
855///
856/// \param BB1 Block to check.
857/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
858/// \param DomTree Opposite dominator tree. If \p Descendants is filled
859/// with blocks from \p BB1's dominator tree, then
860/// this is the post-dominator tree, and vice versa.
Jakub Kuderskib292c222017-07-14 18:26:09 +0000861template <bool IsPostDom>
Diego Novillode1ab262014-09-09 12:40:50 +0000862void SampleProfileLoader::findEquivalencesFor(
Benjamin Kramer8a752e32016-02-13 16:01:12 +0000863 BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
Jakub Kuderskib292c222017-07-14 18:26:09 +0000864 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) {
Dehao Chen7c41dd62015-10-01 00:26:56 +0000865 const BasicBlock *EC = EquivalenceClass[BB1];
Diego Novillo38be3332015-10-15 16:36:21 +0000866 uint64_t Weight = BlockWeights[EC];
Dehao Chen8e7df832015-09-29 18:28:15 +0000867 for (const auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000868 bool IsDomParent = DomTree->dominates(BB2, BB1);
869 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
Dehao Chen7c41dd62015-10-01 00:26:56 +0000870 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
871 EquivalenceClass[BB2] = EC;
Dehao Chenc0a1e432016-08-12 16:22:12 +0000872 // If BB2 is visited, then the entire EC should be marked as visited.
873 if (VisitedBlocks.count(BB2)) {
874 VisitedBlocks.insert(EC);
875 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000876
877 // If BB2 is heavier than BB1, make BB2 have the same weight
878 // as BB1.
879 //
880 // Note that we don't worry about the opposite situation here
881 // (when BB2 is lighter than BB1). We will deal with this
882 // during the propagation phase. Right now, we just want to
883 // make sure that BB1 has the largest weight of all the
884 // members of its equivalence set.
Dehao Chen7c41dd62015-10-01 00:26:56 +0000885 Weight = std::max(Weight, BlockWeights[BB2]);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000886 }
887 }
Dehao Chenc0a1e432016-08-12 16:22:12 +0000888 if (EC == &EC->getParent()->getEntryBlock()) {
889 BlockWeights[EC] = Samples->getHeadSamples() + 1;
890 } else {
891 BlockWeights[EC] = Weight;
892 }
Diego Novillo0accb3d2014-01-10 23:23:46 +0000893}
894
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000895/// Find equivalence classes.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000896///
897/// Since samples may be missing from blocks, we can fill in the gaps by setting
898/// the weights of all the blocks in the same equivalence class to the same
899/// weight. To compute the concept of equivalence, we use dominance and loop
900/// information. Two blocks B1 and B2 are in the same equivalence class if B1
901/// dominates B2, B2 post-dominates B1 and both are in the same loop.
902///
903/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000904void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000905 SmallVector<BasicBlock *, 8> DominatedBBs;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000906 LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +0000907 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000908 for (auto &BB : F) {
909 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000910
911 // Compute BB1's equivalence class once.
912 if (EquivalenceClass.count(BB1)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000913 LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000914 continue;
915 }
916
917 // By default, blocks are in their own equivalence class.
918 EquivalenceClass[BB1] = BB1;
919
920 // Traverse all the blocks dominated by BB1. We are looking for
921 // every basic block BB2 such that:
922 //
923 // 1- BB1 dominates BB2.
924 // 2- BB2 post-dominates BB1.
925 // 3- BB1 and BB2 are in the same loop nest.
926 //
927 // If all those conditions hold, it means that BB2 is executed
928 // as many times as BB1, so they are placed in the same equivalence
929 // class by making BB2's equivalence class be BB1.
930 DominatedBBs.clear();
931 DT->getDescendants(BB1, DominatedBBs);
Diego Novillo7732ae42015-08-26 20:00:27 +0000932 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
Diego Novillo0accb3d2014-01-10 23:23:46 +0000933
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000934 LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000935 }
936
937 // Assign weights to equivalence classes.
938 //
939 // All the basic blocks in the same equivalence class will execute
940 // the same number of times. Since we know that the head block in
941 // each equivalence class has the largest weight, assign that weight
942 // to all the blocks in that equivalence class.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000943 LLVM_DEBUG(
944 dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000945 for (auto &BI : F) {
Dehao Chen8e7df832015-09-29 18:28:15 +0000946 const BasicBlock *BB = &BI;
947 const BasicBlock *EquivBB = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000948 if (BB != EquivBB)
949 BlockWeights[BB] = BlockWeights[EquivBB];
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000950 LLVM_DEBUG(printBlockWeight(dbgs(), BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000951 }
952}
953
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000954/// Visit the given edge to decide if it has a valid weight.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000955///
956/// If \p E has not been visited before, we copy to \p UnknownEdge
957/// and increment the count of unknown edges.
958///
959/// \param E Edge to visit.
960/// \param NumUnknownEdges Current number of unknown edges.
961/// \param UnknownEdge Set if E has not been visited before.
962///
963/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillo38be3332015-10-15 16:36:21 +0000964uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
Diego Novillode1ab262014-09-09 12:40:50 +0000965 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000966 if (!VisitedEdges.count(E)) {
967 (*NumUnknownEdges)++;
968 *UnknownEdge = E;
969 return 0;
970 }
971
972 return EdgeWeights[E];
973}
974
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000975/// Propagate weights through incoming/outgoing edges.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000976///
977/// If the weight of a basic block is known, and there is only one edge
978/// with an unknown weight, we can calculate the weight of that edge.
979///
980/// Similarly, if all the edges have a known count, we can calculate the
981/// count of the basic block, if needed.
982///
983/// \param F Function to process.
Dehao Chenc0a1e432016-08-12 16:22:12 +0000984/// \param UpdateBlockCount Whether we should update basic block counts that
985/// has already been annotated.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000986///
987/// \returns True if new weights were assigned to edges or blocks.
Dehao Chenc0a1e432016-08-12 16:22:12 +0000988bool SampleProfileLoader::propagateThroughEdges(Function &F,
989 bool UpdateBlockCount) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000990 bool Changed = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000991 LLVM_DEBUG(dbgs() << "\nPropagation through edges\n");
Dehao Chen7c41dd62015-10-01 00:26:56 +0000992 for (const auto &BI : F) {
993 const BasicBlock *BB = &BI;
994 const BasicBlock *EC = EquivalenceClass[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000995
996 // Visit all the predecessor and successor edges to determine
997 // which ones have a weight assigned already. Note that it doesn't
998 // matter that we only keep track of a single unknown edge. The
999 // only case we are interested in handling is when only a single
1000 // edge is unknown (see setEdgeOrBlockWeight).
1001 for (unsigned i = 0; i < 2; i++) {
Diego Novillo38be3332015-10-15 16:36:21 +00001002 uint64_t TotalWeight = 0;
Dehao Chen29d26412016-07-11 16:40:17 +00001003 unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
1004 Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001005
1006 if (i == 0) {
1007 // First, visit all predecessor edges.
Dehao Chen29d26412016-07-11 16:40:17 +00001008 NumTotalEdges = Predecessors[BB].size();
Diego Novillob368b7d2014-10-22 16:51:50 +00001009 for (auto *Pred : Predecessors[BB]) {
1010 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001011 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1012 if (E.first == E.second)
1013 SelfReferentialEdge = E;
1014 }
Dehao Chen29d26412016-07-11 16:40:17 +00001015 if (NumTotalEdges == 1) {
1016 SingleEdge = std::make_pair(Predecessors[BB][0], BB);
1017 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001018 } else {
1019 // On the second round, visit all successor edges.
Dehao Chen29d26412016-07-11 16:40:17 +00001020 NumTotalEdges = Successors[BB].size();
Diego Novillob368b7d2014-10-22 16:51:50 +00001021 for (auto *Succ : Successors[BB]) {
1022 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001023 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1024 }
Dehao Chen29d26412016-07-11 16:40:17 +00001025 if (NumTotalEdges == 1) {
1026 SingleEdge = std::make_pair(BB, Successors[BB][0]);
1027 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001028 }
1029
1030 // After visiting all the edges, there are three cases that we
1031 // can handle immediately:
1032 //
1033 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
1034 // In this case, we simply check that the sum of all the edges
1035 // is the same as BB's weight. If not, we change BB's weight
1036 // to match. Additionally, if BB had not been visited before,
1037 // we mark it visited.
1038 //
1039 // - Only one edge is unknown and BB has already been visited.
1040 // In this case, we can compute the weight of the edge by
1041 // subtracting the total block weight from all the known
1042 // edge weights. If the edges weight more than BB, then the
1043 // edge of the last remaining edge is set to zero.
1044 //
1045 // - There exists a self-referential edge and the weight of BB is
1046 // known. In this case, this edge can be based on BB's weight.
1047 // We add up all the other known edges and set the weight on
1048 // the self-referential edge as we did in the previous case.
1049 //
1050 // In any other case, we must continue iterating. Eventually,
1051 // all edges will get a weight, or iteration will stop when
1052 // it reaches SampleProfileMaxPropagateIterations.
1053 if (NumUnknownEdges <= 1) {
Diego Novillo38be3332015-10-15 16:36:21 +00001054 uint64_t &BBWeight = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001055 if (NumUnknownEdges == 0) {
Dehao Chen29d26412016-07-11 16:40:17 +00001056 if (!VisitedBlocks.count(EC)) {
1057 // If we already know the weight of all edges, the weight of the
1058 // basic block can be computed. It should be no larger than the sum
1059 // of all edge weights.
1060 if (TotalWeight > BBWeight) {
1061 BBWeight = TotalWeight;
1062 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001063 LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName()
1064 << " known. Set weight for block: ";
1065 printBlockWeight(dbgs(), BB););
Dehao Chen29d26412016-07-11 16:40:17 +00001066 }
1067 } else if (NumTotalEdges == 1 &&
1068 EdgeWeights[SingleEdge] < BlockWeights[EC]) {
1069 // If there is only one edge for the visited basic block, use the
1070 // block weight to adjust edge weight if edge weight is smaller.
1071 EdgeWeights[SingleEdge] = BlockWeights[EC];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001072 Changed = true;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001073 }
Dehao Chen7c41dd62015-10-01 00:26:56 +00001074 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001075 // If there is a single unknown edge and the block has been
1076 // visited, then we can compute E's weight.
1077 if (BBWeight >= TotalWeight)
1078 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
1079 else
1080 EdgeWeights[UnknownEdge] = 0;
Dehao Chenc0a1e432016-08-12 16:22:12 +00001081 const BasicBlock *OtherEC;
1082 if (i == 0)
1083 OtherEC = EquivalenceClass[UnknownEdge.first];
1084 else
1085 OtherEC = EquivalenceClass[UnknownEdge.second];
1086 // Edge weights should never exceed the BB weights it connects.
1087 if (VisitedBlocks.count(OtherEC) &&
1088 EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
1089 EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001090 VisitedEdges.insert(UnknownEdge);
1091 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001092 LLVM_DEBUG(dbgs() << "Set weight for edge: ";
1093 printEdgeWeight(dbgs(), UnknownEdge));
Diego Novillo0accb3d2014-01-10 23:23:46 +00001094 }
Dehao Chenc0a1e432016-08-12 16:22:12 +00001095 } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
1096 // If a block Weights 0, all its in/out edges should weight 0.
1097 if (i == 0) {
1098 for (auto *Pred : Predecessors[BB]) {
1099 Edge E = std::make_pair(Pred, BB);
1100 EdgeWeights[E] = 0;
1101 VisitedEdges.insert(E);
1102 }
1103 } else {
1104 for (auto *Succ : Successors[BB]) {
1105 Edge E = std::make_pair(BB, Succ);
1106 EdgeWeights[E] = 0;
1107 VisitedEdges.insert(E);
1108 }
1109 }
Dehao Chen7c41dd62015-10-01 00:26:56 +00001110 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
Diego Novillo38be3332015-10-15 16:36:21 +00001111 uint64_t &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +00001112 // We have a self-referential edge and the weight of BB is known.
1113 if (BBWeight >= TotalWeight)
1114 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
1115 else
1116 EdgeWeights[SelfReferentialEdge] = 0;
1117 VisitedEdges.insert(SelfReferentialEdge);
1118 Changed = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001119 LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: ";
1120 printEdgeWeight(dbgs(), SelfReferentialEdge));
Diego Novillo0accb3d2014-01-10 23:23:46 +00001121 }
Dehao Chenc0a1e432016-08-12 16:22:12 +00001122 if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
1123 BlockWeights[EC] = TotalWeight;
1124 VisitedBlocks.insert(EC);
1125 Changed = true;
1126 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001127 }
1128 }
1129
1130 return Changed;
1131}
1132
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001133/// Build in/out edge lists for each basic block in the CFG.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001134///
1135/// We are interested in unique edges. If a block B1 has multiple
1136/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +00001137void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001138 for (auto &BI : F) {
1139 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001140
1141 // Add predecessors for B1.
1142 SmallPtrSet<BasicBlock *, 16> Visited;
1143 if (!Predecessors[B1].empty())
1144 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001145 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
1146 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +00001147 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001148 Predecessors[B1].push_back(B2);
1149 }
1150
1151 // Add successors for B1.
1152 Visited.clear();
1153 if (!Successors[B1].empty())
1154 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001155 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
1156 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +00001157 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +00001158 Successors[B1].push_back(B2);
1159 }
1160 }
1161}
1162
Dehao Chen5d2a1a52017-11-06 19:52:49 +00001163/// Returns the sorted CallTargetMap \p M by count in descending order.
1164static SmallVector<InstrProfValueData, 2> SortCallTargets(
1165 const SampleRecord::CallTargetMap &M) {
1166 SmallVector<InstrProfValueData, 2> R;
1167 for (auto I = M.begin(); I != M.end(); ++I)
1168 R.push_back({Function::getGUID(I->getKey()), I->getValue()});
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +00001169 llvm::sort(R.begin(), R.end(),
1170 [](const InstrProfValueData &L, const InstrProfValueData &R) {
1171 if (L.Count == R.Count)
1172 return L.Value > R.Value;
1173 else
1174 return L.Count > R.Count;
1175 });
Dehao Chen5d2a1a52017-11-06 19:52:49 +00001176 return R;
Dehao Chen77079002017-01-20 22:56:07 +00001177}
1178
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001179/// Propagate weights into edges
Diego Novillo0accb3d2014-01-10 23:23:46 +00001180///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001181/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +00001182///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001183/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +00001184/// of that edge is the weight of the block.
1185///
1186/// - If all incoming or outgoing edges are known except one, and the
1187/// weight of the block is already known, the weight of the unknown
1188/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001189/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001190/// we set the unknown edge weight to zero.
1191///
1192/// - If there is a self-referential edge, and the weight of the block is
1193/// known, the weight for that edge is set to the weight of the block
1194/// minus the weight of the other incoming edges to that block (if
1195/// known).
Diego Novillode1ab262014-09-09 12:40:50 +00001196void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001197 bool Changed = true;
Diego Novillo38be3332015-10-15 16:36:21 +00001198 unsigned I = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001199
Dehao Chenc0a1e432016-08-12 16:22:12 +00001200 // If BB weight is larger than its corresponding loop's header BB weight,
1201 // use the BB weight to replace the loop header BB weight.
1202 for (auto &BI : F) {
1203 BasicBlock *BB = &BI;
1204 Loop *L = LI->getLoopFor(BB);
1205 if (!L) {
1206 continue;
1207 }
1208 BasicBlock *Header = L->getHeader();
1209 if (Header && BlockWeights[BB] > BlockWeights[Header]) {
1210 BlockWeights[Header] = BlockWeights[BB];
1211 }
1212 }
Diego Novilloffc84e32015-05-13 17:04:29 +00001213
Diego Novillo0accb3d2014-01-10 23:23:46 +00001214 // Before propagation starts, build, for each block, a list of
1215 // unique predecessors and successors. This is necessary to handle
1216 // identical edges in multiway branches. Since we visit all blocks and all
1217 // edges of the CFG, it is cleaner to build these lists once at the start
1218 // of the pass.
1219 buildEdges(F);
1220
1221 // Propagate until we converge or we go past the iteration limit.
Diego Novillo38be3332015-10-15 16:36:21 +00001222 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
Dehao Chenc0a1e432016-08-12 16:22:12 +00001223 Changed = propagateThroughEdges(F, false);
1224 }
1225
1226 // The first propagation propagates BB counts from annotated BBs to unknown
1227 // BBs. The 2nd propagation pass resets edges weights, and use all BB weights
1228 // to propagate edge weights.
1229 VisitedEdges.clear();
1230 Changed = true;
1231 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1232 Changed = propagateThroughEdges(F, false);
1233 }
1234
1235 // The 3rd propagation pass allows adjust annotated BB weights that are
1236 // obviously wrong.
1237 Changed = true;
1238 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1239 Changed = propagateThroughEdges(F, true);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001240 }
1241
1242 // Generate MD_prof metadata for every branch instruction using the
1243 // edge weights computed during propagation.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001244 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
Diego Novillo7963ea12015-10-26 18:52:53 +00001245 LLVMContext &Ctx = F.getContext();
1246 MDBuilder MDB(Ctx);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001247 for (auto &BI : F) {
1248 BasicBlock *BB = &BI;
Dehao Chen9232f982016-07-11 16:48:54 +00001249
1250 if (BlockWeights[BB]) {
1251 for (auto &I : BB->getInstList()) {
Dehao Chen77079002017-01-20 22:56:07 +00001252 if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1253 continue;
1254 CallSite CS(&I);
1255 if (!CS.getCalledFunction()) {
1256 const DebugLoc &DLoc = I.getDebugLoc();
1257 if (!DLoc)
1258 continue;
1259 const DILocation *DIL = DLoc;
Mircea Trofin56950972018-02-22 06:42:57 +00001260 uint32_t LineOffset = FunctionSamples::getOffset(DIL);
Dehao Chen533bc6e2017-02-23 18:27:45 +00001261 uint32_t Discriminator = DIL->getBaseDiscriminator();
Dehao Chen77079002017-01-20 22:56:07 +00001262
1263 const FunctionSamples *FS = findFunctionSamples(I);
1264 if (!FS)
1265 continue;
1266 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001267 if (!T || T.get().empty())
Dehao Chen77079002017-01-20 22:56:07 +00001268 continue;
Dehao Chen5d2a1a52017-11-06 19:52:49 +00001269 SmallVector<InstrProfValueData, 2> SortedCallTargets =
1270 SortCallTargets(T.get());
1271 uint64_t Sum;
1272 findIndirectCallFunctionSamples(I, Sum);
Dehao Chen77079002017-01-20 22:56:07 +00001273 annotateValueSite(*I.getParent()->getParent()->getParent(), I,
1274 SortedCallTargets, Sum, IPVK_IndirectCallTarget,
1275 SortedCallTargets.size());
1276 } else if (!dyn_cast<IntrinsicInst>(&I)) {
1277 SmallVector<uint32_t, 1> Weights;
1278 Weights.push_back(BlockWeights[BB]);
1279 I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
Dehao Chen9232f982016-07-11 16:48:54 +00001280 }
1281 }
1282 }
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001283 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001284 if (TI->getNumSuccessors() == 1)
1285 continue;
1286 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1287 continue;
1288
Andrea Di Biagio517e3fc2017-04-18 11:27:58 +00001289 DebugLoc BranchLoc = TI->getDebugLoc();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001290 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1291 << ((BranchLoc) ? Twine(BranchLoc.getLine())
1292 : Twine("<UNKNOWN LOCATION>"))
1293 << ".\n");
Diego Novillo38be3332015-10-15 16:36:21 +00001294 SmallVector<uint32_t, 4> Weights;
Diego Novillo7963ea12015-10-26 18:52:53 +00001295 uint32_t MaxWeight = 0;
Eli Friedman51cf2602017-08-11 21:12:04 +00001296 Instruction *MaxDestInst;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001297 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1298 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001299 Edge E = std::make_pair(BB, Succ);
Diego Novillo38be3332015-10-15 16:36:21 +00001300 uint64_t Weight = EdgeWeights[E];
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001301 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
Diego Novillo38be3332015-10-15 16:36:21 +00001302 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1303 // if needed. Sample counts in profiles are 64-bit unsigned values,
1304 // but internally branch weights are expressed as 32-bit values.
1305 if (Weight > std::numeric_limits<uint32_t>::max()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001306 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
Diego Novillo38be3332015-10-15 16:36:21 +00001307 Weight = std::numeric_limits<uint32_t>::max();
1308 }
Dehao Chenc0a1e432016-08-12 16:22:12 +00001309 // Weight is added by one to avoid propagation errors introduced by
1310 // 0 weights.
1311 Weights.push_back(static_cast<uint32_t>(Weight + 1));
Diego Novillo7963ea12015-10-26 18:52:53 +00001312 if (Weight != 0) {
1313 if (Weight > MaxWeight) {
1314 MaxWeight = Weight;
Eli Friedman51cf2602017-08-11 21:12:04 +00001315 MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
Diego Novillo7963ea12015-10-26 18:52:53 +00001316 }
1317 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001318 }
1319
Dehao Chen53a0c082017-03-23 14:43:10 +00001320 uint64_t TempWeight;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001321 // Only set weights if there is at least one non-zero weight.
1322 // In any other case, let the analyzer set weights.
Dehao Chen53a0c082017-03-23 14:43:10 +00001323 // Do not set weights if the weights are present. In ThinLTO, the profile
1324 // annotation is done twice. If the first annotation already set the
1325 // weights, the second pass does not need to set it.
1326 if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001327 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001328 TI->setMetadata(LLVMContext::MD_prof,
Dehao Chen82667d02016-09-19 16:33:41 +00001329 MDB.createBranchWeights(Weights));
Vivek Pandya95906582017-10-11 17:12:59 +00001330 ORE->emit([&]() {
1331 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1332 << "most popular destination for conditional branches at "
1333 << ore::NV("CondBranchesLoc", BranchLoc);
1334 });
Dehao Chen82667d02016-09-19 16:33:41 +00001335 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001336 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
Dehao Chen82667d02016-09-19 16:33:41 +00001337 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001338 }
1339}
1340
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001341/// Get the line number for the function header.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001342///
1343/// This looks up function \p F in the current compilation unit and
1344/// retrieves the line number where the function is defined. This is
1345/// line 0 for all the samples read from the profile file. Every line
1346/// number is relative to this line.
1347///
1348/// \param F Function object to query.
1349///
Diego Novilloa32aa322014-03-14 21:58:59 +00001350/// \returns the line number where \p F is defined. If it returns 0,
1351/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +00001352unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Pete Cooperadebb932016-03-11 02:14:16 +00001353 if (DISubprogram *S = F.getSubprogram())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +00001354 return S->getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +00001355
Diego Novilloaa555072015-10-27 18:41:46 +00001356 // If the start of \p F is missing, emit a diagnostic to inform the user
Diego Novillo8027b802014-10-22 12:59:00 +00001357 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +00001358 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +00001359 "No debug information found in function " + F.getName() +
1360 ": Function profile not used",
1361 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +00001362 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +00001363}
1364
Diego Novillo7732ae42015-08-26 20:00:27 +00001365void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1366 DT.reset(new DominatorTree);
1367 DT->recalculate(F);
1368
Jakub Kuderskief33edd2018-05-23 17:29:21 +00001369 PDT.reset(new PostDominatorTree(F));
Diego Novillo7732ae42015-08-26 20:00:27 +00001370
1371 LI.reset(new LoopInfo);
1372 LI->analyze(*DT);
1373}
1374
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001375/// Generate branch weight metadata for all branches in \p F.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001376///
1377/// Branch weights are computed out of instruction samples using a
1378/// propagation heuristic. Propagation proceeds in 3 phases:
1379///
1380/// 1- Assignment of block weights. All the basic blocks in the function
1381/// are initial assigned the same weight as their most frequently
1382/// executed instruction.
1383///
1384/// 2- Creation of equivalence classes. Since samples may be missing from
1385/// blocks, we can fill in the gaps by setting the weights of all the
1386/// blocks in the same equivalence class to the same weight. To compute
1387/// the concept of equivalence, we use dominance and loop information.
1388/// Two blocks B1 and B2 are in the same equivalence class if B1
1389/// dominates B2, B2 post-dominates B1 and both are in the same loop.
1390///
1391/// 3- Propagation of block weights into edges. This uses a simple
1392/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001393/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +00001394///
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001395/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +00001396/// of that edge is the weight of the block.
1397///
1398/// - If all the edges are known except one, and the weight of the
1399/// block is already known, the weight of the unknown edge will
1400/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001401/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +00001402/// we set the unknown edge weight to zero.
1403///
1404/// - If there is a self-referential edge, and the weight of the block is
1405/// known, the weight for that edge is set to the weight of the block
1406/// minus the weight of the other incoming edges to that block (if
1407/// known).
1408///
1409/// Since this propagation is not guaranteed to finalize for every CFG, we
1410/// only allow it to proceed for a limited number of iterations (controlled
1411/// by -sample-profile-max-propagate-iterations).
1412///
1413/// FIXME: Try to replace this propagation heuristic with a scheme
1414/// that is guaranteed to finalize. A work-list approach similar to
1415/// the standard value propagation algorithm used by SSA-CCP might
1416/// work here.
1417///
1418/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +00001419/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +00001420///
1421/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +00001422///
1423/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +00001424bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +00001425 bool Changed = false;
1426
Dehao Chen41dc5a62015-10-09 16:50:16 +00001427 if (getFunctionLoc(F) == 0)
Diego Novilloa32aa322014-03-14 21:58:59 +00001428 return false;
1429
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001430 LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1431 << F.getName() << ": " << getFunctionLoc(F) << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +00001432
Dehao Chenc6c051f2017-11-01 20:26:47 +00001433 DenseSet<GlobalValue::GUID> InlinedGUIDs;
1434 Changed |= inlineHotFunctions(F, InlinedGUIDs);
Dehao Chen67226882015-09-30 00:42:46 +00001435
Diego Novillo0accb3d2014-01-10 23:23:46 +00001436 // Compute basic block weights.
1437 Changed |= computeBlockWeights(F);
1438
1439 if (Changed) {
Dehao Chena60cdd32017-02-28 18:09:44 +00001440 // Add an entry count to the function using the samples gathered at the
Dehao Chenc6c051f2017-11-01 20:26:47 +00001441 // function entry.
1442 // Sets the GUIDs that are inlined in the profiled binary. This is used
1443 // for ThinLink to make correct liveness analysis, and also make the IR
1444 // match the profiled binary before annotation.
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001445 F.setEntryCount(
1446 ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
1447 &InlinedGUIDs);
Dehao Chena60cdd32017-02-28 18:09:44 +00001448
Diego Novillo7732ae42015-08-26 20:00:27 +00001449 // Compute dominance and loop info needed for propagation.
1450 computeDominanceAndLoopInfo(F);
1451
Diego Novillo0accb3d2014-01-10 23:23:46 +00001452 // Find equivalence classes.
1453 findEquivalenceClasses(F);
1454
1455 // Propagate weights to all edges.
1456 propagateWeights(F);
1457 }
1458
Diego Novillof9ed08e2015-10-31 21:53:58 +00001459 // If coverage checking was requested, compute it now.
Diego Novillo243ea6a2015-11-23 20:12:21 +00001460 if (SampleProfileRecordCoverage) {
Wei Mi0c2f6be2018-05-10 23:02:27 +00001461 unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
1462 unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
Diego Novillof9ed08e2015-10-31 21:53:58 +00001463 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
Diego Novillo243ea6a2015-11-23 20:12:21 +00001464 if (Coverage < SampleProfileRecordCoverage) {
Diego Novillof9ed08e2015-10-31 21:53:58 +00001465 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001466 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillof9ed08e2015-10-31 21:53:58 +00001467 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1468 Twine(Coverage) + "%) were applied",
1469 DS_Warning));
1470 }
1471 }
1472
Diego Novillo243ea6a2015-11-23 20:12:21 +00001473 if (SampleProfileSampleCoverage) {
1474 uint64_t Used = CoverageTracker.getTotalUsedSamples();
Wei Mi0c2f6be2018-05-10 23:02:27 +00001475 uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
Diego Novillo243ea6a2015-11-23 20:12:21 +00001476 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1477 if (Coverage < SampleProfileSampleCoverage) {
1478 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Pete Cooperadebb932016-03-11 02:14:16 +00001479 F.getSubprogram()->getFilename(), getFunctionLoc(F),
Diego Novillo243ea6a2015-11-23 20:12:21 +00001480 Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1481 Twine(Coverage) + "%) were applied",
1482 DS_Warning));
1483 }
1484 }
Diego Novillo0accb3d2014-01-10 23:23:46 +00001485 return Changed;
1486}
1487
Xinliang David Lie897edb2016-05-27 22:30:44 +00001488char SampleProfileLoaderLegacyPass::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +00001489
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001490INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1491 "Sample Profile loader", false, false)
1492INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Dehao Chen3a81f842017-09-14 17:29:56 +00001493INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Wei Mi0c2f6be2018-05-10 23:02:27 +00001494INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001495INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1496 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +00001497
1498bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillo7732ae42015-08-26 20:00:27 +00001499 auto &Ctx = M.getContext();
Diego Novillo4d711132015-08-25 15:25:11 +00001500 auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx);
Diego Novillofcd55602014-11-03 00:51:45 +00001501 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +00001502 std::string Msg = "Could not open profile: " + EC.message();
David Blaikie2297a912015-11-02 20:01:13 +00001503 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
Diego Novilloc572e922014-10-30 18:00:06 +00001504 return false;
1505 }
Diego Novillofcd55602014-11-03 00:51:45 +00001506 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +00001507 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001508 return true;
1509}
1510
Diego Novillo4d711132015-08-25 15:25:11 +00001511ModulePass *llvm::createSampleProfileLoaderPass() {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001512 return new SampleProfileLoaderLegacyPass(SampleProfileFile);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001513}
1514
Diego Novillo4d711132015-08-25 15:25:11 +00001515ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
Xinliang David Lie897edb2016-05-27 22:30:44 +00001516 return new SampleProfileLoaderLegacyPass(Name);
Diego Novilloc0dd1032013-11-26 20:37:33 +00001517}
1518
Wei Mi0c2f6be2018-05-10 23:02:27 +00001519bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
1520 ProfileSummaryInfo *_PSI) {
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001521 if (!ProfileIsValid)
1522 return false;
1523
Wei Mi0c2f6be2018-05-10 23:02:27 +00001524 PSI = _PSI;
1525 if (M.getProfileSummary() == nullptr)
1526 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()));
1527
Diego Novillo84f06cc2015-11-27 23:14:51 +00001528 // Compute the total number of samples collected in this profile.
1529 for (const auto &I : Reader->getProfiles())
1530 TotalCollectedSamples += I.second.getTotalSamples();
1531
Dehao Chen1ea8bd82017-04-17 22:23:05 +00001532 // Populate the symbol map.
1533 for (const auto &N_F : M.getValueSymbolTable()) {
Benjamin Kramer24cb28b2017-12-28 18:10:41 +00001534 StringRef OrigName = N_F.getKey();
Dehao Chen1ea8bd82017-04-17 22:23:05 +00001535 Function *F = dyn_cast<Function>(N_F.getValue());
1536 if (F == nullptr)
1537 continue;
1538 SymbolMap[OrigName] = F;
1539 auto pos = OrigName.find('.');
Benjamin Kramer24cb28b2017-12-28 18:10:41 +00001540 if (pos != StringRef::npos) {
1541 StringRef NewName = OrigName.substr(0, pos);
Dehao Chen1ea8bd82017-04-17 22:23:05 +00001542 auto r = SymbolMap.insert(std::make_pair(NewName, F));
1543 // Failiing to insert means there is already an entry in SymbolMap,
1544 // thus there are multiple functions that are mapped to the same
1545 // stripped name. In this case of name conflicting, set the value
1546 // to nullptr to avoid confusion.
1547 if (!r.second)
1548 r.first->second = nullptr;
1549 }
1550 }
1551
Diego Novillo4d711132015-08-25 15:25:11 +00001552 bool retval = false;
1553 for (auto &F : M)
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001554 if (!F.isDeclaration()) {
1555 clearFunctionData();
Eli Friedman51cf2602017-08-11 21:12:04 +00001556 retval |= runOnFunction(F, AM);
Diego Novilloa8a3bd22015-10-28 17:40:22 +00001557 }
Diego Novillo4d711132015-08-25 15:25:11 +00001558 return retval;
1559}
1560
Xinliang David Lie897edb2016-05-27 22:30:44 +00001561bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
Dehao Chenf3ed14d2017-09-12 21:55:55 +00001562 ACT = &getAnalysis<AssumptionCacheTracker>();
Dehao Chen3a81f842017-09-14 17:29:56 +00001563 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
Wei Mi0c2f6be2018-05-10 23:02:27 +00001564 ProfileSummaryInfo *PSI =
1565 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1566 return SampleLoader.runOnModule(M, nullptr, PSI);
Xinliang David Lie897edb2016-05-27 22:30:44 +00001567}
1568
Eli Friedman51cf2602017-08-11 21:12:04 +00001569bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
Teresa Johnson915897e2017-12-18 20:02:43 +00001570 // Initialize the entry count to -1, which will be treated conservatively
1571 // by getEntryCount as the same as unknown (None). If we have samples this
1572 // will be overwritten in emitAnnotations.
Easwaran Ramane5b8de22018-01-17 22:24:23 +00001573 F.setEntryCount(ProfileCount(-1, Function::PCT_Real));
Eli Friedman51cf2602017-08-11 21:12:04 +00001574 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1575 if (AM) {
1576 auto &FAM =
1577 AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
1578 .getManager();
1579 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1580 } else {
1581 OwnedORE = make_unique<OptimizationRemarkEmitter>(&F);
1582 ORE = OwnedORE.get();
1583 }
Diego Novillode1ab262014-09-09 12:40:50 +00001584 Samples = Reader->getSamplesFor(F);
Dehao Chen4a435e02017-03-14 17:33:01 +00001585 if (Samples && !Samples->empty())
Diego Novillode1ab262014-09-09 12:40:50 +00001586 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +00001587 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +00001588}
Xinliang David Lid38392e2016-05-27 23:20:16 +00001589
1590PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +00001591 ModuleAnalysisManager &AM) {
Dehao Chenf3ed14d2017-09-12 21:55:55 +00001592 FunctionAnalysisManager &FAM =
1593 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Xinliang David Lid38392e2016-05-27 23:20:16 +00001594
Dehao Chenf3ed14d2017-09-12 21:55:55 +00001595 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
1596 return FAM.getResult<AssumptionAnalysis>(F);
1597 };
Dehao Chen3a81f842017-09-14 17:29:56 +00001598 auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
1599 return FAM.getResult<TargetIRAnalysis>(F);
1600 };
Dehao Chenf3ed14d2017-09-12 21:55:55 +00001601
Dehao Chend26dae02017-10-01 05:24:51 +00001602 SampleProfileLoader SampleLoader(
1603 ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
1604 IsThinLTOPreLink, GetAssumptionCache, GetTTI);
Xinliang David Lid38392e2016-05-27 23:20:16 +00001605
1606 SampleLoader.doInitialization(M);
1607
Wei Mi0c2f6be2018-05-10 23:02:27 +00001608 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
1609 if (!SampleLoader.runOnModule(M, &AM, PSI))
Xinliang David Lid38392e2016-05-27 23:20:16 +00001610 return PreservedAnalyses::all();
1611
1612 return PreservedAnalyses::none();
1613}