blob: 179bbf78366d118225bf956c3b62973d88ea6dbb [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
Chandler Carruth07baed52014-01-13 08:04:33 +000025#include "llvm/Transforms/Scalar.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000026#include "llvm/ADT/DenseMap.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000027#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000028#include "llvm/ADT/SmallSet.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000029#include "llvm/ADT/StringRef.h"
Diego Novillo0accb3d2014-01-10 23:23:46 +000030#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000031#include "llvm/Analysis/PostDominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000032#include "llvm/IR/Constants.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000033#include "llvm/IR/DebugInfo.h"
Diego Novilloa32aa322014-03-14 21:58:59 +000034#include "llvm/IR/DiagnosticInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000035#include "llvm/IR/Dominators.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000036#include "llvm/IR/Function.h"
Chandler Carruth83948572014-03-04 10:30:26 +000037#include "llvm/IR/InstIterator.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000038#include "llvm/IR/Instructions.h"
39#include "llvm/IR/LLVMContext.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000040#include "llvm/IR/MDBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000041#include "llvm/IR/Metadata.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000042#include "llvm/IR/Module.h"
43#include "llvm/Pass.h"
Diego Novillode1ab262014-09-09 12:40:50 +000044#include "llvm/ProfileData/SampleProfReader.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000045#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
Diego Novillo8d6568b2013-11-13 12:22:21 +000047#include "llvm/Support/raw_ostream.h"
Logan Chien61c6df02014-02-22 06:34:10 +000048#include <cctype>
Diego Novillo8d6568b2013-11-13 12:22:21 +000049
50using namespace llvm;
Diego Novillode1ab262014-09-09 12:40:50 +000051using namespace sampleprof;
Diego Novillo8d6568b2013-11-13 12:22:21 +000052
Chandler Carruth964daaa2014-04-22 02:55:47 +000053#define DEBUG_TYPE "sample-profile"
54
Diego Novillo8d6568b2013-11-13 12:22:21 +000055// Command line option to specify the file to read samples from. This is
56// mainly used for debugging.
57static cl::opt<std::string> SampleProfileFile(
58 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
59 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
Diego Novillo0accb3d2014-01-10 23:23:46 +000060static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
61 "sample-profile-max-propagate-iterations", cl::init(100),
62 cl::desc("Maximum number of iterations to go through when propagating "
63 "sample block/edge weights through the CFG."));
Diego Novillo8d6568b2013-11-13 12:22:21 +000064
65namespace {
Diego Novillo92aa8c22014-03-10 22:41:28 +000066typedef DenseMap<BasicBlock *, unsigned> BlockWeightMap;
Diego Novillo0accb3d2014-01-10 23:23:46 +000067typedef DenseMap<BasicBlock *, BasicBlock *> EquivalenceClassMap;
68typedef std::pair<BasicBlock *, BasicBlock *> Edge;
Diego Novillo92aa8c22014-03-10 22:41:28 +000069typedef DenseMap<Edge, unsigned> EdgeWeightMap;
Diego Novillo70959082014-03-14 22:07:18 +000070typedef DenseMap<BasicBlock *, SmallVector<BasicBlock *, 8>> BlockEdgeMap;
Diego Novilloc0dd1032013-11-26 20:37:33 +000071
Diego Novillode1ab262014-09-09 12:40:50 +000072/// \brief Sample profile pass.
Diego Novilloc0dd1032013-11-26 20:37:33 +000073///
Diego Novillode1ab262014-09-09 12:40:50 +000074/// This pass reads profile data from the file specified by
75/// -sample-profile-file and annotates every affected function with the
76/// profile information found in that file.
77class SampleProfileLoader : public FunctionPass {
Diego Novilloc0dd1032013-11-26 20:37:33 +000078public:
Diego Novillode1ab262014-09-09 12:40:50 +000079 // Class identification, replacement for typeinfo
80 static char ID;
Diego Novilloc0dd1032013-11-26 20:37:33 +000081
Diego Novillode1ab262014-09-09 12:40:50 +000082 SampleProfileLoader(StringRef Name = SampleProfileFile)
83 : FunctionPass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Ctx(nullptr),
84 Reader(), Samples(nullptr), Filename(Name), ProfileIsValid(false) {
85 initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry());
86 }
87
88 bool doInitialization(Module &M) override;
89
90 void dump() { Reader->dump(); }
91
92 const char *getPassName() const override { return "Sample profile pass"; }
93
94 bool runOnFunction(Function &F) override;
95
96 void getAnalysisUsage(AnalysisUsage &AU) const override {
97 AU.setPreservesCFG();
98 AU.addRequired<LoopInfo>();
99 AU.addRequired<DominatorTreeWrapperPass>();
100 AU.addRequired<PostDominatorTree>();
101 }
102
103protected:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000104 unsigned getFunctionLoc(Function &F);
Diego Novillode1ab262014-09-09 12:40:50 +0000105 bool emitAnnotations(Function &F);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000106 unsigned getInstWeight(Instruction &I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000107 unsigned getBlockWeight(BasicBlock *BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000108 void printEdgeWeight(raw_ostream &OS, Edge E);
109 void printBlockWeight(raw_ostream &OS, BasicBlock *BB);
110 void printBlockEquivalence(raw_ostream &OS, BasicBlock *BB);
111 bool computeBlockWeights(Function &F);
112 void findEquivalenceClasses(Function &F);
113 void findEquivalencesFor(BasicBlock *BB1,
114 SmallVector<BasicBlock *, 8> Descendants,
115 DominatorTreeBase<BasicBlock> *DomTree);
116 void propagateWeights(Function &F);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000117 unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000118 void buildEdges(Function &F);
119 bool propagateThroughEdges(Function &F);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000120
Diego Novillode1ab262014-09-09 12:40:50 +0000121 /// \brief Line number for the function header. Used to compute absolute
122 /// line numbers from the relative line numbers found in the profile.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000123 unsigned HeaderLineno;
124
Diego Novilloc0dd1032013-11-26 20:37:33 +0000125 /// \brief Map basic blocks to their computed weights.
126 ///
127 /// The weight of a basic block is defined to be the maximum
128 /// of all the instruction weights in that block.
129 BlockWeightMap BlockWeights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000130
131 /// \brief Map edges to their computed weights.
132 ///
133 /// Edge weights are computed by propagating basic block weights in
134 /// SampleProfile::propagateWeights.
135 EdgeWeightMap EdgeWeights;
136
137 /// \brief Set of visited blocks during propagation.
138 SmallPtrSet<BasicBlock *, 128> VisitedBlocks;
139
140 /// \brief Set of visited edges during propagation.
141 SmallSet<Edge, 128> VisitedEdges;
142
143 /// \brief Equivalence classes for block weights.
144 ///
145 /// Two blocks BB1 and BB2 are in the same equivalence class if they
146 /// dominate and post-dominate each other, and they are in the same loop
147 /// nest. When this happens, the two blocks are guaranteed to execute
148 /// the same number of times.
149 EquivalenceClassMap EquivalenceClass;
150
151 /// \brief Dominance, post-dominance and loop information.
152 DominatorTree *DT;
153 PostDominatorTree *PDT;
154 LoopInfo *LI;
155
156 /// \brief Predecessors for each basic block in the CFG.
157 BlockEdgeMap Predecessors;
158
159 /// \brief Successors for each basic block in the CFG.
160 BlockEdgeMap Successors;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000161
162 /// \brief LLVM context holding the debug data we need.
163 LLVMContext *Ctx;
Diego Novilloc0dd1032013-11-26 20:37:33 +0000164
Diego Novillo8d6568b2013-11-13 12:22:21 +0000165 /// \brief Profile reader object.
Diego Novillode1ab262014-09-09 12:40:50 +0000166 std::unique_ptr<SampleProfileReader> Reader;
167
168 /// \brief Samples collected for the body of this function.
169 FunctionSamples *Samples;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000170
171 /// \brief Name of the profile file to load.
172 StringRef Filename;
Diego Novilloa32aa322014-03-14 21:58:59 +0000173
Alp Toker16f98b22014-04-09 14:47:27 +0000174 /// \brief Flag indicating whether the profile input loaded successfully.
Diego Novilloa32aa322014-03-14 21:58:59 +0000175 bool ProfileIsValid;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000176};
177}
178
Diego Novillo0accb3d2014-01-10 23:23:46 +0000179/// \brief Print the weight of edge \p E on stream \p OS.
180///
181/// \param OS Stream to emit the output to.
182/// \param E Edge to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000183void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000184 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
185 << "]: " << EdgeWeights[E] << "\n";
186}
187
188/// \brief Print the equivalence class of block \p BB on stream \p OS.
189///
190/// \param OS Stream to emit the output to.
191/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000192void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
193 BasicBlock *BB) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000194 BasicBlock *Equiv = EquivalenceClass[BB];
195 OS << "equivalence[" << BB->getName()
196 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
197}
198
199/// \brief Print the weight of block \p BB on stream \p OS.
200///
201/// \param OS Stream to emit the output to.
202/// \param BB Block to print.
Diego Novillode1ab262014-09-09 12:40:50 +0000203void SampleProfileLoader::printBlockWeight(raw_ostream &OS, BasicBlock *BB) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000204 OS << "weight[" << BB->getName() << "]: " << BlockWeights[BB] << "\n";
205}
206
Diego Novillo0accb3d2014-01-10 23:23:46 +0000207/// \brief Get the weight for an instruction.
208///
209/// The "weight" of an instruction \p Inst is the number of samples
210/// collected on that instruction at runtime. To retrieve it, we
211/// need to compute the line number of \p Inst relative to the start of its
212/// function. We use HeaderLineno to compute the offset. We then
213/// look up the samples collected for \p Inst using BodySamples.
214///
215/// \param Inst Instruction to query.
216///
217/// \returns The profiled weight of I.
Diego Novillode1ab262014-09-09 12:40:50 +0000218unsigned SampleProfileLoader::getInstWeight(Instruction &Inst) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000219 DebugLoc DLoc = Inst.getDebugLoc();
220 unsigned Lineno = DLoc.getLine();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000221 if (Lineno < HeaderLineno)
222 return 0;
Diego Novillo92aa8c22014-03-10 22:41:28 +0000223
224 DILocation DIL(DLoc.getAsMDNode(*Ctx));
225 int LOffset = Lineno - HeaderLineno;
226 unsigned Discriminator = DIL.getDiscriminator();
Diego Novillode1ab262014-09-09 12:40:50 +0000227 unsigned Weight = Samples->samplesAt(LOffset, Discriminator);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000228 DEBUG(dbgs() << " " << Lineno << "." << Discriminator << ":" << Inst
229 << " (line offset: " << LOffset << "." << Discriminator
Diego Novillo0accb3d2014-01-10 23:23:46 +0000230 << " - weight: " << Weight << ")\n");
231 return Weight;
232}
233
234/// \brief Compute the weight of a basic block.
235///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000236/// The weight of basic block \p BB is the maximum weight of all the
237/// instructions in BB. The weight of \p BB is computed and cached in
Diego Novillo0accb3d2014-01-10 23:23:46 +0000238/// the BlockWeights map.
239///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000240/// \param BB The basic block to query.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000241///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000242/// \returns The computed weight of BB.
243unsigned SampleProfileLoader::getBlockWeight(BasicBlock *BB) {
244 // If we've computed BB's weight before, return it.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000245 std::pair<BlockWeightMap::iterator, bool> Entry =
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000246 BlockWeights.insert(std::make_pair(BB, 0));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000247 if (!Entry.second)
248 return Entry.first->second;
249
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000250 // Otherwise, compute and cache BB's weight.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000251 unsigned Weight = 0;
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000252 for (auto &I : BB->getInstList()) {
Diego Novillob368b7d2014-10-22 16:51:50 +0000253 unsigned InstWeight = getInstWeight(I);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000254 if (InstWeight > Weight)
255 Weight = InstWeight;
256 }
257 Entry.first->second = Weight;
258 return Weight;
259}
260
261/// \brief Compute and store the weights of every basic block.
262///
263/// This populates the BlockWeights map by computing
264/// the weights of every basic block in the CFG.
265///
266/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000267bool SampleProfileLoader::computeBlockWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000268 bool Changed = false;
269 DEBUG(dbgs() << "Block weights\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000270 for (auto &BB : F) {
271 unsigned Weight = getBlockWeight(&BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000272 Changed |= (Weight > 0);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000273 DEBUG(printBlockWeight(dbgs(), &BB));
Diego Novillo0accb3d2014-01-10 23:23:46 +0000274 }
275
276 return Changed;
277}
278
279/// \brief Find equivalence classes for the given block.
280///
281/// This finds all the blocks that are guaranteed to execute the same
282/// number of times as \p BB1. To do this, it traverses all the the
283/// descendants of \p BB1 in the dominator or post-dominator tree.
284///
285/// A block BB2 will be in the same equivalence class as \p BB1 if
286/// the following holds:
287///
288/// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
289/// is a descendant of \p BB1 in the dominator tree, then BB2 should
290/// dominate BB1 in the post-dominator tree.
291///
292/// 2- Both BB2 and \p BB1 must be in the same loop.
293///
294/// For every block BB2 that meets those two requirements, we set BB2's
295/// equivalence class to \p BB1.
296///
297/// \param BB1 Block to check.
298/// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
299/// \param DomTree Opposite dominator tree. If \p Descendants is filled
300/// with blocks from \p BB1's dominator tree, then
301/// this is the post-dominator tree, and vice versa.
Diego Novillode1ab262014-09-09 12:40:50 +0000302void SampleProfileLoader::findEquivalencesFor(
Diego Novillo0accb3d2014-01-10 23:23:46 +0000303 BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants,
304 DominatorTreeBase<BasicBlock> *DomTree) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000305 for (auto *BB2 : Descendants) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000306 bool IsDomParent = DomTree->dominates(BB2, BB1);
307 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
David Blaikie70573dc2014-11-19 07:49:26 +0000308 if (BB1 != BB2 && VisitedBlocks.insert(BB2).second && IsDomParent &&
Diego Novillo0accb3d2014-01-10 23:23:46 +0000309 IsInSameLoop) {
310 EquivalenceClass[BB2] = BB1;
311
312 // If BB2 is heavier than BB1, make BB2 have the same weight
313 // as BB1.
314 //
315 // Note that we don't worry about the opposite situation here
316 // (when BB2 is lighter than BB1). We will deal with this
317 // during the propagation phase. Right now, we just want to
318 // make sure that BB1 has the largest weight of all the
319 // members of its equivalence set.
Diego Novillo92aa8c22014-03-10 22:41:28 +0000320 unsigned &BB1Weight = BlockWeights[BB1];
321 unsigned &BB2Weight = BlockWeights[BB2];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000322 BB1Weight = std::max(BB1Weight, BB2Weight);
323 }
324 }
325}
326
327/// \brief Find equivalence classes.
328///
329/// Since samples may be missing from blocks, we can fill in the gaps by setting
330/// the weights of all the blocks in the same equivalence class to the same
331/// weight. To compute the concept of equivalence, we use dominance and loop
332/// information. Two blocks B1 and B2 are in the same equivalence class if B1
333/// dominates B2, B2 post-dominates B1 and both are in the same loop.
334///
335/// \param F The function to query.
Diego Novillode1ab262014-09-09 12:40:50 +0000336void SampleProfileLoader::findEquivalenceClasses(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000337 SmallVector<BasicBlock *, 8> DominatedBBs;
338 DEBUG(dbgs() << "\nBlock equivalence classes\n");
339 // Find equivalence sets based on dominance and post-dominance information.
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000340 for (auto &BB : F) {
341 BasicBlock *BB1 = &BB;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000342
343 // Compute BB1's equivalence class once.
344 if (EquivalenceClass.count(BB1)) {
345 DEBUG(printBlockEquivalence(dbgs(), BB1));
346 continue;
347 }
348
349 // By default, blocks are in their own equivalence class.
350 EquivalenceClass[BB1] = BB1;
351
352 // Traverse all the blocks dominated by BB1. We are looking for
353 // every basic block BB2 such that:
354 //
355 // 1- BB1 dominates BB2.
356 // 2- BB2 post-dominates BB1.
357 // 3- BB1 and BB2 are in the same loop nest.
358 //
359 // If all those conditions hold, it means that BB2 is executed
360 // as many times as BB1, so they are placed in the same equivalence
361 // class by making BB2's equivalence class be BB1.
362 DominatedBBs.clear();
363 DT->getDescendants(BB1, DominatedBBs);
364 findEquivalencesFor(BB1, DominatedBBs, PDT->DT);
365
366 // Repeat the same logic for all the blocks post-dominated by BB1.
367 // We are looking for every basic block BB2 such that:
368 //
369 // 1- BB1 post-dominates BB2.
370 // 2- BB2 dominates BB1.
371 // 3- BB1 and BB2 are in the same loop nest.
372 //
373 // If all those conditions hold, BB2's equivalence class is BB1.
374 DominatedBBs.clear();
375 PDT->getDescendants(BB1, DominatedBBs);
Chandler Carruth73523022014-01-13 13:07:17 +0000376 findEquivalencesFor(BB1, DominatedBBs, DT);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000377
378 DEBUG(printBlockEquivalence(dbgs(), BB1));
379 }
380
381 // Assign weights to equivalence classes.
382 //
383 // All the basic blocks in the same equivalence class will execute
384 // the same number of times. Since we know that the head block in
385 // each equivalence class has the largest weight, assign that weight
386 // to all the blocks in that equivalence class.
387 DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000388 for (auto &BI : F) {
389 BasicBlock *BB = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000390 BasicBlock *EquivBB = EquivalenceClass[BB];
391 if (BB != EquivBB)
392 BlockWeights[BB] = BlockWeights[EquivBB];
393 DEBUG(printBlockWeight(dbgs(), BB));
394 }
395}
396
397/// \brief Visit the given edge to decide if it has a valid weight.
398///
399/// If \p E has not been visited before, we copy to \p UnknownEdge
400/// and increment the count of unknown edges.
401///
402/// \param E Edge to visit.
403/// \param NumUnknownEdges Current number of unknown edges.
404/// \param UnknownEdge Set if E has not been visited before.
405///
406/// \returns E's weight, if known. Otherwise, return 0.
Diego Novillode1ab262014-09-09 12:40:50 +0000407unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
408 Edge *UnknownEdge) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000409 if (!VisitedEdges.count(E)) {
410 (*NumUnknownEdges)++;
411 *UnknownEdge = E;
412 return 0;
413 }
414
415 return EdgeWeights[E];
416}
417
418/// \brief Propagate weights through incoming/outgoing edges.
419///
420/// If the weight of a basic block is known, and there is only one edge
421/// with an unknown weight, we can calculate the weight of that edge.
422///
423/// Similarly, if all the edges have a known count, we can calculate the
424/// count of the basic block, if needed.
425///
426/// \param F Function to process.
427///
428/// \returns True if new weights were assigned to edges or blocks.
Diego Novillode1ab262014-09-09 12:40:50 +0000429bool SampleProfileLoader::propagateThroughEdges(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000430 bool Changed = false;
431 DEBUG(dbgs() << "\nPropagation through edges\n");
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000432 for (auto &BI : F) {
433 BasicBlock *BB = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000434
435 // Visit all the predecessor and successor edges to determine
436 // which ones have a weight assigned already. Note that it doesn't
437 // matter that we only keep track of a single unknown edge. The
438 // only case we are interested in handling is when only a single
439 // edge is unknown (see setEdgeOrBlockWeight).
440 for (unsigned i = 0; i < 2; i++) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000441 unsigned TotalWeight = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000442 unsigned NumUnknownEdges = 0;
443 Edge UnknownEdge, SelfReferentialEdge;
444
445 if (i == 0) {
446 // First, visit all predecessor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000447 for (auto *Pred : Predecessors[BB]) {
448 Edge E = std::make_pair(Pred, BB);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000449 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
450 if (E.first == E.second)
451 SelfReferentialEdge = E;
452 }
453 } else {
454 // On the second round, visit all successor edges.
Diego Novillob368b7d2014-10-22 16:51:50 +0000455 for (auto *Succ : Successors[BB]) {
456 Edge E = std::make_pair(BB, Succ);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000457 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
458 }
459 }
460
461 // After visiting all the edges, there are three cases that we
462 // can handle immediately:
463 //
464 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
465 // In this case, we simply check that the sum of all the edges
466 // is the same as BB's weight. If not, we change BB's weight
467 // to match. Additionally, if BB had not been visited before,
468 // we mark it visited.
469 //
470 // - Only one edge is unknown and BB has already been visited.
471 // In this case, we can compute the weight of the edge by
472 // subtracting the total block weight from all the known
473 // edge weights. If the edges weight more than BB, then the
474 // edge of the last remaining edge is set to zero.
475 //
476 // - There exists a self-referential edge and the weight of BB is
477 // known. In this case, this edge can be based on BB's weight.
478 // We add up all the other known edges and set the weight on
479 // the self-referential edge as we did in the previous case.
480 //
481 // In any other case, we must continue iterating. Eventually,
482 // all edges will get a weight, or iteration will stop when
483 // it reaches SampleProfileMaxPropagateIterations.
484 if (NumUnknownEdges <= 1) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000485 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000486 if (NumUnknownEdges == 0) {
487 // If we already know the weight of all edges, the weight of the
488 // basic block can be computed. It should be no larger than the sum
489 // of all edge weights.
490 if (TotalWeight > BBWeight) {
491 BBWeight = TotalWeight;
492 Changed = true;
493 DEBUG(dbgs() << "All edge weights for " << BB->getName()
494 << " known. Set weight for block: ";
495 printBlockWeight(dbgs(), BB););
496 }
David Blaikie70573dc2014-11-19 07:49:26 +0000497 if (VisitedBlocks.insert(BB).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000498 Changed = true;
499 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(BB)) {
500 // If there is a single unknown edge and the block has been
501 // visited, then we can compute E's weight.
502 if (BBWeight >= TotalWeight)
503 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
504 else
505 EdgeWeights[UnknownEdge] = 0;
506 VisitedEdges.insert(UnknownEdge);
507 Changed = true;
508 DEBUG(dbgs() << "Set weight for edge: ";
509 printEdgeWeight(dbgs(), UnknownEdge));
510 }
511 } else if (SelfReferentialEdge.first && VisitedBlocks.count(BB)) {
Diego Novillo92aa8c22014-03-10 22:41:28 +0000512 unsigned &BBWeight = BlockWeights[BB];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000513 // We have a self-referential edge and the weight of BB is known.
514 if (BBWeight >= TotalWeight)
515 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
516 else
517 EdgeWeights[SelfReferentialEdge] = 0;
518 VisitedEdges.insert(SelfReferentialEdge);
519 Changed = true;
520 DEBUG(dbgs() << "Set self-referential edge weight to: ";
521 printEdgeWeight(dbgs(), SelfReferentialEdge));
522 }
523 }
524 }
525
526 return Changed;
527}
528
529/// \brief Build in/out edge lists for each basic block in the CFG.
530///
531/// We are interested in unique edges. If a block B1 has multiple
532/// edges to another block B2, we only add a single B1->B2 edge.
Diego Novillode1ab262014-09-09 12:40:50 +0000533void SampleProfileLoader::buildEdges(Function &F) {
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000534 for (auto &BI : F) {
535 BasicBlock *B1 = &BI;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000536
537 // Add predecessors for B1.
538 SmallPtrSet<BasicBlock *, 16> Visited;
539 if (!Predecessors[B1].empty())
540 llvm_unreachable("Found a stale predecessors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000541 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
542 BasicBlock *B2 = *PI;
David Blaikie70573dc2014-11-19 07:49:26 +0000543 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000544 Predecessors[B1].push_back(B2);
545 }
546
547 // Add successors for B1.
548 Visited.clear();
549 if (!Successors[B1].empty())
550 llvm_unreachable("Found a stale successors list in a basic block.");
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000551 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
552 BasicBlock *B2 = *SI;
David Blaikie70573dc2014-11-19 07:49:26 +0000553 if (Visited.insert(B2).second)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000554 Successors[B1].push_back(B2);
555 }
556 }
557}
558
559/// \brief Propagate weights into edges
560///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000561/// The following rules are applied to every block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000562///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000563/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000564/// of that edge is the weight of the block.
565///
566/// - If all incoming or outgoing edges are known except one, and the
567/// weight of the block is already known, the weight of the unknown
568/// edge will be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000569/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000570/// we set the unknown edge weight to zero.
571///
572/// - If there is a self-referential edge, and the weight of the block is
573/// known, the weight for that edge is set to the weight of the block
574/// minus the weight of the other incoming edges to that block (if
575/// known).
Diego Novillode1ab262014-09-09 12:40:50 +0000576void SampleProfileLoader::propagateWeights(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000577 bool Changed = true;
578 unsigned i = 0;
579
580 // Before propagation starts, build, for each block, a list of
581 // unique predecessors and successors. This is necessary to handle
582 // identical edges in multiway branches. Since we visit all blocks and all
583 // edges of the CFG, it is cleaner to build these lists once at the start
584 // of the pass.
585 buildEdges(F);
586
587 // Propagate until we converge or we go past the iteration limit.
588 while (Changed && i++ < SampleProfileMaxPropagateIterations) {
589 Changed = propagateThroughEdges(F);
590 }
591
592 // Generate MD_prof metadata for every branch instruction using the
593 // edge weights computed during propagation.
594 DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
595 MDBuilder MDB(F.getContext());
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000596 for (auto &BI : F) {
597 BasicBlock *BB = &BI;
598 TerminatorInst *TI = BB->getTerminator();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000599 if (TI->getNumSuccessors() == 1)
600 continue;
601 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
602 continue;
603
604 DEBUG(dbgs() << "\nGetting weights for branch at line "
Diego Novillo92aa8c22014-03-10 22:41:28 +0000605 << TI->getDebugLoc().getLine() << ".\n");
606 SmallVector<unsigned, 4> Weights;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000607 bool AllWeightsZero = true;
608 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
609 BasicBlock *Succ = TI->getSuccessor(I);
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000610 Edge E = std::make_pair(BB, Succ);
Diego Novillo92aa8c22014-03-10 22:41:28 +0000611 unsigned Weight = EdgeWeights[E];
Diego Novillo0accb3d2014-01-10 23:23:46 +0000612 DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
613 Weights.push_back(Weight);
614 if (Weight != 0)
615 AllWeightsZero = false;
616 }
617
618 // Only set weights if there is at least one non-zero weight.
619 // In any other case, let the analyzer set weights.
620 if (!AllWeightsZero) {
621 DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
622 TI->setMetadata(llvm::LLVMContext::MD_prof,
623 MDB.createBranchWeights(Weights));
624 } else {
625 DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
626 }
627 }
628}
629
630/// \brief Get the line number for the function header.
631///
632/// This looks up function \p F in the current compilation unit and
633/// retrieves the line number where the function is defined. This is
634/// line 0 for all the samples read from the profile file. Every line
635/// number is relative to this line.
636///
637/// \param F Function object to query.
638///
Diego Novilloa32aa322014-03-14 21:58:59 +0000639/// \returns the line number where \p F is defined. If it returns 0,
640/// it means that there is no debug information available for \p F.
Diego Novillode1ab262014-09-09 12:40:50 +0000641unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
Timur Iskhodzhanoveb229ca2014-10-23 23:46:28 +0000642 DISubprogram S = getDISubprogram(&F);
Diego Novillo8027b802014-10-22 12:59:00 +0000643 if (S.isSubprogram())
644 return S.getLineNumber();
Diego Novillo0accb3d2014-01-10 23:23:46 +0000645
Diego Novillo8027b802014-10-22 12:59:00 +0000646 // If could not find the start of \p F, emit a diagnostic to inform the user
647 // about the missed opportunity.
David Blaikie61079682014-03-16 01:36:18 +0000648 F.getContext().diagnose(DiagnosticInfoSampleProfile(
Diego Novilloa67c0b42014-10-22 13:36:35 +0000649 "No debug information found in function " + F.getName() +
650 ": Function profile not used",
651 DS_Warning));
Diego Novilloa32aa322014-03-14 21:58:59 +0000652 return 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000653}
654
655/// \brief Generate branch weight metadata for all branches in \p F.
656///
657/// Branch weights are computed out of instruction samples using a
658/// propagation heuristic. Propagation proceeds in 3 phases:
659///
660/// 1- Assignment of block weights. All the basic blocks in the function
661/// are initial assigned the same weight as their most frequently
662/// executed instruction.
663///
664/// 2- Creation of equivalence classes. Since samples may be missing from
665/// blocks, we can fill in the gaps by setting the weights of all the
666/// blocks in the same equivalence class to the same weight. To compute
667/// the concept of equivalence, we use dominance and loop information.
668/// Two blocks B1 and B2 are in the same equivalence class if B1
669/// dominates B2, B2 post-dominates B1 and both are in the same loop.
670///
671/// 3- Propagation of block weights into edges. This uses a simple
672/// propagation heuristic. The following rules are applied to every
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000673/// block BB in the CFG:
Diego Novillo0accb3d2014-01-10 23:23:46 +0000674///
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000675/// - If BB has a single predecessor/successor, then the weight
Diego Novillo0accb3d2014-01-10 23:23:46 +0000676/// of that edge is the weight of the block.
677///
678/// - If all the edges are known except one, and the weight of the
679/// block is already known, the weight of the unknown edge will
680/// be the weight of the block minus the sum of all the known
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000681/// edges. If the sum of all the known edges is larger than BB's weight,
Diego Novillo0accb3d2014-01-10 23:23:46 +0000682/// we set the unknown edge weight to zero.
683///
684/// - If there is a self-referential edge, and the weight of the block is
685/// known, the weight for that edge is set to the weight of the block
686/// minus the weight of the other incoming edges to that block (if
687/// known).
688///
689/// Since this propagation is not guaranteed to finalize for every CFG, we
690/// only allow it to proceed for a limited number of iterations (controlled
691/// by -sample-profile-max-propagate-iterations).
692///
693/// FIXME: Try to replace this propagation heuristic with a scheme
694/// that is guaranteed to finalize. A work-list approach similar to
695/// the standard value propagation algorithm used by SSA-CCP might
696/// work here.
697///
698/// Once all the branch weights are computed, we emit the MD_prof
Diego Novillo19e7b7e2014-10-22 18:39:50 +0000699/// metadata on BB using the computed values for each of its branches.
Diego Novillo0accb3d2014-01-10 23:23:46 +0000700///
701/// \param F The function to query.
Diego Novilloa32aa322014-03-14 21:58:59 +0000702///
703/// \returns true if \p F was modified. Returns false, otherwise.
Diego Novillode1ab262014-09-09 12:40:50 +0000704bool SampleProfileLoader::emitAnnotations(Function &F) {
Diego Novillo0accb3d2014-01-10 23:23:46 +0000705 bool Changed = false;
706
707 // Initialize invariants used during computation and propagation.
708 HeaderLineno = getFunctionLoc(F);
Diego Novilloa32aa322014-03-14 21:58:59 +0000709 if (HeaderLineno == 0)
710 return false;
711
Diego Novillo0accb3d2014-01-10 23:23:46 +0000712 DEBUG(dbgs() << "Line number for the first instruction in " << F.getName()
713 << ": " << HeaderLineno << "\n");
Diego Novillo0accb3d2014-01-10 23:23:46 +0000714
715 // Compute basic block weights.
716 Changed |= computeBlockWeights(F);
717
718 if (Changed) {
719 // Find equivalence classes.
720 findEquivalenceClasses(F);
721
722 // Propagate weights to all edges.
723 propagateWeights(F);
724 }
725
726 return Changed;
727}
728
Diego Novilloc0dd1032013-11-26 20:37:33 +0000729char SampleProfileLoader::ID = 0;
Diego Novillo0accb3d2014-01-10 23:23:46 +0000730INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile",
731 "Sample Profile loader", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000732INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000733INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
734INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Diego Novillo92aa8c22014-03-10 22:41:28 +0000735INITIALIZE_PASS_DEPENDENCY(AddDiscriminators)
Diego Novillo0accb3d2014-01-10 23:23:46 +0000736INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile",
737 "Sample Profile loader", false, false)
Diego Novilloc0dd1032013-11-26 20:37:33 +0000738
739bool SampleProfileLoader::doInitialization(Module &M) {
Diego Novillofcd55602014-11-03 00:51:45 +0000740 auto ReaderOrErr = SampleProfileReader::create(Filename, M.getContext());
741 if (std::error_code EC = ReaderOrErr.getError()) {
Diego Novilloc572e922014-10-30 18:00:06 +0000742 std::string Msg = "Could not open profile: " + EC.message();
Diego Novillo77a5a5f2014-10-30 18:48:41 +0000743 M.getContext().diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg));
Diego Novilloc572e922014-10-30 18:00:06 +0000744 return false;
745 }
Diego Novillofcd55602014-11-03 00:51:45 +0000746 Reader = std::move(ReaderOrErr.get());
Diego Novilloc572e922014-10-30 18:00:06 +0000747 ProfileIsValid = (Reader->read() == sampleprof_error::success);
Diego Novilloc0dd1032013-11-26 20:37:33 +0000748 return true;
749}
750
751FunctionPass *llvm::createSampleProfileLoaderPass() {
752 return new SampleProfileLoader(SampleProfileFile);
753}
754
755FunctionPass *llvm::createSampleProfileLoaderPass(StringRef Name) {
756 return new SampleProfileLoader(Name);
757}
758
Diego Novillo8d6568b2013-11-13 12:22:21 +0000759bool SampleProfileLoader::runOnFunction(Function &F) {
Diego Novilloa32aa322014-03-14 21:58:59 +0000760 if (!ProfileIsValid)
761 return false;
Diego Novillode1ab262014-09-09 12:40:50 +0000762
763 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
764 PDT = &getAnalysis<PostDominatorTree>();
765 LI = &getAnalysis<LoopInfo>();
766 Ctx = &F.getParent()->getContext();
767 Samples = Reader->getSamplesFor(F);
768 if (!Samples->empty())
769 return emitAnnotations(F);
Diego Novillo0accb3d2014-01-10 23:23:46 +0000770 return false;
Diego Novillo8d6568b2013-11-13 12:22:21 +0000771}