Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1 | //===-- PGOInstrumentation.cpp - MST-based PGO Instrumentation ------------===// |
| 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 PGO instrumentation using a minimum spanning tree based |
| 11 | // on the following paper: |
| 12 | // [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points |
| 13 | // for program frequency counts. BIT Numerical Mathematics 1973, Volume 13, |
| 14 | // Issue 3, pp 313-322 |
| 15 | // The idea of the algorithm based on the fact that for each node (except for |
| 16 | // the entry and exit), the sum of incoming edge counts equals the sum of |
| 17 | // outgoing edge counts. The count of edge on spanning tree can be derived from |
| 18 | // those edges not on the spanning tree. Knuth proves this method instruments |
| 19 | // the minimum number of edges. |
| 20 | // |
| 21 | // The minimal spanning tree here is actually a maximum weight tree -- on-tree |
| 22 | // edges have higher frequencies (more likely to execute). The idea is to |
| 23 | // instrument those less frequently executed edges to reduce the runtime |
| 24 | // overhead of instrumented binaries. |
| 25 | // |
| 26 | // This file contains two passes: |
| 27 | // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 28 | // count profile, and generates the instrumentation for indirect call |
| 29 | // profiling. |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 30 | // (2) Pass PGOInstrumentationUse which reads the edge count profile and |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 31 | // annotates the branch weights. It also reads the indirect call value |
| 32 | // profiling records and annotate the indirect call instructions. |
| 33 | // |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 34 | // To get the precise counter information, These two passes need to invoke at |
| 35 | // the same compilation point (so they see the same IR). For pass |
| 36 | // PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For |
| 37 | // pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and |
| 38 | // the profile is opened in module level and passed to each PGOUseFunc instance. |
| 39 | // The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put |
| 40 | // in class FuncPGOInstrumentation. |
| 41 | // |
| 42 | // Class PGOEdge represents a CFG edge and some auxiliary information. Class |
| 43 | // BBInfo contains auxiliary information for each BB. These two classes are used |
| 44 | // in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived |
| 45 | // class of PGOEdge and BBInfo, respectively. They contains extra data structure |
| 46 | // used in populating profile counters. |
| 47 | // The MST implementation is in Class CFGMST (CFGMST.h). |
| 48 | // |
| 49 | //===----------------------------------------------------------------------===// |
| 50 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 51 | #include "llvm/Transforms/PGOInstrumentation.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 52 | #include "CFGMST.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 53 | #include "llvm/ADT/STLExtras.h" |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 54 | #include "llvm/ADT/SmallVector.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 55 | #include "llvm/ADT/Statistic.h" |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 56 | #include "llvm/ADT/Triple.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 57 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 58 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
| 59 | #include "llvm/Analysis/CFG.h" |
Teresa Johnson | 1e44b5d | 2016-07-12 21:13:44 +0000 | [diff] [blame] | 60 | #include "llvm/Analysis/IndirectCallSiteVisitor.h" |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 61 | #include "llvm/IR/CallSite.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 62 | #include "llvm/IR/DiagnosticInfo.h" |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 63 | #include "llvm/IR/GlobalValue.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 64 | #include "llvm/IR/IRBuilder.h" |
| 65 | #include "llvm/IR/InstIterator.h" |
| 66 | #include "llvm/IR/Instructions.h" |
| 67 | #include "llvm/IR/IntrinsicInst.h" |
| 68 | #include "llvm/IR/MDBuilder.h" |
| 69 | #include "llvm/IR/Module.h" |
| 70 | #include "llvm/Pass.h" |
| 71 | #include "llvm/ProfileData/InstrProfReader.h" |
Easwaran Raman | 5fe04a1 | 2016-05-26 22:57:11 +0000 | [diff] [blame] | 72 | #include "llvm/ProfileData/ProfileCommon.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 73 | #include "llvm/Support/BranchProbability.h" |
| 74 | #include "llvm/Support/Debug.h" |
| 75 | #include "llvm/Support/JamCRC.h" |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 76 | #include "llvm/Transforms/Instrumentation.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 77 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 78 | #include <algorithm> |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 79 | #include <string> |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 80 | #include <unordered_map> |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 81 | #include <utility> |
| 82 | #include <vector> |
| 83 | |
| 84 | using namespace llvm; |
| 85 | |
| 86 | #define DEBUG_TYPE "pgo-instrumentation" |
| 87 | |
| 88 | STATISTIC(NumOfPGOInstrument, "Number of edges instrumented."); |
| 89 | STATISTIC(NumOfPGOEdge, "Number of edges."); |
| 90 | STATISTIC(NumOfPGOBB, "Number of basic-blocks."); |
| 91 | STATISTIC(NumOfPGOSplit, "Number of critical edge splits."); |
| 92 | STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts."); |
| 93 | STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile."); |
| 94 | STATISTIC(NumOfPGOMissing, "Number of functions without profile."); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 95 | STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations."); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 96 | |
| 97 | // Command line option to specify the file to read profile from. This is |
| 98 | // mainly used for testing. |
| 99 | static cl::opt<std::string> |
| 100 | PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, |
| 101 | cl::value_desc("filename"), |
| 102 | cl::desc("Specify the path of profile data file. This is" |
| 103 | "mainly for test purpose.")); |
| 104 | |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 105 | // Command line option to disable value profiling. The default is false: |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 106 | // i.e. value profiling is enabled by default. This is for debug purpose. |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 107 | static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false), |
| 108 | cl::Hidden, |
| 109 | cl::desc("Disable Value Profiling")); |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 110 | |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 111 | // Command line option to set the maximum number of VP annotations to write to |
Rong Xu | 08afb05 | 2016-04-28 17:31:22 +0000 | [diff] [blame] | 112 | // the metadata for a single indirect call callsite. |
| 113 | static cl::opt<unsigned> MaxNumAnnotations( |
| 114 | "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore, |
| 115 | cl::desc("Max number of annotations for a single indirect " |
| 116 | "call callsite")); |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 117 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 118 | // Command line option to control appending FunctionHash to the name of a COMDAT |
| 119 | // function. This is to avoid the hash mismatch caused by the preinliner. |
| 120 | static cl::opt<bool> DoComdatRenaming( |
| 121 | "do-comdat-renaming", cl::init(true), cl::Hidden, |
| 122 | cl::desc("Append function hash to the name of COMDAT function to avoid " |
| 123 | "function hash mismatch due to the preinliner")); |
| 124 | |
Rong Xu | 0698de9 | 2016-05-13 17:26:06 +0000 | [diff] [blame] | 125 | // Command line option to enable/disable the warning about missing profile |
| 126 | // information. |
Xinliang David Li | 76a0108 | 2016-08-11 05:09:30 +0000 | [diff] [blame] | 127 | static cl::opt<bool> PGOWarnMissing("pgo-warn-missing-function", |
| 128 | cl::init(false), |
| 129 | cl::Hidden); |
Rong Xu | 0698de9 | 2016-05-13 17:26:06 +0000 | [diff] [blame] | 130 | |
| 131 | // Command line option to enable/disable the warning about a hash mismatch in |
| 132 | // the profile data. |
| 133 | static cl::opt<bool> NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), |
| 134 | cl::Hidden); |
| 135 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 136 | namespace { |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 137 | class PGOInstrumentationGenLegacyPass : public ModulePass { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 138 | public: |
| 139 | static char ID; |
| 140 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 141 | PGOInstrumentationGenLegacyPass() : ModulePass(ID) { |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 142 | initializePGOInstrumentationGenLegacyPassPass( |
| 143 | *PassRegistry::getPassRegistry()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 144 | } |
| 145 | |
| 146 | const char *getPassName() const override { |
| 147 | return "PGOInstrumentationGenPass"; |
| 148 | } |
| 149 | |
| 150 | private: |
| 151 | bool runOnModule(Module &M) override; |
| 152 | |
| 153 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 154 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
| 155 | } |
| 156 | }; |
| 157 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 158 | class PGOInstrumentationUseLegacyPass : public ModulePass { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 159 | public: |
| 160 | static char ID; |
| 161 | |
| 162 | // Provide the profile filename as the parameter. |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 163 | PGOInstrumentationUseLegacyPass(std::string Filename = "") |
Benjamin Kramer | 82de7d3 | 2016-05-27 14:27:24 +0000 | [diff] [blame] | 164 | : ModulePass(ID), ProfileFileName(std::move(Filename)) { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 165 | if (!PGOTestProfileFile.empty()) |
| 166 | ProfileFileName = PGOTestProfileFile; |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 167 | initializePGOInstrumentationUseLegacyPassPass( |
| 168 | *PassRegistry::getPassRegistry()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 169 | } |
| 170 | |
| 171 | const char *getPassName() const override { |
| 172 | return "PGOInstrumentationUsePass"; |
| 173 | } |
| 174 | |
| 175 | private: |
| 176 | std::string ProfileFileName; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 177 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 178 | bool runOnModule(Module &M) override; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 179 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 180 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
| 181 | } |
| 182 | }; |
| 183 | } // end anonymous namespace |
| 184 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 185 | char PGOInstrumentationGenLegacyPass::ID = 0; |
| 186 | INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 187 | "PGO instrumentation.", false, false) |
| 188 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 189 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 190 | INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 191 | "PGO instrumentation.", false, false) |
| 192 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 193 | ModulePass *llvm::createPGOInstrumentationGenLegacyPass() { |
| 194 | return new PGOInstrumentationGenLegacyPass(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 195 | } |
| 196 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 197 | char PGOInstrumentationUseLegacyPass::ID = 0; |
| 198 | INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 199 | "Read PGO instrumentation profile.", false, false) |
| 200 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 201 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 202 | INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 203 | "Read PGO instrumentation profile.", false, false) |
| 204 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 205 | ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) { |
| 206 | return new PGOInstrumentationUseLegacyPass(Filename.str()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 207 | } |
| 208 | |
| 209 | namespace { |
| 210 | /// \brief An MST based instrumentation for PGO |
| 211 | /// |
| 212 | /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO |
| 213 | /// in the function level. |
| 214 | struct PGOEdge { |
| 215 | // This class implements the CFG edges. Note the CFG can be a multi-graph. |
| 216 | // So there might be multiple edges with same SrcBB and DestBB. |
| 217 | const BasicBlock *SrcBB; |
| 218 | const BasicBlock *DestBB; |
| 219 | uint64_t Weight; |
| 220 | bool InMST; |
| 221 | bool Removed; |
| 222 | bool IsCritical; |
| 223 | PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) |
| 224 | : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false), |
| 225 | IsCritical(false) {} |
| 226 | // Return the information string of an edge. |
| 227 | const std::string infoString() const { |
| 228 | return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") + |
| 229 | (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str(); |
| 230 | } |
| 231 | }; |
| 232 | |
| 233 | // This class stores the auxiliary information for each BB. |
| 234 | struct BBInfo { |
| 235 | BBInfo *Group; |
| 236 | uint32_t Index; |
| 237 | uint32_t Rank; |
| 238 | |
| 239 | BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {} |
| 240 | |
| 241 | // Return the information string of this object. |
| 242 | const std::string infoString() const { |
| 243 | return (Twine("Index=") + Twine(Index)).str(); |
| 244 | } |
| 245 | }; |
| 246 | |
| 247 | // This class implements the CFG edges. Note the CFG can be a multi-graph. |
| 248 | template <class Edge, class BBInfo> class FuncPGOInstrumentation { |
| 249 | private: |
| 250 | Function &F; |
| 251 | void computeCFGHash(); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 252 | void renameComdatFunction(); |
| 253 | // A map that stores the Comdat group in function F. |
| 254 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 255 | |
| 256 | public: |
| 257 | std::string FuncName; |
| 258 | GlobalVariable *FuncNameVar; |
| 259 | // CFG hash value for this function. |
| 260 | uint64_t FunctionHash; |
| 261 | |
| 262 | // The Minimum Spanning Tree of function CFG. |
| 263 | CFGMST<Edge, BBInfo> MST; |
| 264 | |
| 265 | // Give an edge, find the BB that will be instrumented. |
| 266 | // Return nullptr if there is no BB to be instrumented. |
| 267 | BasicBlock *getInstrBB(Edge *E); |
| 268 | |
| 269 | // Return the auxiliary BB information. |
| 270 | BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); } |
| 271 | |
| 272 | // Dump edges and BB information. |
| 273 | void dumpInfo(std::string Str = "") const { |
| 274 | MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " + |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 275 | Twine(FunctionHash) + "\t" + Str); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 276 | } |
| 277 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 278 | FuncPGOInstrumentation( |
| 279 | Function &Func, |
| 280 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, |
| 281 | bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr, |
| 282 | BlockFrequencyInfo *BFI = nullptr) |
| 283 | : F(Func), ComdatMembers(ComdatMembers), FunctionHash(0), |
| 284 | MST(F, BPI, BFI) { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 285 | FuncName = getPGOFuncName(F); |
| 286 | computeCFGHash(); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 287 | if (ComdatMembers.size()) |
| 288 | renameComdatFunction(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 289 | DEBUG(dumpInfo("after CFGMST")); |
| 290 | |
| 291 | NumOfPGOBB += MST.BBInfos.size(); |
| 292 | for (auto &E : MST.AllEdges) { |
| 293 | if (E->Removed) |
| 294 | continue; |
| 295 | NumOfPGOEdge++; |
| 296 | if (!E->InMST) |
| 297 | NumOfPGOInstrument++; |
| 298 | } |
| 299 | |
| 300 | if (CreateGlobalVar) |
| 301 | FuncNameVar = createPGOFuncNameVar(F, FuncName); |
Eugene Zelenko | 6ac3f73 | 2016-01-26 18:48:36 +0000 | [diff] [blame] | 302 | } |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 303 | |
| 304 | // Return the number of profile counters needed for the function. |
| 305 | unsigned getNumCounters() { |
| 306 | unsigned NumCounters = 0; |
| 307 | for (auto &E : this->MST.AllEdges) { |
| 308 | if (!E->InMST && !E->Removed) |
| 309 | NumCounters++; |
| 310 | } |
| 311 | return NumCounters; |
| 312 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 313 | }; |
| 314 | |
| 315 | // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index |
| 316 | // value of each BB in the CFG. The higher 32 bits record the number of edges. |
| 317 | template <class Edge, class BBInfo> |
| 318 | void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() { |
| 319 | std::vector<char> Indexes; |
| 320 | JamCRC JC; |
| 321 | for (auto &BB : F) { |
| 322 | const TerminatorInst *TI = BB.getTerminator(); |
| 323 | for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) { |
| 324 | BasicBlock *Succ = TI->getSuccessor(I); |
| 325 | uint32_t Index = getBBInfo(Succ).Index; |
| 326 | for (int J = 0; J < 4; J++) |
| 327 | Indexes.push_back((char)(Index >> (J * 8))); |
| 328 | } |
| 329 | } |
| 330 | JC.update(Indexes); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 331 | FunctionHash = (uint64_t)findIndirectCallSites(F).size() << 48 | |
| 332 | (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC(); |
| 333 | } |
| 334 | |
| 335 | // Check if we can safely rename this Comdat function. |
| 336 | static bool canRenameComdat( |
| 337 | Function &F, |
| 338 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { |
| 339 | if (F.getName().empty()) |
| 340 | return false; |
| 341 | if (!needsComdatForCounter(F, *(F.getParent()))) |
| 342 | return false; |
| 343 | // Only safe to do if this function may be discarded if it is not used |
| 344 | // in the compilation unit. |
| 345 | if (!GlobalValue::isDiscardableIfUnused(F.getLinkage())) |
| 346 | return false; |
| 347 | |
| 348 | // For AvailableExternallyLinkage functions. |
| 349 | if (!F.hasComdat()) { |
| 350 | assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage); |
| 351 | return true; |
| 352 | } |
| 353 | |
| 354 | // FIXME: Current only handle those Comdat groups that only containing one |
| 355 | // function and function aliases. |
| 356 | // (1) For a Comdat group containing multiple functions, we need to have a |
| 357 | // unique postfix based on the hashes for each function. There is a |
| 358 | // non-trivial code refactoring to do this efficiently. |
| 359 | // (2) Variables can not be renamed, so we can not rename Comdat function in a |
| 360 | // group including global vars. |
| 361 | Comdat *C = F.getComdat(); |
| 362 | for (auto &&CM : make_range(ComdatMembers.equal_range(C))) { |
| 363 | if (dyn_cast<GlobalAlias>(CM.second)) |
| 364 | continue; |
| 365 | Function *FM = dyn_cast<Function>(CM.second); |
| 366 | if (FM != &F) |
| 367 | return false; |
| 368 | } |
| 369 | return true; |
| 370 | } |
| 371 | |
| 372 | // Append the CFGHash to the Comdat function name. |
| 373 | template <class Edge, class BBInfo> |
| 374 | void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() { |
| 375 | if (!canRenameComdat(F, ComdatMembers)) |
| 376 | return; |
| 377 | std::string NewFuncName = |
| 378 | Twine(F.getName() + "." + Twine(FunctionHash)).str(); |
| 379 | F.setName(Twine(NewFuncName)); |
| 380 | FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str(); |
| 381 | Comdat *NewComdat; |
| 382 | Module *M = F.getParent(); |
| 383 | // For AvailableExternallyLinkage functions, change the linkage to |
| 384 | // LinkOnceODR and put them into comdat. This is because after renaming, there |
| 385 | // is no backup external copy available for the function. |
| 386 | if (!F.hasComdat()) { |
| 387 | assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage); |
| 388 | NewComdat = M->getOrInsertComdat(StringRef(NewFuncName)); |
| 389 | F.setLinkage(GlobalValue::LinkOnceODRLinkage); |
| 390 | F.setComdat(NewComdat); |
| 391 | return; |
| 392 | } |
| 393 | |
| 394 | // This function belongs to a single function Comdat group. |
| 395 | Comdat *OrigComdat = F.getComdat(); |
| 396 | std::string NewComdatName = |
| 397 | Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str(); |
| 398 | NewComdat = M->getOrInsertComdat(StringRef(NewComdatName)); |
| 399 | NewComdat->setSelectionKind(OrigComdat->getSelectionKind()); |
| 400 | |
| 401 | for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) { |
| 402 | if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) { |
| 403 | // For aliases, change the name directly. |
| 404 | assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F); |
| 405 | GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash))); |
| 406 | continue; |
| 407 | } |
| 408 | // Must be a function. |
| 409 | Function *CF = dyn_cast<Function>(CM.second); |
| 410 | assert(CF); |
| 411 | CF->setComdat(NewComdat); |
| 412 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 413 | } |
| 414 | |
| 415 | // Given a CFG E to be instrumented, find which BB to place the instrumented |
| 416 | // code. The function will split the critical edge if necessary. |
| 417 | template <class Edge, class BBInfo> |
| 418 | BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) { |
| 419 | if (E->InMST || E->Removed) |
| 420 | return nullptr; |
| 421 | |
| 422 | BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); |
| 423 | BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); |
| 424 | // For a fake edge, instrument the real BB. |
| 425 | if (SrcBB == nullptr) |
| 426 | return DestBB; |
| 427 | if (DestBB == nullptr) |
| 428 | return SrcBB; |
| 429 | |
| 430 | // Instrument the SrcBB if it has a single successor, |
| 431 | // otherwise, the DestBB if this is not a critical edge. |
| 432 | TerminatorInst *TI = SrcBB->getTerminator(); |
| 433 | if (TI->getNumSuccessors() <= 1) |
| 434 | return SrcBB; |
| 435 | if (!E->IsCritical) |
| 436 | return DestBB; |
| 437 | |
| 438 | // For a critical edge, we have to split. Instrument the newly |
| 439 | // created BB. |
| 440 | NumOfPGOSplit++; |
| 441 | DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> " |
| 442 | << getBBInfo(DestBB).Index << "\n"); |
| 443 | unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); |
| 444 | BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum); |
| 445 | assert(InstrBB && "Critical edge is not split"); |
| 446 | |
| 447 | E->Removed = true; |
| 448 | return InstrBB; |
| 449 | } |
| 450 | |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 451 | // Visit all edge and instrument the edges not in MST, and do value profiling. |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 452 | // Critical edges will be split. |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 453 | static void instrumentOneFunc( |
| 454 | Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI, |
| 455 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 456 | FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI, |
| 457 | BFI); |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 458 | unsigned NumCounters = FuncInfo.getNumCounters(); |
| 459 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 460 | uint32_t I = 0; |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 461 | Type *I8PtrTy = Type::getInt8PtrTy(M->getContext()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 462 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 463 | BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get()); |
| 464 | if (!InstrBB) |
| 465 | continue; |
| 466 | |
| 467 | IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt()); |
| 468 | assert(Builder.GetInsertPoint() != InstrBB->end() && |
| 469 | "Cannot get the Instrumentation point"); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 470 | Builder.CreateCall( |
| 471 | Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment), |
| 472 | {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), |
| 473 | Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters), |
| 474 | Builder.getInt32(I++)}); |
| 475 | } |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 476 | assert(I == NumCounters); |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 477 | |
| 478 | if (DisableValueProfiling) |
| 479 | return; |
| 480 | |
| 481 | unsigned NumIndirectCallSites = 0; |
Rong Xu | 0eb3603 | 2016-04-01 23:16:44 +0000 | [diff] [blame] | 482 | for (auto &I : findIndirectCallSites(F)) { |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 483 | CallSite CS(I); |
| 484 | Value *Callee = CS.getCalledValue(); |
| 485 | DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = " |
| 486 | << NumIndirectCallSites << "\n"); |
| 487 | IRBuilder<> Builder(I); |
| 488 | assert(Builder.GetInsertPoint() != I->getParent()->end() && |
| 489 | "Cannot get the Instrumentation point"); |
| 490 | Builder.CreateCall( |
| 491 | Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile), |
| 492 | {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), |
| 493 | Builder.getInt64(FuncInfo.FunctionHash), |
| 494 | Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()), |
| 495 | Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget), |
| 496 | Builder.getInt32(NumIndirectCallSites++)}); |
| 497 | } |
| 498 | NumOfPGOICall += NumIndirectCallSites; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 499 | } |
| 500 | |
| 501 | // This class represents a CFG edge in profile use compilation. |
| 502 | struct PGOUseEdge : public PGOEdge { |
| 503 | bool CountValid; |
| 504 | uint64_t CountValue; |
| 505 | PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) |
| 506 | : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {} |
| 507 | |
| 508 | // Set edge count value |
| 509 | void setEdgeCount(uint64_t Value) { |
| 510 | CountValue = Value; |
| 511 | CountValid = true; |
| 512 | } |
| 513 | |
| 514 | // Return the information string for this object. |
| 515 | const std::string infoString() const { |
| 516 | if (!CountValid) |
| 517 | return PGOEdge::infoString(); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 518 | return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue)) |
| 519 | .str(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 520 | } |
| 521 | }; |
| 522 | |
| 523 | typedef SmallVector<PGOUseEdge *, 2> DirectEdges; |
| 524 | |
| 525 | // This class stores the auxiliary information for each BB. |
| 526 | struct UseBBInfo : public BBInfo { |
| 527 | uint64_t CountValue; |
| 528 | bool CountValid; |
| 529 | int32_t UnknownCountInEdge; |
| 530 | int32_t UnknownCountOutEdge; |
| 531 | DirectEdges InEdges; |
| 532 | DirectEdges OutEdges; |
| 533 | UseBBInfo(unsigned IX) |
| 534 | : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0), |
| 535 | UnknownCountOutEdge(0) {} |
| 536 | UseBBInfo(unsigned IX, uint64_t C) |
| 537 | : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0), |
| 538 | UnknownCountOutEdge(0) {} |
| 539 | |
| 540 | // Set the profile count value for this BB. |
| 541 | void setBBInfoCount(uint64_t Value) { |
| 542 | CountValue = Value; |
| 543 | CountValid = true; |
| 544 | } |
| 545 | |
| 546 | // Return the information string of this object. |
| 547 | const std::string infoString() const { |
| 548 | if (!CountValid) |
| 549 | return BBInfo::infoString(); |
| 550 | return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str(); |
| 551 | } |
| 552 | }; |
| 553 | |
| 554 | // Sum up the count values for all the edges. |
| 555 | static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) { |
| 556 | uint64_t Total = 0; |
| 557 | for (auto &E : Edges) { |
| 558 | if (E->Removed) |
| 559 | continue; |
| 560 | Total += E->CountValue; |
| 561 | } |
| 562 | return Total; |
| 563 | } |
| 564 | |
| 565 | class PGOUseFunc { |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 566 | public: |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 567 | PGOUseFunc(Function &Func, Module *Modu, |
| 568 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, |
| 569 | BranchProbabilityInfo *BPI = nullptr, |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 570 | BlockFrequencyInfo *BFI = nullptr) |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 571 | : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI), |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 572 | FreqAttr(FFA_Normal) {} |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 573 | |
| 574 | // Read counts for the instrumented BB from profile. |
| 575 | bool readCounters(IndexedInstrProfReader *PGOReader); |
| 576 | |
| 577 | // Populate the counts for all BBs. |
| 578 | void populateCounters(); |
| 579 | |
| 580 | // Set the branch weights based on the count values. |
| 581 | void setBranchWeights(); |
| 582 | |
| 583 | // Annotate the indirect call sites. |
| 584 | void annotateIndirectCallSites(); |
| 585 | |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 586 | // The hotness of the function from the profile count. |
| 587 | enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot }; |
| 588 | |
| 589 | // Return the function hotness from the profile. |
| 590 | FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; } |
| 591 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 592 | // Return the function hash. |
| 593 | uint64_t getFuncHash() const { return FuncInfo.FunctionHash; } |
Easwaran Raman | 5fe04a1 | 2016-05-26 22:57:11 +0000 | [diff] [blame] | 594 | // Return the profile record for this function; |
| 595 | InstrProfRecord &getProfileRecord() { return ProfileRecord; } |
| 596 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 597 | private: |
| 598 | Function &F; |
| 599 | Module *M; |
| 600 | // This member stores the shared information with class PGOGenFunc. |
| 601 | FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo; |
| 602 | |
| 603 | // Return the auxiliary BB information. |
| 604 | UseBBInfo &getBBInfo(const BasicBlock *BB) const { |
| 605 | return FuncInfo.getBBInfo(BB); |
| 606 | } |
| 607 | |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 608 | // The maximum count value in the profile. This is only used in PGO use |
| 609 | // compilation. |
| 610 | uint64_t ProgramMaxCount; |
| 611 | |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 612 | // ProfileRecord for this function. |
| 613 | InstrProfRecord ProfileRecord; |
| 614 | |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 615 | // Function hotness info derived from profile. |
| 616 | FuncFreqAttr FreqAttr; |
| 617 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 618 | // Find the Instrumented BB and set the value. |
| 619 | void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile); |
| 620 | |
| 621 | // Set the edge counter value for the unknown edge -- there should be only |
| 622 | // one unknown edge. |
| 623 | void setEdgeCount(DirectEdges &Edges, uint64_t Value); |
| 624 | |
| 625 | // Return FuncName string; |
| 626 | const std::string getFuncName() const { return FuncInfo.FuncName; } |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 627 | |
| 628 | // Set the hot/cold inline hints based on the count values. |
| 629 | // FIXME: This function should be removed once the functionality in |
| 630 | // the inliner is implemented. |
| 631 | void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) { |
| 632 | if (ProgramMaxCount == 0) |
| 633 | return; |
| 634 | // Threshold of the hot functions. |
| 635 | const BranchProbability HotFunctionThreshold(1, 100); |
| 636 | // Threshold of the cold functions. |
| 637 | const BranchProbability ColdFunctionThreshold(2, 10000); |
| 638 | if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount)) |
| 639 | FreqAttr = FFA_Hot; |
| 640 | else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount)) |
| 641 | FreqAttr = FFA_Cold; |
| 642 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 643 | }; |
| 644 | |
| 645 | // Visit all the edges and assign the count value for the instrumented |
| 646 | // edges and the BB. |
| 647 | void PGOUseFunc::setInstrumentedCounts( |
| 648 | const std::vector<uint64_t> &CountFromProfile) { |
| 649 | |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 650 | assert(FuncInfo.getNumCounters() == CountFromProfile.size()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 651 | // Use a worklist as we will update the vector during the iteration. |
| 652 | std::vector<PGOUseEdge *> WorkList; |
| 653 | for (auto &E : FuncInfo.MST.AllEdges) |
| 654 | WorkList.push_back(E.get()); |
| 655 | |
| 656 | uint32_t I = 0; |
| 657 | for (auto &E : WorkList) { |
| 658 | BasicBlock *InstrBB = FuncInfo.getInstrBB(E); |
| 659 | if (!InstrBB) |
| 660 | continue; |
| 661 | uint64_t CountValue = CountFromProfile[I++]; |
| 662 | if (!E->Removed) { |
| 663 | getBBInfo(InstrBB).setBBInfoCount(CountValue); |
| 664 | E->setEdgeCount(CountValue); |
| 665 | continue; |
| 666 | } |
| 667 | |
| 668 | // Need to add two new edges. |
| 669 | BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); |
| 670 | BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); |
| 671 | // Add new edge of SrcBB->InstrBB. |
| 672 | PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0); |
| 673 | NewEdge.setEdgeCount(CountValue); |
| 674 | // Add new edge of InstrBB->DestBB. |
| 675 | PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0); |
| 676 | NewEdge1.setEdgeCount(CountValue); |
| 677 | NewEdge1.InMST = true; |
| 678 | getBBInfo(InstrBB).setBBInfoCount(CountValue); |
| 679 | } |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 680 | assert(I == CountFromProfile.size()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 681 | } |
| 682 | |
| 683 | // Set the count value for the unknown edge. There should be one and only one |
| 684 | // unknown edge in Edges vector. |
| 685 | void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) { |
| 686 | for (auto &E : Edges) { |
| 687 | if (E->CountValid) |
| 688 | continue; |
| 689 | E->setEdgeCount(Value); |
| 690 | |
| 691 | getBBInfo(E->SrcBB).UnknownCountOutEdge--; |
| 692 | getBBInfo(E->DestBB).UnknownCountInEdge--; |
| 693 | return; |
| 694 | } |
| 695 | llvm_unreachable("Cannot find the unknown count edge"); |
| 696 | } |
| 697 | |
| 698 | // Read the profile from ProfileFileName and assign the value to the |
| 699 | // instrumented BB and the edges. This function also updates ProgramMaxCount. |
| 700 | // Return true if the profile are successfully read, and false on errors. |
| 701 | bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) { |
| 702 | auto &Ctx = M->getContext(); |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 703 | Expected<InstrProfRecord> Result = |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 704 | PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash); |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 705 | if (Error E = Result.takeError()) { |
| 706 | handleAllErrors(std::move(E), [&](const InstrProfError &IPE) { |
| 707 | auto Err = IPE.get(); |
| 708 | bool SkipWarning = false; |
| 709 | if (Err == instrprof_error::unknown_function) { |
| 710 | NumOfPGOMissing++; |
Xinliang David Li | 76a0108 | 2016-08-11 05:09:30 +0000 | [diff] [blame] | 711 | SkipWarning = !PGOWarnMissing; |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 712 | } else if (Err == instrprof_error::hash_mismatch || |
| 713 | Err == instrprof_error::malformed) { |
| 714 | NumOfPGOMismatch++; |
| 715 | SkipWarning = NoPGOWarnMismatch; |
| 716 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 717 | |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 718 | if (SkipWarning) |
| 719 | return; |
| 720 | |
| 721 | std::string Msg = IPE.message() + std::string(" ") + F.getName().str(); |
| 722 | Ctx.diagnose( |
| 723 | DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); |
| 724 | }); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 725 | return false; |
| 726 | } |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 727 | ProfileRecord = std::move(Result.get()); |
| 728 | std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 729 | |
| 730 | NumOfPGOFunc++; |
| 731 | DEBUG(dbgs() << CountFromProfile.size() << " counts\n"); |
| 732 | uint64_t ValueSum = 0; |
| 733 | for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) { |
| 734 | DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n"); |
| 735 | ValueSum += CountFromProfile[I]; |
| 736 | } |
| 737 | |
| 738 | DEBUG(dbgs() << "SUM = " << ValueSum << "\n"); |
| 739 | |
| 740 | getBBInfo(nullptr).UnknownCountOutEdge = 2; |
| 741 | getBBInfo(nullptr).UnknownCountInEdge = 2; |
| 742 | |
| 743 | setInstrumentedCounts(CountFromProfile); |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 744 | ProgramMaxCount = PGOReader->getMaximumFunctionCount(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 745 | return true; |
| 746 | } |
| 747 | |
| 748 | // Populate the counters from instrumented BBs to all BBs. |
| 749 | // In the end of this operation, all BBs should have a valid count value. |
| 750 | void PGOUseFunc::populateCounters() { |
| 751 | // First set up Count variable for all BBs. |
| 752 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 753 | if (E->Removed) |
| 754 | continue; |
| 755 | |
| 756 | const BasicBlock *SrcBB = E->SrcBB; |
| 757 | const BasicBlock *DestBB = E->DestBB; |
| 758 | UseBBInfo &SrcInfo = getBBInfo(SrcBB); |
| 759 | UseBBInfo &DestInfo = getBBInfo(DestBB); |
| 760 | SrcInfo.OutEdges.push_back(E.get()); |
| 761 | DestInfo.InEdges.push_back(E.get()); |
| 762 | SrcInfo.UnknownCountOutEdge++; |
| 763 | DestInfo.UnknownCountInEdge++; |
| 764 | |
| 765 | if (!E->CountValid) |
| 766 | continue; |
| 767 | DestInfo.UnknownCountInEdge--; |
| 768 | SrcInfo.UnknownCountOutEdge--; |
| 769 | } |
| 770 | |
| 771 | bool Changes = true; |
| 772 | unsigned NumPasses = 0; |
| 773 | while (Changes) { |
| 774 | NumPasses++; |
| 775 | Changes = false; |
| 776 | |
| 777 | // For efficient traversal, it's better to start from the end as most |
| 778 | // of the instrumented edges are at the end. |
| 779 | for (auto &BB : reverse(F)) { |
| 780 | UseBBInfo &Count = getBBInfo(&BB); |
| 781 | if (!Count.CountValid) { |
| 782 | if (Count.UnknownCountOutEdge == 0) { |
| 783 | Count.CountValue = sumEdgeCount(Count.OutEdges); |
| 784 | Count.CountValid = true; |
| 785 | Changes = true; |
| 786 | } else if (Count.UnknownCountInEdge == 0) { |
| 787 | Count.CountValue = sumEdgeCount(Count.InEdges); |
| 788 | Count.CountValid = true; |
| 789 | Changes = true; |
| 790 | } |
| 791 | } |
| 792 | if (Count.CountValid) { |
| 793 | if (Count.UnknownCountOutEdge == 1) { |
| 794 | uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges); |
| 795 | setEdgeCount(Count.OutEdges, Total); |
| 796 | Changes = true; |
| 797 | } |
| 798 | if (Count.UnknownCountInEdge == 1) { |
| 799 | uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges); |
| 800 | setEdgeCount(Count.InEdges, Total); |
| 801 | Changes = true; |
| 802 | } |
| 803 | } |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n"); |
Sean Silva | 8c7e121 | 2016-05-28 04:19:45 +0000 | [diff] [blame] | 808 | #ifndef NDEBUG |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 809 | // Assert every BB has a valid counter. |
Sean Silva | 8c7e121 | 2016-05-28 04:19:45 +0000 | [diff] [blame] | 810 | for (auto &BB : F) |
| 811 | assert(getBBInfo(&BB).CountValid && "BB count is not valid"); |
| 812 | #endif |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 813 | uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue; |
Sean Silva | 02b9d89 | 2016-05-28 04:05:36 +0000 | [diff] [blame] | 814 | F.setEntryCount(FuncEntryCount); |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 815 | uint64_t FuncMaxCount = FuncEntryCount; |
Sean Silva | 8c7e121 | 2016-05-28 04:19:45 +0000 | [diff] [blame] | 816 | for (auto &BB : F) |
| 817 | FuncMaxCount = std::max(FuncMaxCount, getBBInfo(&BB).CountValue); |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 818 | markFunctionAttributes(FuncEntryCount, FuncMaxCount); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 819 | |
| 820 | DEBUG(FuncInfo.dumpInfo("after reading profile.")); |
| 821 | } |
| 822 | |
Xinliang David Li | 2c93368 | 2016-08-19 05:31:33 +0000 | [diff] [blame^] | 823 | static void setProfMetadata(Module *M, TerminatorInst *TI, |
| 824 | ArrayRef<unsigned> EdgeCounts, uint64_t MaxCount) { |
| 825 | MDBuilder MDB(M->getContext()); |
| 826 | assert(MaxCount > 0 && "Bad max count"); |
| 827 | uint64_t Scale = calculateCountScale(MaxCount); |
| 828 | SmallVector<unsigned, 4> Weights; |
| 829 | for (const auto &ECI : EdgeCounts) |
| 830 | Weights.push_back(scaleBranchCount(ECI, Scale)); |
| 831 | |
| 832 | DEBUG(dbgs() << "Weight is: "; |
| 833 | for (const auto &W : Weights) { dbgs() << W << " "; } |
| 834 | dbgs() << "\n";); |
| 835 | TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); |
| 836 | } |
| 837 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 838 | // Assign the scaled count values to the BB with multiple out edges. |
| 839 | void PGOUseFunc::setBranchWeights() { |
| 840 | // Generate MD_prof metadata for every branch instruction. |
| 841 | DEBUG(dbgs() << "\nSetting branch weights.\n"); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 842 | for (auto &BB : F) { |
| 843 | TerminatorInst *TI = BB.getTerminator(); |
| 844 | if (TI->getNumSuccessors() < 2) |
| 845 | continue; |
| 846 | if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) |
| 847 | continue; |
| 848 | if (getBBInfo(&BB).CountValue == 0) |
| 849 | continue; |
| 850 | |
| 851 | // We have a non-zero Branch BB. |
| 852 | const UseBBInfo &BBCountInfo = getBBInfo(&BB); |
| 853 | unsigned Size = BBCountInfo.OutEdges.size(); |
| 854 | SmallVector<unsigned, 2> EdgeCounts(Size, 0); |
| 855 | uint64_t MaxCount = 0; |
| 856 | for (unsigned s = 0; s < Size; s++) { |
| 857 | const PGOUseEdge *E = BBCountInfo.OutEdges[s]; |
| 858 | const BasicBlock *SrcBB = E->SrcBB; |
| 859 | const BasicBlock *DestBB = E->DestBB; |
Eugene Zelenko | 6ac3f73 | 2016-01-26 18:48:36 +0000 | [diff] [blame] | 860 | if (DestBB == nullptr) |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 861 | continue; |
| 862 | unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); |
| 863 | uint64_t EdgeCount = E->CountValue; |
| 864 | if (EdgeCount > MaxCount) |
| 865 | MaxCount = EdgeCount; |
| 866 | EdgeCounts[SuccNum] = EdgeCount; |
| 867 | } |
Xinliang David Li | 2c93368 | 2016-08-19 05:31:33 +0000 | [diff] [blame^] | 868 | setProfMetadata(M, TI, EdgeCounts, MaxCount); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 869 | } |
| 870 | } |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 871 | |
| 872 | // Traverse all the indirect callsites and annotate the instructions. |
| 873 | void PGOUseFunc::annotateIndirectCallSites() { |
| 874 | if (DisableValueProfiling) |
| 875 | return; |
| 876 | |
Rong Xu | 8e8fe85 | 2016-04-01 16:43:30 +0000 | [diff] [blame] | 877 | // Create the PGOFuncName meta data. |
Rong Xu | f8f051c | 2016-04-22 21:00:17 +0000 | [diff] [blame] | 878 | createPGOFuncNameMetadata(F, FuncInfo.FuncName); |
Rong Xu | b534166 | 2016-03-30 18:37:52 +0000 | [diff] [blame] | 879 | |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 880 | unsigned IndirectCallSiteIndex = 0; |
Rong Xu | 0eb3603 | 2016-04-01 23:16:44 +0000 | [diff] [blame] | 881 | auto IndirectCallSites = findIndirectCallSites(F); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 882 | unsigned NumValueSites = |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 883 | ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget); |
Rong Xu | 0eb3603 | 2016-04-01 23:16:44 +0000 | [diff] [blame] | 884 | if (NumValueSites != IndirectCallSites.size()) { |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 885 | std::string Msg = |
| 886 | std::string("Inconsistent number of indirect call sites: ") + |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 887 | F.getName().str(); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 888 | auto &Ctx = M->getContext(); |
| 889 | Ctx.diagnose( |
| 890 | DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); |
| 891 | return; |
| 892 | } |
| 893 | |
Rong Xu | 0eb3603 | 2016-04-01 23:16:44 +0000 | [diff] [blame] | 894 | for (auto &I : IndirectCallSites) { |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 895 | DEBUG(dbgs() << "Read one indirect call instrumentation: Index=" |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 896 | << IndirectCallSiteIndex << " out of " << NumValueSites |
| 897 | << "\n"); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 898 | annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget, |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 899 | IndirectCallSiteIndex, MaxNumAnnotations); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 900 | IndirectCallSiteIndex++; |
| 901 | } |
| 902 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 903 | } // end anonymous namespace |
| 904 | |
Xinliang David Li | d382e9d | 2016-07-22 04:46:56 +0000 | [diff] [blame] | 905 | // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 906 | // aware this is an ir_level profile so it can set the version flag. |
| 907 | static void createIRLevelProfileFlagVariable(Module &M) { |
| 908 | Type *IntTy64 = Type::getInt64Ty(M.getContext()); |
| 909 | uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 910 | auto IRLevelVersionVariable = new GlobalVariable( |
| 911 | M, IntTy64, true, GlobalVariable::ExternalLinkage, |
| 912 | Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), |
Xinliang David Li | d382e9d | 2016-07-22 04:46:56 +0000 | [diff] [blame] | 913 | INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 914 | IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility); |
| 915 | Triple TT(M.getTargetTriple()); |
Xinliang David Li | 11c849c | 2016-05-27 16:22:03 +0000 | [diff] [blame] | 916 | if (!TT.supportsCOMDAT()) |
Rong Xu | ca28a0a | 2016-05-11 00:31:59 +0000 | [diff] [blame] | 917 | IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 918 | else |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 919 | IRLevelVersionVariable->setComdat(M.getOrInsertComdat( |
Xinliang David Li | d382e9d | 2016-07-22 04:46:56 +0000 | [diff] [blame] | 920 | StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)))); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 921 | } |
| 922 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 923 | // Collect the set of members for each Comdat in module M and store |
| 924 | // in ComdatMembers. |
| 925 | static void collectComdatMembers( |
| 926 | Module &M, |
| 927 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { |
| 928 | if (!DoComdatRenaming) |
| 929 | return; |
| 930 | for (Function &F : M) |
| 931 | if (Comdat *C = F.getComdat()) |
| 932 | ComdatMembers.insert(std::make_pair(C, &F)); |
| 933 | for (GlobalVariable &GV : M.globals()) |
| 934 | if (Comdat *C = GV.getComdat()) |
| 935 | ComdatMembers.insert(std::make_pair(C, &GV)); |
| 936 | for (GlobalAlias &GA : M.aliases()) |
| 937 | if (Comdat *C = GA.getComdat()) |
| 938 | ComdatMembers.insert(std::make_pair(C, &GA)); |
| 939 | } |
| 940 | |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 941 | static bool InstrumentAllFunctions( |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 942 | Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, |
| 943 | function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 944 | createIRLevelProfileFlagVariable(M); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 945 | std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; |
| 946 | collectComdatMembers(M, ComdatMembers); |
| 947 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 948 | for (auto &F : M) { |
| 949 | if (F.isDeclaration()) |
| 950 | continue; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 951 | auto *BPI = LookupBPI(F); |
| 952 | auto *BFI = LookupBFI(F); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 953 | instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 954 | } |
| 955 | return true; |
| 956 | } |
| 957 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 958 | bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) { |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 959 | if (skipModule(M)) |
| 960 | return false; |
| 961 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 962 | auto LookupBPI = [this](Function &F) { |
| 963 | return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 964 | }; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 965 | auto LookupBFI = [this](Function &F) { |
| 966 | return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 967 | }; |
| 968 | return InstrumentAllFunctions(M, LookupBPI, LookupBFI); |
| 969 | } |
| 970 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 971 | PreservedAnalyses PGOInstrumentationGen::run(Module &M, |
Sean Silva | fd03ac6 | 2016-08-09 00:28:38 +0000 | [diff] [blame] | 972 | ModuleAnalysisManager &AM) { |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 973 | |
| 974 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 975 | auto LookupBPI = [&FAM](Function &F) { |
| 976 | return &FAM.getResult<BranchProbabilityAnalysis>(F); |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 977 | }; |
| 978 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 979 | auto LookupBFI = [&FAM](Function &F) { |
| 980 | return &FAM.getResult<BlockFrequencyAnalysis>(F); |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 981 | }; |
| 982 | |
| 983 | if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI)) |
| 984 | return PreservedAnalyses::all(); |
| 985 | |
| 986 | return PreservedAnalyses::none(); |
| 987 | } |
| 988 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 989 | static bool annotateAllFunctions( |
| 990 | Module &M, StringRef ProfileFileName, |
| 991 | function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 992 | function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 993 | DEBUG(dbgs() << "Read in profile counters: "); |
| 994 | auto &Ctx = M.getContext(); |
| 995 | // Read the counter array from file. |
| 996 | auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName); |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 997 | if (Error E = ReaderOrErr.takeError()) { |
| 998 | handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { |
| 999 | Ctx.diagnose( |
| 1000 | DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message())); |
| 1001 | }); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1002 | return false; |
| 1003 | } |
| 1004 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1005 | std::unique_ptr<IndexedInstrProfReader> PGOReader = |
| 1006 | std::move(ReaderOrErr.get()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1007 | if (!PGOReader) { |
| 1008 | Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(), |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1009 | StringRef("Cannot get PGOReader"))); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1010 | return false; |
| 1011 | } |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 1012 | // TODO: might need to change the warning once the clang option is finalized. |
| 1013 | if (!PGOReader->isIRLevelProfile()) { |
| 1014 | Ctx.diagnose(DiagnosticInfoPGOProfile( |
| 1015 | ProfileFileName.data(), "Not an IR level instrumentation profile")); |
| 1016 | return false; |
| 1017 | } |
| 1018 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 1019 | std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; |
| 1020 | collectComdatMembers(M, ComdatMembers); |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 1021 | std::vector<Function *> HotFunctions; |
| 1022 | std::vector<Function *> ColdFunctions; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1023 | for (auto &F : M) { |
| 1024 | if (F.isDeclaration()) |
| 1025 | continue; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1026 | auto *BPI = LookupBPI(F); |
| 1027 | auto *BFI = LookupBFI(F); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 1028 | PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI); |
Sean Silva | 2e8f095 | 2016-05-28 04:19:40 +0000 | [diff] [blame] | 1029 | if (!Func.readCounters(PGOReader.get())) |
| 1030 | continue; |
| 1031 | Func.populateCounters(); |
| 1032 | Func.setBranchWeights(); |
| 1033 | Func.annotateIndirectCallSites(); |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 1034 | PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr(); |
| 1035 | if (FreqAttr == PGOUseFunc::FFA_Cold) |
Sean Silva | 2a73019 | 2016-05-28 03:02:50 +0000 | [diff] [blame] | 1036 | ColdFunctions.push_back(&F); |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 1037 | else if (FreqAttr == PGOUseFunc::FFA_Hot) |
| 1038 | HotFunctions.push_back(&F); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1039 | } |
Easwaran Raman | 8bceb9d | 2016-06-21 19:29:49 +0000 | [diff] [blame] | 1040 | M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext())); |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 1041 | // Set function hotness attribute from the profile. |
Sean Silva | 42cc342 | 2016-05-28 04:24:39 +0000 | [diff] [blame] | 1042 | // We have to apply these attributes at the end because their presence |
| 1043 | // can affect the BranchProbabilityInfo of any callers, resulting in an |
| 1044 | // inconsistent MST between prof-gen and prof-use. |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 1045 | for (auto &F : HotFunctions) { |
| 1046 | F->addFnAttr(llvm::Attribute::InlineHint); |
| 1047 | DEBUG(dbgs() << "Set inline attribute to function: " << F->getName() |
| 1048 | << "\n"); |
| 1049 | } |
| 1050 | for (auto &F : ColdFunctions) { |
| 1051 | F->addFnAttr(llvm::Attribute::Cold); |
| 1052 | DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n"); |
| 1053 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1054 | return true; |
| 1055 | } |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1056 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1057 | PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename) |
Benjamin Kramer | 82de7d3 | 2016-05-27 14:27:24 +0000 | [diff] [blame] | 1058 | : ProfileFileName(std::move(Filename)) { |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1059 | if (!PGOTestProfileFile.empty()) |
| 1060 | ProfileFileName = PGOTestProfileFile; |
| 1061 | } |
| 1062 | |
| 1063 | PreservedAnalyses PGOInstrumentationUse::run(Module &M, |
Sean Silva | fd03ac6 | 2016-08-09 00:28:38 +0000 | [diff] [blame] | 1064 | ModuleAnalysisManager &AM) { |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1065 | |
| 1066 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
| 1067 | auto LookupBPI = [&FAM](Function &F) { |
| 1068 | return &FAM.getResult<BranchProbabilityAnalysis>(F); |
| 1069 | }; |
| 1070 | |
| 1071 | auto LookupBFI = [&FAM](Function &F) { |
| 1072 | return &FAM.getResult<BlockFrequencyAnalysis>(F); |
| 1073 | }; |
| 1074 | |
| 1075 | if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI)) |
| 1076 | return PreservedAnalyses::all(); |
| 1077 | |
| 1078 | return PreservedAnalyses::none(); |
| 1079 | } |
| 1080 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1081 | bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) { |
| 1082 | if (skipModule(M)) |
| 1083 | return false; |
| 1084 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1085 | auto LookupBPI = [this](Function &F) { |
| 1086 | return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1087 | }; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1088 | auto LookupBFI = [this](Function &F) { |
| 1089 | return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1090 | }; |
| 1091 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1092 | return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI); |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1093 | } |