Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 1 | //===- 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 | |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/DenseMap.h" |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 26 | #include "llvm/ADT/SmallPtrSet.h" |
Chandler Carruth | 07baed5 | 2014-01-13 08:04:33 +0000 | [diff] [blame] | 27 | #include "llvm/ADT/SmallSet.h" |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 28 | #include "llvm/ADT/StringRef.h" |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/LoopInfo.h" |
Chandler Carruth | 07baed5 | 2014-01-13 08:04:33 +0000 | [diff] [blame] | 30 | #include "llvm/Analysis/PostDominators.h" |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Constants.h" |
Chandler Carruth | 9a4c9e5 | 2014-03-06 00:46:21 +0000 | [diff] [blame] | 32 | #include "llvm/IR/DebugInfo.h" |
Diego Novillo | a32aa32 | 2014-03-14 21:58:59 +0000 | [diff] [blame] | 33 | #include "llvm/IR/DiagnosticInfo.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 34 | #include "llvm/IR/Dominators.h" |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 35 | #include "llvm/IR/Function.h" |
Chandler Carruth | 8394857 | 2014-03-04 10:30:26 +0000 | [diff] [blame] | 36 | #include "llvm/IR/InstIterator.h" |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 37 | #include "llvm/IR/Instructions.h" |
| 38 | #include "llvm/IR/LLVMContext.h" |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 39 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 40 | #include "llvm/IR/Metadata.h" |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 41 | #include "llvm/IR/Module.h" |
| 42 | #include "llvm/Pass.h" |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 43 | #include "llvm/ProfileData/SampleProfReader.h" |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 44 | #include "llvm/Support/CommandLine.h" |
| 45 | #include "llvm/Support/Debug.h" |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 46 | #include "llvm/Support/ErrorOr.h" |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 47 | #include "llvm/Support/raw_ostream.h" |
Diego Novillo | 4d71113 | 2015-08-25 15:25:11 +0000 | [diff] [blame] | 48 | #include "llvm/Transforms/IPO.h" |
Dehao Chen | 6722688 | 2015-09-30 00:42:46 +0000 | [diff] [blame] | 49 | #include "llvm/Transforms/Utils/Cloning.h" |
Logan Chien | 61c6df0 | 2014-02-22 06:34:10 +0000 | [diff] [blame] | 50 | #include <cctype> |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 51 | |
| 52 | using namespace llvm; |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 53 | using namespace sampleprof; |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 54 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 55 | #define DEBUG_TYPE "sample-profile" |
| 56 | |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 57 | // Command line option to specify the file to read samples from. This is |
| 58 | // mainly used for debugging. |
| 59 | static cl::opt<std::string> SampleProfileFile( |
| 60 | "sample-profile-file", cl::init(""), cl::value_desc("filename"), |
| 61 | cl::desc("Profile file loaded by -sample-profile"), cl::Hidden); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 62 | static cl::opt<unsigned> SampleProfileMaxPropagateIterations( |
| 63 | "sample-profile-max-propagate-iterations", cl::init(100), |
| 64 | cl::desc("Maximum number of iterations to go through when propagating " |
| 65 | "sample block/edge weights through the CFG.")); |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 66 | |
| 67 | namespace { |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 68 | typedef DenseMap<const BasicBlock *, unsigned> BlockWeightMap; |
| 69 | typedef DenseMap<const BasicBlock *, const BasicBlock *> EquivalenceClassMap; |
| 70 | typedef std::pair<const BasicBlock *, const BasicBlock *> Edge; |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 71 | typedef DenseMap<Edge, unsigned> EdgeWeightMap; |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 72 | typedef DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>> |
| 73 | BlockEdgeMap; |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 74 | |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 75 | /// \brief Sample profile pass. |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 76 | /// |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 77 | /// This pass reads profile data from the file specified by |
| 78 | /// -sample-profile-file and annotates every affected function with the |
| 79 | /// profile information found in that file. |
Diego Novillo | 4d71113 | 2015-08-25 15:25:11 +0000 | [diff] [blame] | 80 | class SampleProfileLoader : public ModulePass { |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 81 | public: |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 82 | // Class identification, replacement for typeinfo |
| 83 | static char ID; |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 84 | |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 85 | SampleProfileLoader(StringRef Name = SampleProfileFile) |
Diego Novillo | 7732ae4 | 2015-08-26 20:00:27 +0000 | [diff] [blame] | 86 | : ModulePass(ID), DT(nullptr), PDT(nullptr), LI(nullptr), Reader(), |
| 87 | Samples(nullptr), Filename(Name), ProfileIsValid(false) { |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 88 | initializeSampleProfileLoaderPass(*PassRegistry::getPassRegistry()); |
| 89 | } |
| 90 | |
| 91 | bool doInitialization(Module &M) override; |
| 92 | |
| 93 | void dump() { Reader->dump(); } |
| 94 | |
| 95 | const char *getPassName() const override { return "Sample profile pass"; } |
| 96 | |
Diego Novillo | 4d71113 | 2015-08-25 15:25:11 +0000 | [diff] [blame] | 97 | bool runOnModule(Module &M) override; |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 98 | |
| 99 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 100 | AU.setPreservesCFG(); |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 101 | } |
| 102 | |
| 103 | protected: |
Diego Novillo | 4d71113 | 2015-08-25 15:25:11 +0000 | [diff] [blame] | 104 | bool runOnFunction(Function &F); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 105 | unsigned getFunctionLoc(Function &F); |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 106 | bool emitAnnotations(Function &F); |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 107 | ErrorOr<unsigned> getInstWeight(const Instruction &I) const; |
| 108 | ErrorOr<unsigned> getBlockWeight(const BasicBlock *BB) const; |
Dehao Chen | 6722688 | 2015-09-30 00:42:46 +0000 | [diff] [blame] | 109 | const FunctionSamples *findCalleeFunctionSamples(const CallInst &I) const; |
| 110 | const FunctionSamples *findFunctionSamples(const Instruction &I) const; |
| 111 | bool inlineHotFunctions(Function &F); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 112 | void printEdgeWeight(raw_ostream &OS, Edge E); |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 113 | void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const; |
| 114 | void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 115 | bool computeBlockWeights(Function &F); |
| 116 | void findEquivalenceClasses(Function &F); |
| 117 | void findEquivalencesFor(BasicBlock *BB1, |
| 118 | SmallVector<BasicBlock *, 8> Descendants, |
| 119 | DominatorTreeBase<BasicBlock> *DomTree); |
| 120 | void propagateWeights(Function &F); |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 121 | unsigned visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 122 | void buildEdges(Function &F); |
| 123 | bool propagateThroughEdges(Function &F); |
Diego Novillo | 7732ae4 | 2015-08-26 20:00:27 +0000 | [diff] [blame] | 124 | void computeDominanceAndLoopInfo(Function &F); |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 125 | |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 126 | /// \brief Line number for the function header. Used to compute absolute |
| 127 | /// line numbers from the relative line numbers found in the profile. |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 128 | unsigned HeaderLineno; |
| 129 | |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 130 | /// \brief Map basic blocks to their computed weights. |
| 131 | /// |
| 132 | /// The weight of a basic block is defined to be the maximum |
| 133 | /// of all the instruction weights in that block. |
| 134 | BlockWeightMap BlockWeights; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 135 | |
| 136 | /// \brief Map edges to their computed weights. |
| 137 | /// |
| 138 | /// Edge weights are computed by propagating basic block weights in |
| 139 | /// SampleProfile::propagateWeights. |
| 140 | EdgeWeightMap EdgeWeights; |
| 141 | |
| 142 | /// \brief Set of visited blocks during propagation. |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 143 | SmallPtrSet<const BasicBlock *, 128> VisitedBlocks; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 144 | |
| 145 | /// \brief Set of visited edges during propagation. |
| 146 | SmallSet<Edge, 128> VisitedEdges; |
| 147 | |
| 148 | /// \brief Equivalence classes for block weights. |
| 149 | /// |
| 150 | /// Two blocks BB1 and BB2 are in the same equivalence class if they |
| 151 | /// dominate and post-dominate each other, and they are in the same loop |
| 152 | /// nest. When this happens, the two blocks are guaranteed to execute |
| 153 | /// the same number of times. |
| 154 | EquivalenceClassMap EquivalenceClass; |
| 155 | |
| 156 | /// \brief Dominance, post-dominance and loop information. |
Diego Novillo | 7732ae4 | 2015-08-26 20:00:27 +0000 | [diff] [blame] | 157 | std::unique_ptr<DominatorTree> DT; |
| 158 | std::unique_ptr<DominatorTreeBase<BasicBlock>> PDT; |
| 159 | std::unique_ptr<LoopInfo> LI; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 160 | |
| 161 | /// \brief Predecessors for each basic block in the CFG. |
| 162 | BlockEdgeMap Predecessors; |
| 163 | |
| 164 | /// \brief Successors for each basic block in the CFG. |
| 165 | BlockEdgeMap Successors; |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 166 | |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 167 | /// \brief Profile reader object. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 168 | std::unique_ptr<SampleProfileReader> Reader; |
| 169 | |
| 170 | /// \brief Samples collected for the body of this function. |
| 171 | FunctionSamples *Samples; |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 172 | |
| 173 | /// \brief Name of the profile file to load. |
| 174 | StringRef Filename; |
Diego Novillo | a32aa32 | 2014-03-14 21:58:59 +0000 | [diff] [blame] | 175 | |
Alp Toker | 16f98b2 | 2014-04-09 14:47:27 +0000 | [diff] [blame] | 176 | /// \brief Flag indicating whether the profile input loaded successfully. |
Diego Novillo | a32aa32 | 2014-03-14 21:58:59 +0000 | [diff] [blame] | 177 | bool ProfileIsValid; |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 178 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 179 | } |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 180 | |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 181 | /// \brief Print the weight of edge \p E on stream \p OS. |
| 182 | /// |
| 183 | /// \param OS Stream to emit the output to. |
| 184 | /// \param E Edge to print. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 185 | void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) { |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 186 | OS << "weight[" << E.first->getName() << "->" << E.second->getName() |
| 187 | << "]: " << EdgeWeights[E] << "\n"; |
| 188 | } |
| 189 | |
| 190 | /// \brief Print the equivalence class of block \p BB on stream \p OS. |
| 191 | /// |
| 192 | /// \param OS Stream to emit the output to. |
| 193 | /// \param BB Block to print. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 194 | void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS, |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 195 | const BasicBlock *BB) { |
| 196 | const BasicBlock *Equiv = EquivalenceClass[BB]; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 197 | OS << "equivalence[" << BB->getName() |
| 198 | << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n"; |
| 199 | } |
| 200 | |
| 201 | /// \brief Print the weight of block \p BB on stream \p OS. |
| 202 | /// |
| 203 | /// \param OS Stream to emit the output to. |
| 204 | /// \param BB Block to print. |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 205 | void SampleProfileLoader::printBlockWeight(raw_ostream &OS, |
| 206 | const BasicBlock *BB) const { |
| 207 | const auto &I = BlockWeights.find(BB); |
| 208 | unsigned W = (I == BlockWeights.end() ? 0 : I->second); |
| 209 | OS << "weight[" << BB->getName() << "]: " << W << "\n"; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 210 | } |
| 211 | |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 212 | /// \brief Get the weight for an instruction. |
| 213 | /// |
| 214 | /// The "weight" of an instruction \p Inst is the number of samples |
| 215 | /// collected on that instruction at runtime. To retrieve it, we |
| 216 | /// need to compute the line number of \p Inst relative to the start of its |
| 217 | /// function. We use HeaderLineno to compute the offset. We then |
| 218 | /// look up the samples collected for \p Inst using BodySamples. |
| 219 | /// |
| 220 | /// \param Inst Instruction to query. |
| 221 | /// |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 222 | /// \returns the weight of \p Inst. |
| 223 | ErrorOr<unsigned> |
| 224 | SampleProfileLoader::getInstWeight(const Instruction &Inst) const { |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 225 | DebugLoc DLoc = Inst.getDebugLoc(); |
Duncan P. N. Exon Smith | ec819c0 | 2015-03-30 19:49:49 +0000 | [diff] [blame] | 226 | if (!DLoc) |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 227 | return std::error_code(); |
Duncan P. N. Exon Smith | 41a1546 | 2015-03-20 00:56:55 +0000 | [diff] [blame] | 228 | |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 229 | unsigned Lineno = DLoc.getLine(); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 230 | if (Lineno < HeaderLineno) |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 231 | return std::error_code(); |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 232 | |
Duncan P. N. Exon Smith | a9308c4 | 2015-04-29 16:38:44 +0000 | [diff] [blame] | 233 | const DILocation *DIL = DLoc; |
Dehao Chen | 6722688 | 2015-09-30 00:42:46 +0000 | [diff] [blame] | 234 | const FunctionSamples *FS = findFunctionSamples(Inst); |
| 235 | if (!FS) |
| 236 | return std::error_code(); |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 237 | ErrorOr<unsigned> R = |
Dehao Chen | 6722688 | 2015-09-30 00:42:46 +0000 | [diff] [blame] | 238 | FS->findSamplesAt(Lineno - HeaderLineno, DIL->getDiscriminator()); |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 239 | if (R) |
| 240 | DEBUG(dbgs() << " " << Lineno << "." << DIL->getDiscriminator() << ":" |
| 241 | << Inst << " (line offset: " << Lineno - HeaderLineno << "." |
| 242 | << DIL->getDiscriminator() << " - weight: " << R.get() |
| 243 | << ")\n"); |
| 244 | return R; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 245 | } |
| 246 | |
| 247 | /// \brief Compute the weight of a basic block. |
| 248 | /// |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 249 | /// The weight of basic block \p BB is the maximum weight of all the |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 250 | /// instructions in BB. |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 251 | /// |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 252 | /// \param BB The basic block to query. |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 253 | /// |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 254 | /// \returns the weight for \p BB. |
| 255 | ErrorOr<unsigned> |
| 256 | SampleProfileLoader::getBlockWeight(const BasicBlock *BB) const { |
| 257 | bool Found = false; |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 258 | unsigned Weight = 0; |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 259 | for (auto &I : BB->getInstList()) { |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 260 | const ErrorOr<unsigned> &R = getInstWeight(I); |
| 261 | if (R && R.get() >= Weight) { |
| 262 | Weight = R.get(); |
| 263 | Found = true; |
| 264 | } |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 265 | } |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 266 | if (Found) |
| 267 | return Weight; |
| 268 | else |
| 269 | return std::error_code(); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 270 | } |
| 271 | |
| 272 | /// \brief Compute and store the weights of every basic block. |
| 273 | /// |
| 274 | /// This populates the BlockWeights map by computing |
| 275 | /// the weights of every basic block in the CFG. |
| 276 | /// |
| 277 | /// \param F The function to query. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 278 | bool SampleProfileLoader::computeBlockWeights(Function &F) { |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 279 | bool Changed = false; |
| 280 | DEBUG(dbgs() << "Block weights\n"); |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 281 | for (const auto &BB : F) { |
| 282 | ErrorOr<unsigned> Weight = getBlockWeight(&BB); |
| 283 | if (Weight) { |
| 284 | BlockWeights[&BB] = Weight.get(); |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 285 | VisitedBlocks.insert(&BB); |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 286 | Changed = true; |
| 287 | } |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 288 | DEBUG(printBlockWeight(dbgs(), &BB)); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 289 | } |
| 290 | |
| 291 | return Changed; |
| 292 | } |
| 293 | |
Dehao Chen | 6722688 | 2015-09-30 00:42:46 +0000 | [diff] [blame] | 294 | /// \brief Get the FunctionSamples for a call instruction. |
| 295 | /// |
| 296 | /// The FunctionSamples of a call instruction \p Inst is the inlined |
| 297 | /// instance in which that call instruction is calling to. It contains |
| 298 | /// all samples that resides in the inlined instance. We first find the |
| 299 | /// inlined instance in which the call instruction is from, then we |
| 300 | /// traverse its children to find the callsite with the matching |
| 301 | /// location and callee function name. |
| 302 | /// |
| 303 | /// \param Inst Call instruction to query. |
| 304 | /// |
| 305 | /// \returns The FunctionSamples pointer to the inlined instance. |
| 306 | const FunctionSamples * |
| 307 | SampleProfileLoader::findCalleeFunctionSamples(const CallInst &Inst) const { |
| 308 | const DILocation *DIL = Inst.getDebugLoc(); |
| 309 | if (!DIL) { |
| 310 | return nullptr; |
| 311 | } |
| 312 | DISubprogram *SP = DIL->getScope()->getSubprogram(); |
| 313 | if (!SP || DIL->getLine() < SP->getLine()) |
| 314 | return nullptr; |
| 315 | |
| 316 | Function *CalleeFunc = Inst.getCalledFunction(); |
| 317 | if (!CalleeFunc) { |
| 318 | return nullptr; |
| 319 | } |
| 320 | |
| 321 | StringRef CalleeName = CalleeFunc->getName(); |
| 322 | const FunctionSamples *FS = findFunctionSamples(Inst); |
| 323 | if (FS == nullptr) |
| 324 | return nullptr; |
| 325 | |
| 326 | return FS->findFunctionSamplesAt(CallsiteLocation( |
| 327 | DIL->getLine() - SP->getLine(), DIL->getDiscriminator(), CalleeName)); |
| 328 | } |
| 329 | |
| 330 | /// \brief Get the FunctionSamples for an instruction. |
| 331 | /// |
| 332 | /// The FunctionSamples of an instruction \p Inst is the inlined instance |
| 333 | /// in which that instruction is coming from. We traverse the inline stack |
| 334 | /// of that instruction, and match it with the tree nodes in the profile. |
| 335 | /// |
| 336 | /// \param Inst Instruction to query. |
| 337 | /// |
| 338 | /// \returns the FunctionSamples pointer to the inlined instance. |
| 339 | const FunctionSamples * |
| 340 | SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const { |
| 341 | SmallVector<CallsiteLocation, 10> S; |
| 342 | const DILocation *DIL = Inst.getDebugLoc(); |
| 343 | if (!DIL) { |
| 344 | return Samples; |
| 345 | } |
| 346 | StringRef CalleeName; |
| 347 | for (const DILocation *DIL = Inst.getDebugLoc(); DIL; |
| 348 | DIL = DIL->getInlinedAt()) { |
| 349 | DISubprogram *SP = DIL->getScope()->getSubprogram(); |
| 350 | if (!SP || DIL->getLine() < SP->getLine()) |
| 351 | return nullptr; |
| 352 | if (!CalleeName.empty()) { |
| 353 | S.push_back(CallsiteLocation(DIL->getLine() - SP->getLine(), |
| 354 | DIL->getDiscriminator(), CalleeName)); |
| 355 | } |
| 356 | CalleeName = SP->getLinkageName(); |
| 357 | } |
| 358 | if (S.size() == 0) |
| 359 | return Samples; |
| 360 | const FunctionSamples *FS = Samples; |
| 361 | for (int i = S.size() - 1; i >= 0 && FS != nullptr; i--) { |
| 362 | FS = FS->findFunctionSamplesAt(S[i]); |
| 363 | } |
| 364 | return FS; |
| 365 | } |
| 366 | |
| 367 | /// \brief Iteratively inline hot callsites of a function. |
| 368 | /// |
| 369 | /// Iteratively traverse all callsites of the function \p F, and find if |
| 370 | /// the corresponding inlined instance exists and is hot in profile. If |
| 371 | /// it is hot enough, inline the callsites and adds new callsites of the |
| 372 | /// callee into the caller. |
| 373 | /// |
| 374 | /// TODO: investigate the possibility of not invoking InlineFunction directly. |
| 375 | /// |
| 376 | /// \param F function to perform iterative inlining. |
| 377 | /// |
| 378 | /// \returns True if there is any inline happened. |
| 379 | bool SampleProfileLoader::inlineHotFunctions(Function &F) { |
| 380 | bool Changed = false; |
| 381 | while (true) { |
| 382 | bool LocalChanged = false; |
| 383 | SmallVector<CallInst *, 10> CIS; |
| 384 | for (auto &BB : F) { |
| 385 | for (auto &I : BB.getInstList()) { |
| 386 | CallInst *CI = dyn_cast<CallInst>(&I); |
| 387 | if (CI) { |
| 388 | const FunctionSamples *FS = findCalleeFunctionSamples(*CI); |
| 389 | if (FS && FS->getTotalSamples() > 0) { |
| 390 | CIS.push_back(CI); |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | for (auto CI : CIS) { |
| 396 | InlineFunctionInfo IFI; |
| 397 | if (InlineFunction(CI, IFI)) |
| 398 | LocalChanged = true; |
| 399 | } |
| 400 | if (LocalChanged) { |
| 401 | Changed = true; |
| 402 | } else { |
| 403 | break; |
| 404 | } |
| 405 | } |
| 406 | return Changed; |
| 407 | } |
| 408 | |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 409 | /// \brief Find equivalence classes for the given block. |
| 410 | /// |
| 411 | /// This finds all the blocks that are guaranteed to execute the same |
Eric Christopher | 572e03a | 2015-06-19 01:53:21 +0000 | [diff] [blame] | 412 | /// number of times as \p BB1. To do this, it traverses all the |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 413 | /// descendants of \p BB1 in the dominator or post-dominator tree. |
| 414 | /// |
| 415 | /// A block BB2 will be in the same equivalence class as \p BB1 if |
| 416 | /// the following holds: |
| 417 | /// |
| 418 | /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2 |
| 419 | /// is a descendant of \p BB1 in the dominator tree, then BB2 should |
| 420 | /// dominate BB1 in the post-dominator tree. |
| 421 | /// |
| 422 | /// 2- Both BB2 and \p BB1 must be in the same loop. |
| 423 | /// |
| 424 | /// For every block BB2 that meets those two requirements, we set BB2's |
| 425 | /// equivalence class to \p BB1. |
| 426 | /// |
| 427 | /// \param BB1 Block to check. |
| 428 | /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree. |
| 429 | /// \param DomTree Opposite dominator tree. If \p Descendants is filled |
| 430 | /// with blocks from \p BB1's dominator tree, then |
| 431 | /// this is the post-dominator tree, and vice versa. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 432 | void SampleProfileLoader::findEquivalencesFor( |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 433 | BasicBlock *BB1, SmallVector<BasicBlock *, 8> Descendants, |
| 434 | DominatorTreeBase<BasicBlock> *DomTree) { |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 435 | const BasicBlock *EC = EquivalenceClass[BB1]; |
| 436 | unsigned Weight = BlockWeights[EC]; |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 437 | for (const auto *BB2 : Descendants) { |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 438 | bool IsDomParent = DomTree->dominates(BB2, BB1); |
| 439 | bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2); |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 440 | if (BB1 != BB2 && IsDomParent && IsInSameLoop) { |
| 441 | EquivalenceClass[BB2] = EC; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 442 | |
| 443 | // If BB2 is heavier than BB1, make BB2 have the same weight |
| 444 | // as BB1. |
| 445 | // |
| 446 | // Note that we don't worry about the opposite situation here |
| 447 | // (when BB2 is lighter than BB1). We will deal with this |
| 448 | // during the propagation phase. Right now, we just want to |
| 449 | // make sure that BB1 has the largest weight of all the |
| 450 | // members of its equivalence set. |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 451 | Weight = std::max(Weight, BlockWeights[BB2]); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 452 | } |
| 453 | } |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 454 | BlockWeights[EC] = Weight; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 455 | } |
| 456 | |
| 457 | /// \brief Find equivalence classes. |
| 458 | /// |
| 459 | /// Since samples may be missing from blocks, we can fill in the gaps by setting |
| 460 | /// the weights of all the blocks in the same equivalence class to the same |
| 461 | /// weight. To compute the concept of equivalence, we use dominance and loop |
| 462 | /// information. Two blocks B1 and B2 are in the same equivalence class if B1 |
| 463 | /// dominates B2, B2 post-dominates B1 and both are in the same loop. |
| 464 | /// |
| 465 | /// \param F The function to query. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 466 | void SampleProfileLoader::findEquivalenceClasses(Function &F) { |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 467 | SmallVector<BasicBlock *, 8> DominatedBBs; |
| 468 | DEBUG(dbgs() << "\nBlock equivalence classes\n"); |
| 469 | // Find equivalence sets based on dominance and post-dominance information. |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 470 | for (auto &BB : F) { |
| 471 | BasicBlock *BB1 = &BB; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 472 | |
| 473 | // Compute BB1's equivalence class once. |
| 474 | if (EquivalenceClass.count(BB1)) { |
| 475 | DEBUG(printBlockEquivalence(dbgs(), BB1)); |
| 476 | continue; |
| 477 | } |
| 478 | |
| 479 | // By default, blocks are in their own equivalence class. |
| 480 | EquivalenceClass[BB1] = BB1; |
| 481 | |
| 482 | // Traverse all the blocks dominated by BB1. We are looking for |
| 483 | // every basic block BB2 such that: |
| 484 | // |
| 485 | // 1- BB1 dominates BB2. |
| 486 | // 2- BB2 post-dominates BB1. |
| 487 | // 3- BB1 and BB2 are in the same loop nest. |
| 488 | // |
| 489 | // If all those conditions hold, it means that BB2 is executed |
| 490 | // as many times as BB1, so they are placed in the same equivalence |
| 491 | // class by making BB2's equivalence class be BB1. |
| 492 | DominatedBBs.clear(); |
| 493 | DT->getDescendants(BB1, DominatedBBs); |
Diego Novillo | 7732ae4 | 2015-08-26 20:00:27 +0000 | [diff] [blame] | 494 | findEquivalencesFor(BB1, DominatedBBs, PDT.get()); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 495 | |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 496 | DEBUG(printBlockEquivalence(dbgs(), BB1)); |
| 497 | } |
| 498 | |
| 499 | // Assign weights to equivalence classes. |
| 500 | // |
| 501 | // All the basic blocks in the same equivalence class will execute |
| 502 | // the same number of times. Since we know that the head block in |
| 503 | // each equivalence class has the largest weight, assign that weight |
| 504 | // to all the blocks in that equivalence class. |
| 505 | DEBUG(dbgs() << "\nAssign the same weight to all blocks in the same class\n"); |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 506 | for (auto &BI : F) { |
Dehao Chen | 8e7df83 | 2015-09-29 18:28:15 +0000 | [diff] [blame] | 507 | const BasicBlock *BB = &BI; |
| 508 | const BasicBlock *EquivBB = EquivalenceClass[BB]; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 509 | if (BB != EquivBB) |
| 510 | BlockWeights[BB] = BlockWeights[EquivBB]; |
| 511 | DEBUG(printBlockWeight(dbgs(), BB)); |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | /// \brief Visit the given edge to decide if it has a valid weight. |
| 516 | /// |
| 517 | /// If \p E has not been visited before, we copy to \p UnknownEdge |
| 518 | /// and increment the count of unknown edges. |
| 519 | /// |
| 520 | /// \param E Edge to visit. |
| 521 | /// \param NumUnknownEdges Current number of unknown edges. |
| 522 | /// \param UnknownEdge Set if E has not been visited before. |
| 523 | /// |
| 524 | /// \returns E's weight, if known. Otherwise, return 0. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 525 | unsigned SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges, |
| 526 | Edge *UnknownEdge) { |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 527 | if (!VisitedEdges.count(E)) { |
| 528 | (*NumUnknownEdges)++; |
| 529 | *UnknownEdge = E; |
| 530 | return 0; |
| 531 | } |
| 532 | |
| 533 | return EdgeWeights[E]; |
| 534 | } |
| 535 | |
| 536 | /// \brief Propagate weights through incoming/outgoing edges. |
| 537 | /// |
| 538 | /// If the weight of a basic block is known, and there is only one edge |
| 539 | /// with an unknown weight, we can calculate the weight of that edge. |
| 540 | /// |
| 541 | /// Similarly, if all the edges have a known count, we can calculate the |
| 542 | /// count of the basic block, if needed. |
| 543 | /// |
| 544 | /// \param F Function to process. |
| 545 | /// |
| 546 | /// \returns True if new weights were assigned to edges or blocks. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 547 | bool SampleProfileLoader::propagateThroughEdges(Function &F) { |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 548 | bool Changed = false; |
| 549 | DEBUG(dbgs() << "\nPropagation through edges\n"); |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 550 | for (const auto &BI : F) { |
| 551 | const BasicBlock *BB = &BI; |
| 552 | const BasicBlock *EC = EquivalenceClass[BB]; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 553 | |
| 554 | // Visit all the predecessor and successor edges to determine |
| 555 | // which ones have a weight assigned already. Note that it doesn't |
| 556 | // matter that we only keep track of a single unknown edge. The |
| 557 | // only case we are interested in handling is when only a single |
| 558 | // edge is unknown (see setEdgeOrBlockWeight). |
| 559 | for (unsigned i = 0; i < 2; i++) { |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 560 | unsigned TotalWeight = 0; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 561 | unsigned NumUnknownEdges = 0; |
| 562 | Edge UnknownEdge, SelfReferentialEdge; |
| 563 | |
| 564 | if (i == 0) { |
| 565 | // First, visit all predecessor edges. |
Diego Novillo | b368b7d | 2014-10-22 16:51:50 +0000 | [diff] [blame] | 566 | for (auto *Pred : Predecessors[BB]) { |
| 567 | Edge E = std::make_pair(Pred, BB); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 568 | TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); |
| 569 | if (E.first == E.second) |
| 570 | SelfReferentialEdge = E; |
| 571 | } |
| 572 | } else { |
| 573 | // On the second round, visit all successor edges. |
Diego Novillo | b368b7d | 2014-10-22 16:51:50 +0000 | [diff] [blame] | 574 | for (auto *Succ : Successors[BB]) { |
| 575 | Edge E = std::make_pair(BB, Succ); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 576 | TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge); |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | // After visiting all the edges, there are three cases that we |
| 581 | // can handle immediately: |
| 582 | // |
| 583 | // - All the edge weights are known (i.e., NumUnknownEdges == 0). |
| 584 | // In this case, we simply check that the sum of all the edges |
| 585 | // is the same as BB's weight. If not, we change BB's weight |
| 586 | // to match. Additionally, if BB had not been visited before, |
| 587 | // we mark it visited. |
| 588 | // |
| 589 | // - Only one edge is unknown and BB has already been visited. |
| 590 | // In this case, we can compute the weight of the edge by |
| 591 | // subtracting the total block weight from all the known |
| 592 | // edge weights. If the edges weight more than BB, then the |
| 593 | // edge of the last remaining edge is set to zero. |
| 594 | // |
| 595 | // - There exists a self-referential edge and the weight of BB is |
| 596 | // known. In this case, this edge can be based on BB's weight. |
| 597 | // We add up all the other known edges and set the weight on |
| 598 | // the self-referential edge as we did in the previous case. |
| 599 | // |
| 600 | // In any other case, we must continue iterating. Eventually, |
| 601 | // all edges will get a weight, or iteration will stop when |
| 602 | // it reaches SampleProfileMaxPropagateIterations. |
| 603 | if (NumUnknownEdges <= 1) { |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 604 | unsigned &BBWeight = BlockWeights[EC]; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 605 | if (NumUnknownEdges == 0) { |
| 606 | // If we already know the weight of all edges, the weight of the |
| 607 | // basic block can be computed. It should be no larger than the sum |
| 608 | // of all edge weights. |
| 609 | if (TotalWeight > BBWeight) { |
| 610 | BBWeight = TotalWeight; |
| 611 | Changed = true; |
| 612 | DEBUG(dbgs() << "All edge weights for " << BB->getName() |
| 613 | << " known. Set weight for block: "; |
| 614 | printBlockWeight(dbgs(), BB);); |
| 615 | } |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 616 | if (VisitedBlocks.insert(EC).second) |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 617 | Changed = true; |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 618 | } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) { |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 619 | // If there is a single unknown edge and the block has been |
| 620 | // visited, then we can compute E's weight. |
| 621 | if (BBWeight >= TotalWeight) |
| 622 | EdgeWeights[UnknownEdge] = BBWeight - TotalWeight; |
| 623 | else |
| 624 | EdgeWeights[UnknownEdge] = 0; |
| 625 | VisitedEdges.insert(UnknownEdge); |
| 626 | Changed = true; |
| 627 | DEBUG(dbgs() << "Set weight for edge: "; |
| 628 | printEdgeWeight(dbgs(), UnknownEdge)); |
| 629 | } |
Dehao Chen | 7c41dd6 | 2015-10-01 00:26:56 +0000 | [diff] [blame^] | 630 | } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) { |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 631 | unsigned &BBWeight = BlockWeights[BB]; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 632 | // We have a self-referential edge and the weight of BB is known. |
| 633 | if (BBWeight >= TotalWeight) |
| 634 | EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight; |
| 635 | else |
| 636 | EdgeWeights[SelfReferentialEdge] = 0; |
| 637 | VisitedEdges.insert(SelfReferentialEdge); |
| 638 | Changed = true; |
| 639 | DEBUG(dbgs() << "Set self-referential edge weight to: "; |
| 640 | printEdgeWeight(dbgs(), SelfReferentialEdge)); |
| 641 | } |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | return Changed; |
| 646 | } |
| 647 | |
| 648 | /// \brief Build in/out edge lists for each basic block in the CFG. |
| 649 | /// |
| 650 | /// We are interested in unique edges. If a block B1 has multiple |
| 651 | /// edges to another block B2, we only add a single B1->B2 edge. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 652 | void SampleProfileLoader::buildEdges(Function &F) { |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 653 | for (auto &BI : F) { |
| 654 | BasicBlock *B1 = &BI; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 655 | |
| 656 | // Add predecessors for B1. |
| 657 | SmallPtrSet<BasicBlock *, 16> Visited; |
| 658 | if (!Predecessors[B1].empty()) |
| 659 | llvm_unreachable("Found a stale predecessors list in a basic block."); |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 660 | for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) { |
| 661 | BasicBlock *B2 = *PI; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 662 | if (Visited.insert(B2).second) |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 663 | Predecessors[B1].push_back(B2); |
| 664 | } |
| 665 | |
| 666 | // Add successors for B1. |
| 667 | Visited.clear(); |
| 668 | if (!Successors[B1].empty()) |
| 669 | llvm_unreachable("Found a stale successors list in a basic block."); |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 670 | for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) { |
| 671 | BasicBlock *B2 = *SI; |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 672 | if (Visited.insert(B2).second) |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 673 | Successors[B1].push_back(B2); |
| 674 | } |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | /// \brief Propagate weights into edges |
| 679 | /// |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 680 | /// The following rules are applied to every block BB in the CFG: |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 681 | /// |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 682 | /// - If BB has a single predecessor/successor, then the weight |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 683 | /// of that edge is the weight of the block. |
| 684 | /// |
| 685 | /// - If all incoming or outgoing edges are known except one, and the |
| 686 | /// weight of the block is already known, the weight of the unknown |
| 687 | /// edge will be the weight of the block minus the sum of all the known |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 688 | /// edges. If the sum of all the known edges is larger than BB's weight, |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 689 | /// we set the unknown edge weight to zero. |
| 690 | /// |
| 691 | /// - If there is a self-referential edge, and the weight of the block is |
| 692 | /// known, the weight for that edge is set to the weight of the block |
| 693 | /// minus the weight of the other incoming edges to that block (if |
| 694 | /// known). |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 695 | void SampleProfileLoader::propagateWeights(Function &F) { |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 696 | bool Changed = true; |
| 697 | unsigned i = 0; |
| 698 | |
Diego Novillo | ffc84e3 | 2015-05-13 17:04:29 +0000 | [diff] [blame] | 699 | // Add an entry count to the function using the samples gathered |
| 700 | // at the function entry. |
| 701 | F.setEntryCount(Samples->getHeadSamples()); |
| 702 | |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 703 | // Before propagation starts, build, for each block, a list of |
| 704 | // unique predecessors and successors. This is necessary to handle |
| 705 | // identical edges in multiway branches. Since we visit all blocks and all |
| 706 | // edges of the CFG, it is cleaner to build these lists once at the start |
| 707 | // of the pass. |
| 708 | buildEdges(F); |
| 709 | |
| 710 | // Propagate until we converge or we go past the iteration limit. |
| 711 | while (Changed && i++ < SampleProfileMaxPropagateIterations) { |
| 712 | Changed = propagateThroughEdges(F); |
| 713 | } |
| 714 | |
| 715 | // Generate MD_prof metadata for every branch instruction using the |
| 716 | // edge weights computed during propagation. |
| 717 | DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n"); |
| 718 | MDBuilder MDB(F.getContext()); |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 719 | for (auto &BI : F) { |
| 720 | BasicBlock *BB = &BI; |
| 721 | TerminatorInst *TI = BB->getTerminator(); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 722 | if (TI->getNumSuccessors() == 1) |
| 723 | continue; |
| 724 | if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) |
| 725 | continue; |
| 726 | |
| 727 | DEBUG(dbgs() << "\nGetting weights for branch at line " |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 728 | << TI->getDebugLoc().getLine() << ".\n"); |
| 729 | SmallVector<unsigned, 4> Weights; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 730 | bool AllWeightsZero = true; |
| 731 | for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) { |
| 732 | BasicBlock *Succ = TI->getSuccessor(I); |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 733 | Edge E = std::make_pair(BB, Succ); |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 734 | unsigned Weight = EdgeWeights[E]; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 735 | DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E)); |
| 736 | Weights.push_back(Weight); |
| 737 | if (Weight != 0) |
| 738 | AllWeightsZero = false; |
| 739 | } |
| 740 | |
| 741 | // Only set weights if there is at least one non-zero weight. |
| 742 | // In any other case, let the analyzer set weights. |
| 743 | if (!AllWeightsZero) { |
| 744 | DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n"); |
| 745 | TI->setMetadata(llvm::LLVMContext::MD_prof, |
| 746 | MDB.createBranchWeights(Weights)); |
| 747 | } else { |
| 748 | DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n"); |
| 749 | } |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | /// \brief Get the line number for the function header. |
| 754 | /// |
| 755 | /// This looks up function \p F in the current compilation unit and |
| 756 | /// retrieves the line number where the function is defined. This is |
| 757 | /// line 0 for all the samples read from the profile file. Every line |
| 758 | /// number is relative to this line. |
| 759 | /// |
| 760 | /// \param F Function object to query. |
| 761 | /// |
Diego Novillo | a32aa32 | 2014-03-14 21:58:59 +0000 | [diff] [blame] | 762 | /// \returns the line number where \p F is defined. If it returns 0, |
| 763 | /// it means that there is no debug information available for \p F. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 764 | unsigned SampleProfileLoader::getFunctionLoc(Function &F) { |
Duncan P. N. Exon Smith | a9308c4 | 2015-04-29 16:38:44 +0000 | [diff] [blame] | 765 | if (DISubprogram *S = getDISubprogram(&F)) |
Duncan P. N. Exon Smith | 537b4a8 | 2015-04-14 03:40:37 +0000 | [diff] [blame] | 766 | return S->getLine(); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 767 | |
Diego Novillo | 8027b80 | 2014-10-22 12:59:00 +0000 | [diff] [blame] | 768 | // If could not find the start of \p F, emit a diagnostic to inform the user |
| 769 | // about the missed opportunity. |
David Blaikie | 6107968 | 2014-03-16 01:36:18 +0000 | [diff] [blame] | 770 | F.getContext().diagnose(DiagnosticInfoSampleProfile( |
Diego Novillo | a67c0b4 | 2014-10-22 13:36:35 +0000 | [diff] [blame] | 771 | "No debug information found in function " + F.getName() + |
| 772 | ": Function profile not used", |
| 773 | DS_Warning)); |
Diego Novillo | a32aa32 | 2014-03-14 21:58:59 +0000 | [diff] [blame] | 774 | return 0; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 775 | } |
| 776 | |
Diego Novillo | 7732ae4 | 2015-08-26 20:00:27 +0000 | [diff] [blame] | 777 | void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) { |
| 778 | DT.reset(new DominatorTree); |
| 779 | DT->recalculate(F); |
| 780 | |
| 781 | PDT.reset(new DominatorTreeBase<BasicBlock>(true)); |
| 782 | PDT->recalculate(F); |
| 783 | |
| 784 | LI.reset(new LoopInfo); |
| 785 | LI->analyze(*DT); |
| 786 | } |
| 787 | |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 788 | /// \brief Generate branch weight metadata for all branches in \p F. |
| 789 | /// |
| 790 | /// Branch weights are computed out of instruction samples using a |
| 791 | /// propagation heuristic. Propagation proceeds in 3 phases: |
| 792 | /// |
| 793 | /// 1- Assignment of block weights. All the basic blocks in the function |
| 794 | /// are initial assigned the same weight as their most frequently |
| 795 | /// executed instruction. |
| 796 | /// |
| 797 | /// 2- Creation of equivalence classes. Since samples may be missing from |
| 798 | /// blocks, we can fill in the gaps by setting the weights of all the |
| 799 | /// blocks in the same equivalence class to the same weight. To compute |
| 800 | /// the concept of equivalence, we use dominance and loop information. |
| 801 | /// Two blocks B1 and B2 are in the same equivalence class if B1 |
| 802 | /// dominates B2, B2 post-dominates B1 and both are in the same loop. |
| 803 | /// |
| 804 | /// 3- Propagation of block weights into edges. This uses a simple |
| 805 | /// propagation heuristic. The following rules are applied to every |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 806 | /// block BB in the CFG: |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 807 | /// |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 808 | /// - If BB has a single predecessor/successor, then the weight |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 809 | /// of that edge is the weight of the block. |
| 810 | /// |
| 811 | /// - If all the edges are known except one, and the weight of the |
| 812 | /// block is already known, the weight of the unknown edge will |
| 813 | /// be the weight of the block minus the sum of all the known |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 814 | /// edges. If the sum of all the known edges is larger than BB's weight, |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 815 | /// we set the unknown edge weight to zero. |
| 816 | /// |
| 817 | /// - If there is a self-referential edge, and the weight of the block is |
| 818 | /// known, the weight for that edge is set to the weight of the block |
| 819 | /// minus the weight of the other incoming edges to that block (if |
| 820 | /// known). |
| 821 | /// |
| 822 | /// Since this propagation is not guaranteed to finalize for every CFG, we |
| 823 | /// only allow it to proceed for a limited number of iterations (controlled |
| 824 | /// by -sample-profile-max-propagate-iterations). |
| 825 | /// |
| 826 | /// FIXME: Try to replace this propagation heuristic with a scheme |
| 827 | /// that is guaranteed to finalize. A work-list approach similar to |
| 828 | /// the standard value propagation algorithm used by SSA-CCP might |
| 829 | /// work here. |
| 830 | /// |
| 831 | /// Once all the branch weights are computed, we emit the MD_prof |
Diego Novillo | 19e7b7e | 2014-10-22 18:39:50 +0000 | [diff] [blame] | 832 | /// metadata on BB using the computed values for each of its branches. |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 833 | /// |
| 834 | /// \param F The function to query. |
Diego Novillo | a32aa32 | 2014-03-14 21:58:59 +0000 | [diff] [blame] | 835 | /// |
| 836 | /// \returns true if \p F was modified. Returns false, otherwise. |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 837 | bool SampleProfileLoader::emitAnnotations(Function &F) { |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 838 | bool Changed = false; |
| 839 | |
| 840 | // Initialize invariants used during computation and propagation. |
| 841 | HeaderLineno = getFunctionLoc(F); |
Diego Novillo | a32aa32 | 2014-03-14 21:58:59 +0000 | [diff] [blame] | 842 | if (HeaderLineno == 0) |
| 843 | return false; |
| 844 | |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 845 | DEBUG(dbgs() << "Line number for the first instruction in " << F.getName() |
| 846 | << ": " << HeaderLineno << "\n"); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 847 | |
Dehao Chen | 6722688 | 2015-09-30 00:42:46 +0000 | [diff] [blame] | 848 | Changed |= inlineHotFunctions(F); |
| 849 | |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 850 | // Compute basic block weights. |
| 851 | Changed |= computeBlockWeights(F); |
| 852 | |
| 853 | if (Changed) { |
Diego Novillo | 7732ae4 | 2015-08-26 20:00:27 +0000 | [diff] [blame] | 854 | // Compute dominance and loop info needed for propagation. |
| 855 | computeDominanceAndLoopInfo(F); |
| 856 | |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 857 | // Find equivalence classes. |
| 858 | findEquivalenceClasses(F); |
| 859 | |
| 860 | // Propagate weights to all edges. |
| 861 | propagateWeights(F); |
| 862 | } |
| 863 | |
| 864 | return Changed; |
| 865 | } |
| 866 | |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 867 | char SampleProfileLoader::ID = 0; |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 868 | INITIALIZE_PASS_BEGIN(SampleProfileLoader, "sample-profile", |
| 869 | "Sample Profile loader", false, false) |
Diego Novillo | 92aa8c2 | 2014-03-10 22:41:28 +0000 | [diff] [blame] | 870 | INITIALIZE_PASS_DEPENDENCY(AddDiscriminators) |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 871 | INITIALIZE_PASS_END(SampleProfileLoader, "sample-profile", |
| 872 | "Sample Profile loader", false, false) |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 873 | |
| 874 | bool SampleProfileLoader::doInitialization(Module &M) { |
Diego Novillo | 7732ae4 | 2015-08-26 20:00:27 +0000 | [diff] [blame] | 875 | auto &Ctx = M.getContext(); |
Diego Novillo | 4d71113 | 2015-08-25 15:25:11 +0000 | [diff] [blame] | 876 | auto ReaderOrErr = SampleProfileReader::create(Filename, Ctx); |
Diego Novillo | fcd5560 | 2014-11-03 00:51:45 +0000 | [diff] [blame] | 877 | if (std::error_code EC = ReaderOrErr.getError()) { |
Diego Novillo | c572e92 | 2014-10-30 18:00:06 +0000 | [diff] [blame] | 878 | std::string Msg = "Could not open profile: " + EC.message(); |
Diego Novillo | 4d71113 | 2015-08-25 15:25:11 +0000 | [diff] [blame] | 879 | Ctx.diagnose(DiagnosticInfoSampleProfile(Filename.data(), Msg)); |
Diego Novillo | c572e92 | 2014-10-30 18:00:06 +0000 | [diff] [blame] | 880 | return false; |
| 881 | } |
Diego Novillo | fcd5560 | 2014-11-03 00:51:45 +0000 | [diff] [blame] | 882 | Reader = std::move(ReaderOrErr.get()); |
Diego Novillo | c572e92 | 2014-10-30 18:00:06 +0000 | [diff] [blame] | 883 | ProfileIsValid = (Reader->read() == sampleprof_error::success); |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 884 | return true; |
| 885 | } |
| 886 | |
Diego Novillo | 4d71113 | 2015-08-25 15:25:11 +0000 | [diff] [blame] | 887 | ModulePass *llvm::createSampleProfileLoaderPass() { |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 888 | return new SampleProfileLoader(SampleProfileFile); |
| 889 | } |
| 890 | |
Diego Novillo | 4d71113 | 2015-08-25 15:25:11 +0000 | [diff] [blame] | 891 | ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) { |
Diego Novillo | c0dd103 | 2013-11-26 20:37:33 +0000 | [diff] [blame] | 892 | return new SampleProfileLoader(Name); |
| 893 | } |
| 894 | |
Diego Novillo | 4d71113 | 2015-08-25 15:25:11 +0000 | [diff] [blame] | 895 | bool SampleProfileLoader::runOnModule(Module &M) { |
| 896 | bool retval = false; |
| 897 | for (auto &F : M) |
| 898 | if (!F.isDeclaration()) |
| 899 | retval |= runOnFunction(F); |
| 900 | return retval; |
| 901 | } |
| 902 | |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 903 | bool SampleProfileLoader::runOnFunction(Function &F) { |
Diego Novillo | a32aa32 | 2014-03-14 21:58:59 +0000 | [diff] [blame] | 904 | if (!ProfileIsValid) |
| 905 | return false; |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 906 | |
Diego Novillo | de1ab26 | 2014-09-09 12:40:50 +0000 | [diff] [blame] | 907 | Samples = Reader->getSamplesFor(F); |
| 908 | if (!Samples->empty()) |
| 909 | return emitAnnotations(F); |
Diego Novillo | 0accb3d | 2014-01-10 23:23:46 +0000 | [diff] [blame] | 910 | return false; |
Diego Novillo | 8d6568b | 2013-11-13 12:22:21 +0000 | [diff] [blame] | 911 | } |