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 | 0eb3603 | 2016-04-01 23:16:44 +0000 | [diff] [blame] | 53 | #include "IndirectCallSiteVisitor.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 54 | #include "llvm/ADT/STLExtras.h" |
| 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" |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 60 | #include "llvm/IR/CallSite.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 61 | #include "llvm/IR/DiagnosticInfo.h" |
| 62 | #include "llvm/IR/IRBuilder.h" |
| 63 | #include "llvm/IR/InstIterator.h" |
| 64 | #include "llvm/IR/Instructions.h" |
| 65 | #include "llvm/IR/IntrinsicInst.h" |
| 66 | #include "llvm/IR/MDBuilder.h" |
| 67 | #include "llvm/IR/Module.h" |
| 68 | #include "llvm/Pass.h" |
| 69 | #include "llvm/ProfileData/InstrProfReader.h" |
| 70 | #include "llvm/Support/BranchProbability.h" |
| 71 | #include "llvm/Support/Debug.h" |
| 72 | #include "llvm/Support/JamCRC.h" |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 73 | #include "llvm/Transforms/Instrumentation.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 74 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 75 | #include <algorithm> |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 76 | #include <string> |
| 77 | #include <utility> |
| 78 | #include <vector> |
| 79 | |
| 80 | using namespace llvm; |
| 81 | |
| 82 | #define DEBUG_TYPE "pgo-instrumentation" |
| 83 | |
| 84 | STATISTIC(NumOfPGOInstrument, "Number of edges instrumented."); |
| 85 | STATISTIC(NumOfPGOEdge, "Number of edges."); |
| 86 | STATISTIC(NumOfPGOBB, "Number of basic-blocks."); |
| 87 | STATISTIC(NumOfPGOSplit, "Number of critical edge splits."); |
| 88 | STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts."); |
| 89 | STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile."); |
| 90 | STATISTIC(NumOfPGOMissing, "Number of functions without profile."); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 91 | STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations."); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 92 | |
| 93 | // Command line option to specify the file to read profile from. This is |
| 94 | // mainly used for testing. |
| 95 | static cl::opt<std::string> |
| 96 | PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, |
| 97 | cl::value_desc("filename"), |
| 98 | cl::desc("Specify the path of profile data file. This is" |
| 99 | "mainly for test purpose.")); |
| 100 | |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 101 | // Command line option to disable value profiling. The default is false: |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 102 | // 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] | 103 | static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false), |
| 104 | cl::Hidden, |
| 105 | cl::desc("Disable Value Profiling")); |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 106 | |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 107 | // 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] | 108 | // the metadata for a single indirect call callsite. |
| 109 | static cl::opt<unsigned> MaxNumAnnotations( |
| 110 | "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore, |
| 111 | cl::desc("Max number of annotations for a single indirect " |
| 112 | "call callsite")); |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 113 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 114 | namespace { |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 115 | class PGOInstrumentationGenLegacyPass : public ModulePass { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 116 | public: |
| 117 | static char ID; |
| 118 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 119 | PGOInstrumentationGenLegacyPass() : ModulePass(ID) { |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 120 | initializePGOInstrumentationGenLegacyPassPass( |
| 121 | *PassRegistry::getPassRegistry()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 122 | } |
| 123 | |
| 124 | const char *getPassName() const override { |
| 125 | return "PGOInstrumentationGenPass"; |
| 126 | } |
| 127 | |
| 128 | private: |
| 129 | bool runOnModule(Module &M) override; |
| 130 | |
| 131 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 132 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
| 133 | } |
| 134 | }; |
| 135 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 136 | class PGOInstrumentationUseLegacyPass : public ModulePass { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 137 | public: |
| 138 | static char ID; |
| 139 | |
| 140 | // Provide the profile filename as the parameter. |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 141 | PGOInstrumentationUseLegacyPass(std::string Filename = "") |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 142 | : ModulePass(ID), ProfileFileName(Filename) { |
| 143 | if (!PGOTestProfileFile.empty()) |
| 144 | ProfileFileName = PGOTestProfileFile; |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 145 | initializePGOInstrumentationUseLegacyPassPass( |
| 146 | *PassRegistry::getPassRegistry()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 147 | } |
| 148 | |
| 149 | const char *getPassName() const override { |
| 150 | return "PGOInstrumentationUsePass"; |
| 151 | } |
| 152 | |
| 153 | private: |
| 154 | std::string ProfileFileName; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 155 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame^] | 156 | bool runOnModule(Module &M) override; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 157 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 158 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
| 159 | } |
| 160 | }; |
| 161 | } // end anonymous namespace |
| 162 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 163 | char PGOInstrumentationGenLegacyPass::ID = 0; |
| 164 | INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 165 | "PGO instrumentation.", false, false) |
| 166 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 167 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 168 | INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 169 | "PGO instrumentation.", false, false) |
| 170 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 171 | ModulePass *llvm::createPGOInstrumentationGenLegacyPass() { |
| 172 | return new PGOInstrumentationGenLegacyPass(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 173 | } |
| 174 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 175 | char PGOInstrumentationUseLegacyPass::ID = 0; |
| 176 | INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 177 | "Read PGO instrumentation profile.", false, false) |
| 178 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 179 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 180 | INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 181 | "Read PGO instrumentation profile.", false, false) |
| 182 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 183 | ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) { |
| 184 | return new PGOInstrumentationUseLegacyPass(Filename.str()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 185 | } |
| 186 | |
| 187 | namespace { |
| 188 | /// \brief An MST based instrumentation for PGO |
| 189 | /// |
| 190 | /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO |
| 191 | /// in the function level. |
| 192 | struct PGOEdge { |
| 193 | // This class implements the CFG edges. Note the CFG can be a multi-graph. |
| 194 | // So there might be multiple edges with same SrcBB and DestBB. |
| 195 | const BasicBlock *SrcBB; |
| 196 | const BasicBlock *DestBB; |
| 197 | uint64_t Weight; |
| 198 | bool InMST; |
| 199 | bool Removed; |
| 200 | bool IsCritical; |
| 201 | PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) |
| 202 | : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false), |
| 203 | IsCritical(false) {} |
| 204 | // Return the information string of an edge. |
| 205 | const std::string infoString() const { |
| 206 | return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") + |
| 207 | (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str(); |
| 208 | } |
| 209 | }; |
| 210 | |
| 211 | // This class stores the auxiliary information for each BB. |
| 212 | struct BBInfo { |
| 213 | BBInfo *Group; |
| 214 | uint32_t Index; |
| 215 | uint32_t Rank; |
| 216 | |
| 217 | BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {} |
| 218 | |
| 219 | // Return the information string of this object. |
| 220 | const std::string infoString() const { |
| 221 | return (Twine("Index=") + Twine(Index)).str(); |
| 222 | } |
| 223 | }; |
| 224 | |
| 225 | // This class implements the CFG edges. Note the CFG can be a multi-graph. |
| 226 | template <class Edge, class BBInfo> class FuncPGOInstrumentation { |
| 227 | private: |
| 228 | Function &F; |
| 229 | void computeCFGHash(); |
| 230 | |
| 231 | public: |
| 232 | std::string FuncName; |
| 233 | GlobalVariable *FuncNameVar; |
| 234 | // CFG hash value for this function. |
| 235 | uint64_t FunctionHash; |
| 236 | |
| 237 | // The Minimum Spanning Tree of function CFG. |
| 238 | CFGMST<Edge, BBInfo> MST; |
| 239 | |
| 240 | // Give an edge, find the BB that will be instrumented. |
| 241 | // Return nullptr if there is no BB to be instrumented. |
| 242 | BasicBlock *getInstrBB(Edge *E); |
| 243 | |
| 244 | // Return the auxiliary BB information. |
| 245 | BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); } |
| 246 | |
| 247 | // Dump edges and BB information. |
| 248 | void dumpInfo(std::string Str = "") const { |
| 249 | MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " + |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 250 | Twine(FunctionHash) + "\t" + Str); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 251 | } |
| 252 | |
| 253 | FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false, |
| 254 | BranchProbabilityInfo *BPI = nullptr, |
| 255 | BlockFrequencyInfo *BFI = nullptr) |
| 256 | : F(Func), FunctionHash(0), MST(F, BPI, BFI) { |
| 257 | FuncName = getPGOFuncName(F); |
| 258 | computeCFGHash(); |
| 259 | DEBUG(dumpInfo("after CFGMST")); |
| 260 | |
| 261 | NumOfPGOBB += MST.BBInfos.size(); |
| 262 | for (auto &E : MST.AllEdges) { |
| 263 | if (E->Removed) |
| 264 | continue; |
| 265 | NumOfPGOEdge++; |
| 266 | if (!E->InMST) |
| 267 | NumOfPGOInstrument++; |
| 268 | } |
| 269 | |
| 270 | if (CreateGlobalVar) |
| 271 | FuncNameVar = createPGOFuncNameVar(F, FuncName); |
Eugene Zelenko | 6ac3f73 | 2016-01-26 18:48:36 +0000 | [diff] [blame] | 272 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 273 | }; |
| 274 | |
| 275 | // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index |
| 276 | // value of each BB in the CFG. The higher 32 bits record the number of edges. |
| 277 | template <class Edge, class BBInfo> |
| 278 | void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() { |
| 279 | std::vector<char> Indexes; |
| 280 | JamCRC JC; |
| 281 | for (auto &BB : F) { |
| 282 | const TerminatorInst *TI = BB.getTerminator(); |
| 283 | for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) { |
| 284 | BasicBlock *Succ = TI->getSuccessor(I); |
| 285 | uint32_t Index = getBBInfo(Succ).Index; |
| 286 | for (int J = 0; J < 4; J++) |
| 287 | Indexes.push_back((char)(Index >> (J * 8))); |
| 288 | } |
| 289 | } |
| 290 | JC.update(Indexes); |
| 291 | FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC(); |
| 292 | } |
| 293 | |
| 294 | // Given a CFG E to be instrumented, find which BB to place the instrumented |
| 295 | // code. The function will split the critical edge if necessary. |
| 296 | template <class Edge, class BBInfo> |
| 297 | BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) { |
| 298 | if (E->InMST || E->Removed) |
| 299 | return nullptr; |
| 300 | |
| 301 | BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); |
| 302 | BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); |
| 303 | // For a fake edge, instrument the real BB. |
| 304 | if (SrcBB == nullptr) |
| 305 | return DestBB; |
| 306 | if (DestBB == nullptr) |
| 307 | return SrcBB; |
| 308 | |
| 309 | // Instrument the SrcBB if it has a single successor, |
| 310 | // otherwise, the DestBB if this is not a critical edge. |
| 311 | TerminatorInst *TI = SrcBB->getTerminator(); |
| 312 | if (TI->getNumSuccessors() <= 1) |
| 313 | return SrcBB; |
| 314 | if (!E->IsCritical) |
| 315 | return DestBB; |
| 316 | |
| 317 | // For a critical edge, we have to split. Instrument the newly |
| 318 | // created BB. |
| 319 | NumOfPGOSplit++; |
| 320 | DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> " |
| 321 | << getBBInfo(DestBB).Index << "\n"); |
| 322 | unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); |
| 323 | BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum); |
| 324 | assert(InstrBB && "Critical edge is not split"); |
| 325 | |
| 326 | E->Removed = true; |
| 327 | return InstrBB; |
| 328 | } |
| 329 | |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 330 | // 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] | 331 | // Critical edges will be split. |
| 332 | static void instrumentOneFunc(Function &F, Module *M, |
| 333 | BranchProbabilityInfo *BPI, |
| 334 | BlockFrequencyInfo *BFI) { |
| 335 | unsigned NumCounters = 0; |
| 336 | FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI); |
| 337 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 338 | if (!E->InMST && !E->Removed) |
| 339 | NumCounters++; |
| 340 | } |
| 341 | |
| 342 | uint32_t I = 0; |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 343 | Type *I8PtrTy = Type::getInt8PtrTy(M->getContext()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 344 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 345 | BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get()); |
| 346 | if (!InstrBB) |
| 347 | continue; |
| 348 | |
| 349 | IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt()); |
| 350 | assert(Builder.GetInsertPoint() != InstrBB->end() && |
| 351 | "Cannot get the Instrumentation point"); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 352 | Builder.CreateCall( |
| 353 | Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment), |
| 354 | {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), |
| 355 | Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters), |
| 356 | Builder.getInt32(I++)}); |
| 357 | } |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 358 | |
| 359 | if (DisableValueProfiling) |
| 360 | return; |
| 361 | |
| 362 | unsigned NumIndirectCallSites = 0; |
Rong Xu | 0eb3603 | 2016-04-01 23:16:44 +0000 | [diff] [blame] | 363 | for (auto &I : findIndirectCallSites(F)) { |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 364 | CallSite CS(I); |
| 365 | Value *Callee = CS.getCalledValue(); |
| 366 | DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = " |
| 367 | << NumIndirectCallSites << "\n"); |
| 368 | IRBuilder<> Builder(I); |
| 369 | assert(Builder.GetInsertPoint() != I->getParent()->end() && |
| 370 | "Cannot get the Instrumentation point"); |
| 371 | Builder.CreateCall( |
| 372 | Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile), |
| 373 | {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), |
| 374 | Builder.getInt64(FuncInfo.FunctionHash), |
| 375 | Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()), |
| 376 | Builder.getInt32(llvm::InstrProfValueKind::IPVK_IndirectCallTarget), |
| 377 | Builder.getInt32(NumIndirectCallSites++)}); |
| 378 | } |
| 379 | NumOfPGOICall += NumIndirectCallSites; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 380 | } |
| 381 | |
| 382 | // This class represents a CFG edge in profile use compilation. |
| 383 | struct PGOUseEdge : public PGOEdge { |
| 384 | bool CountValid; |
| 385 | uint64_t CountValue; |
| 386 | PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) |
| 387 | : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {} |
| 388 | |
| 389 | // Set edge count value |
| 390 | void setEdgeCount(uint64_t Value) { |
| 391 | CountValue = Value; |
| 392 | CountValid = true; |
| 393 | } |
| 394 | |
| 395 | // Return the information string for this object. |
| 396 | const std::string infoString() const { |
| 397 | if (!CountValid) |
| 398 | return PGOEdge::infoString(); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 399 | return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue)) |
| 400 | .str(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 401 | } |
| 402 | }; |
| 403 | |
| 404 | typedef SmallVector<PGOUseEdge *, 2> DirectEdges; |
| 405 | |
| 406 | // This class stores the auxiliary information for each BB. |
| 407 | struct UseBBInfo : public BBInfo { |
| 408 | uint64_t CountValue; |
| 409 | bool CountValid; |
| 410 | int32_t UnknownCountInEdge; |
| 411 | int32_t UnknownCountOutEdge; |
| 412 | DirectEdges InEdges; |
| 413 | DirectEdges OutEdges; |
| 414 | UseBBInfo(unsigned IX) |
| 415 | : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0), |
| 416 | UnknownCountOutEdge(0) {} |
| 417 | UseBBInfo(unsigned IX, uint64_t C) |
| 418 | : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0), |
| 419 | UnknownCountOutEdge(0) {} |
| 420 | |
| 421 | // Set the profile count value for this BB. |
| 422 | void setBBInfoCount(uint64_t Value) { |
| 423 | CountValue = Value; |
| 424 | CountValid = true; |
| 425 | } |
| 426 | |
| 427 | // Return the information string of this object. |
| 428 | const std::string infoString() const { |
| 429 | if (!CountValid) |
| 430 | return BBInfo::infoString(); |
| 431 | return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str(); |
| 432 | } |
| 433 | }; |
| 434 | |
| 435 | // Sum up the count values for all the edges. |
| 436 | static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) { |
| 437 | uint64_t Total = 0; |
| 438 | for (auto &E : Edges) { |
| 439 | if (E->Removed) |
| 440 | continue; |
| 441 | Total += E->CountValue; |
| 442 | } |
| 443 | return Total; |
| 444 | } |
| 445 | |
| 446 | class PGOUseFunc { |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 447 | public: |
| 448 | PGOUseFunc(Function &Func, Module *Modu, BranchProbabilityInfo *BPI = nullptr, |
| 449 | BlockFrequencyInfo *BFI = nullptr) |
| 450 | : F(Func), M(Modu), FuncInfo(Func, false, BPI, BFI), |
| 451 | FreqAttr(FFA_Normal) {} |
| 452 | |
| 453 | // Read counts for the instrumented BB from profile. |
| 454 | bool readCounters(IndexedInstrProfReader *PGOReader); |
| 455 | |
| 456 | // Populate the counts for all BBs. |
| 457 | void populateCounters(); |
| 458 | |
| 459 | // Set the branch weights based on the count values. |
| 460 | void setBranchWeights(); |
| 461 | |
| 462 | // Annotate the indirect call sites. |
| 463 | void annotateIndirectCallSites(); |
| 464 | |
| 465 | // The hotness of the function from the profile count. |
| 466 | enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot }; |
| 467 | |
Rong Xu | 08afb05 | 2016-04-28 17:31:22 +0000 | [diff] [blame] | 468 | // Return the function hotness from the profile. |
| 469 | FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; } |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 470 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 471 | private: |
| 472 | Function &F; |
| 473 | Module *M; |
| 474 | // This member stores the shared information with class PGOGenFunc. |
| 475 | FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo; |
| 476 | |
| 477 | // Return the auxiliary BB information. |
| 478 | UseBBInfo &getBBInfo(const BasicBlock *BB) const { |
| 479 | return FuncInfo.getBBInfo(BB); |
| 480 | } |
| 481 | |
| 482 | // The maximum count value in the profile. This is only used in PGO use |
| 483 | // compilation. |
| 484 | uint64_t ProgramMaxCount; |
| 485 | |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 486 | // ProfileRecord for this function. |
| 487 | InstrProfRecord ProfileRecord; |
| 488 | |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 489 | // Function hotness info derived from profile. |
| 490 | FuncFreqAttr FreqAttr; |
| 491 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 492 | // Find the Instrumented BB and set the value. |
| 493 | void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile); |
| 494 | |
| 495 | // Set the edge counter value for the unknown edge -- there should be only |
| 496 | // one unknown edge. |
| 497 | void setEdgeCount(DirectEdges &Edges, uint64_t Value); |
| 498 | |
| 499 | // Return FuncName string; |
| 500 | const std::string getFuncName() const { return FuncInfo.FuncName; } |
| 501 | |
| 502 | // Set the hot/cold inline hints based on the count values. |
| 503 | // FIXME: This function should be removed once the functionality in |
| 504 | // the inliner is implemented. |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 505 | void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 506 | if (ProgramMaxCount == 0) |
| 507 | return; |
| 508 | // Threshold of the hot functions. |
| 509 | const BranchProbability HotFunctionThreshold(1, 100); |
| 510 | // Threshold of the cold functions. |
| 511 | const BranchProbability ColdFunctionThreshold(2, 10000); |
| 512 | if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount)) |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 513 | FreqAttr = FFA_Hot; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 514 | else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount)) |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 515 | FreqAttr = FFA_Cold; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 516 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 517 | }; |
| 518 | |
| 519 | // Visit all the edges and assign the count value for the instrumented |
| 520 | // edges and the BB. |
| 521 | void PGOUseFunc::setInstrumentedCounts( |
| 522 | const std::vector<uint64_t> &CountFromProfile) { |
| 523 | |
| 524 | // Use a worklist as we will update the vector during the iteration. |
| 525 | std::vector<PGOUseEdge *> WorkList; |
| 526 | for (auto &E : FuncInfo.MST.AllEdges) |
| 527 | WorkList.push_back(E.get()); |
| 528 | |
| 529 | uint32_t I = 0; |
| 530 | for (auto &E : WorkList) { |
| 531 | BasicBlock *InstrBB = FuncInfo.getInstrBB(E); |
| 532 | if (!InstrBB) |
| 533 | continue; |
| 534 | uint64_t CountValue = CountFromProfile[I++]; |
| 535 | if (!E->Removed) { |
| 536 | getBBInfo(InstrBB).setBBInfoCount(CountValue); |
| 537 | E->setEdgeCount(CountValue); |
| 538 | continue; |
| 539 | } |
| 540 | |
| 541 | // Need to add two new edges. |
| 542 | BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); |
| 543 | BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); |
| 544 | // Add new edge of SrcBB->InstrBB. |
| 545 | PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0); |
| 546 | NewEdge.setEdgeCount(CountValue); |
| 547 | // Add new edge of InstrBB->DestBB. |
| 548 | PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0); |
| 549 | NewEdge1.setEdgeCount(CountValue); |
| 550 | NewEdge1.InMST = true; |
| 551 | getBBInfo(InstrBB).setBBInfoCount(CountValue); |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | // Set the count value for the unknown edge. There should be one and only one |
| 556 | // unknown edge in Edges vector. |
| 557 | void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) { |
| 558 | for (auto &E : Edges) { |
| 559 | if (E->CountValid) |
| 560 | continue; |
| 561 | E->setEdgeCount(Value); |
| 562 | |
| 563 | getBBInfo(E->SrcBB).UnknownCountOutEdge--; |
| 564 | getBBInfo(E->DestBB).UnknownCountInEdge--; |
| 565 | return; |
| 566 | } |
| 567 | llvm_unreachable("Cannot find the unknown count edge"); |
| 568 | } |
| 569 | |
| 570 | // Read the profile from ProfileFileName and assign the value to the |
| 571 | // instrumented BB and the edges. This function also updates ProgramMaxCount. |
| 572 | // Return true if the profile are successfully read, and false on errors. |
| 573 | bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) { |
| 574 | auto &Ctx = M->getContext(); |
| 575 | ErrorOr<InstrProfRecord> Result = |
| 576 | PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash); |
| 577 | if (std::error_code EC = Result.getError()) { |
| 578 | if (EC == instrprof_error::unknown_function) |
| 579 | NumOfPGOMissing++; |
| 580 | else if (EC == instrprof_error::hash_mismatch || |
| 581 | EC == llvm::instrprof_error::malformed) |
| 582 | NumOfPGOMismatch++; |
| 583 | |
| 584 | std::string Msg = EC.message() + std::string(" ") + F.getName().str(); |
| 585 | Ctx.diagnose( |
| 586 | DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); |
| 587 | return false; |
| 588 | } |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 589 | ProfileRecord = std::move(Result.get()); |
| 590 | std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 591 | |
| 592 | NumOfPGOFunc++; |
| 593 | DEBUG(dbgs() << CountFromProfile.size() << " counts\n"); |
| 594 | uint64_t ValueSum = 0; |
| 595 | for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) { |
| 596 | DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n"); |
| 597 | ValueSum += CountFromProfile[I]; |
| 598 | } |
| 599 | |
| 600 | DEBUG(dbgs() << "SUM = " << ValueSum << "\n"); |
| 601 | |
| 602 | getBBInfo(nullptr).UnknownCountOutEdge = 2; |
| 603 | getBBInfo(nullptr).UnknownCountInEdge = 2; |
| 604 | |
| 605 | setInstrumentedCounts(CountFromProfile); |
| 606 | ProgramMaxCount = PGOReader->getMaximumFunctionCount(); |
| 607 | return true; |
| 608 | } |
| 609 | |
| 610 | // Populate the counters from instrumented BBs to all BBs. |
| 611 | // In the end of this operation, all BBs should have a valid count value. |
| 612 | void PGOUseFunc::populateCounters() { |
| 613 | // First set up Count variable for all BBs. |
| 614 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 615 | if (E->Removed) |
| 616 | continue; |
| 617 | |
| 618 | const BasicBlock *SrcBB = E->SrcBB; |
| 619 | const BasicBlock *DestBB = E->DestBB; |
| 620 | UseBBInfo &SrcInfo = getBBInfo(SrcBB); |
| 621 | UseBBInfo &DestInfo = getBBInfo(DestBB); |
| 622 | SrcInfo.OutEdges.push_back(E.get()); |
| 623 | DestInfo.InEdges.push_back(E.get()); |
| 624 | SrcInfo.UnknownCountOutEdge++; |
| 625 | DestInfo.UnknownCountInEdge++; |
| 626 | |
| 627 | if (!E->CountValid) |
| 628 | continue; |
| 629 | DestInfo.UnknownCountInEdge--; |
| 630 | SrcInfo.UnknownCountOutEdge--; |
| 631 | } |
| 632 | |
| 633 | bool Changes = true; |
| 634 | unsigned NumPasses = 0; |
| 635 | while (Changes) { |
| 636 | NumPasses++; |
| 637 | Changes = false; |
| 638 | |
| 639 | // For efficient traversal, it's better to start from the end as most |
| 640 | // of the instrumented edges are at the end. |
| 641 | for (auto &BB : reverse(F)) { |
| 642 | UseBBInfo &Count = getBBInfo(&BB); |
| 643 | if (!Count.CountValid) { |
| 644 | if (Count.UnknownCountOutEdge == 0) { |
| 645 | Count.CountValue = sumEdgeCount(Count.OutEdges); |
| 646 | Count.CountValid = true; |
| 647 | Changes = true; |
| 648 | } else if (Count.UnknownCountInEdge == 0) { |
| 649 | Count.CountValue = sumEdgeCount(Count.InEdges); |
| 650 | Count.CountValid = true; |
| 651 | Changes = true; |
| 652 | } |
| 653 | } |
| 654 | if (Count.CountValid) { |
| 655 | if (Count.UnknownCountOutEdge == 1) { |
| 656 | uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges); |
| 657 | setEdgeCount(Count.OutEdges, Total); |
| 658 | Changes = true; |
| 659 | } |
| 660 | if (Count.UnknownCountInEdge == 1) { |
| 661 | uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges); |
| 662 | setEdgeCount(Count.InEdges, Total); |
| 663 | Changes = true; |
| 664 | } |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n"); |
| 670 | // Assert every BB has a valid counter. |
| 671 | uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue; |
| 672 | uint64_t FuncMaxCount = FuncEntryCount; |
| 673 | for (auto &BB : F) { |
| 674 | assert(getBBInfo(&BB).CountValid && "BB count is not valid"); |
| 675 | uint64_t Count = getBBInfo(&BB).CountValue; |
| 676 | if (Count > FuncMaxCount) |
| 677 | FuncMaxCount = Count; |
| 678 | } |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 679 | markFunctionAttributes(FuncEntryCount, FuncMaxCount); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 680 | |
| 681 | DEBUG(FuncInfo.dumpInfo("after reading profile.")); |
| 682 | } |
| 683 | |
| 684 | // Assign the scaled count values to the BB with multiple out edges. |
| 685 | void PGOUseFunc::setBranchWeights() { |
| 686 | // Generate MD_prof metadata for every branch instruction. |
| 687 | DEBUG(dbgs() << "\nSetting branch weights.\n"); |
| 688 | MDBuilder MDB(M->getContext()); |
| 689 | for (auto &BB : F) { |
| 690 | TerminatorInst *TI = BB.getTerminator(); |
| 691 | if (TI->getNumSuccessors() < 2) |
| 692 | continue; |
| 693 | if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) |
| 694 | continue; |
| 695 | if (getBBInfo(&BB).CountValue == 0) |
| 696 | continue; |
| 697 | |
| 698 | // We have a non-zero Branch BB. |
| 699 | const UseBBInfo &BBCountInfo = getBBInfo(&BB); |
| 700 | unsigned Size = BBCountInfo.OutEdges.size(); |
| 701 | SmallVector<unsigned, 2> EdgeCounts(Size, 0); |
| 702 | uint64_t MaxCount = 0; |
| 703 | for (unsigned s = 0; s < Size; s++) { |
| 704 | const PGOUseEdge *E = BBCountInfo.OutEdges[s]; |
| 705 | const BasicBlock *SrcBB = E->SrcBB; |
| 706 | const BasicBlock *DestBB = E->DestBB; |
Eugene Zelenko | 6ac3f73 | 2016-01-26 18:48:36 +0000 | [diff] [blame] | 707 | if (DestBB == nullptr) |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 708 | continue; |
| 709 | unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); |
| 710 | uint64_t EdgeCount = E->CountValue; |
| 711 | if (EdgeCount > MaxCount) |
| 712 | MaxCount = EdgeCount; |
| 713 | EdgeCounts[SuccNum] = EdgeCount; |
| 714 | } |
| 715 | assert(MaxCount > 0 && "Bad max count"); |
| 716 | uint64_t Scale = calculateCountScale(MaxCount); |
| 717 | SmallVector<unsigned, 4> Weights; |
| 718 | for (const auto &ECI : EdgeCounts) |
| 719 | Weights.push_back(scaleBranchCount(ECI, Scale)); |
| 720 | |
| 721 | TI->setMetadata(llvm::LLVMContext::MD_prof, |
| 722 | MDB.createBranchWeights(Weights)); |
| 723 | DEBUG(dbgs() << "Weight is: "; |
| 724 | for (const auto &W : Weights) { dbgs() << W << " "; } |
| 725 | dbgs() << "\n";); |
| 726 | } |
| 727 | } |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 728 | |
| 729 | // Traverse all the indirect callsites and annotate the instructions. |
| 730 | void PGOUseFunc::annotateIndirectCallSites() { |
| 731 | if (DisableValueProfiling) |
| 732 | return; |
| 733 | |
Rong Xu | 8e8fe85 | 2016-04-01 16:43:30 +0000 | [diff] [blame] | 734 | // Create the PGOFuncName meta data. |
Rong Xu | f8f051c | 2016-04-22 21:00:17 +0000 | [diff] [blame] | 735 | createPGOFuncNameMetadata(F, FuncInfo.FuncName); |
Rong Xu | b534166 | 2016-03-30 18:37:52 +0000 | [diff] [blame] | 736 | |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 737 | unsigned IndirectCallSiteIndex = 0; |
Rong Xu | 0eb3603 | 2016-04-01 23:16:44 +0000 | [diff] [blame] | 738 | auto IndirectCallSites = findIndirectCallSites(F); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 739 | unsigned NumValueSites = |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 740 | ProfileRecord.getNumValueSites(IPVK_IndirectCallTarget); |
Rong Xu | 0eb3603 | 2016-04-01 23:16:44 +0000 | [diff] [blame] | 741 | if (NumValueSites != IndirectCallSites.size()) { |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 742 | std::string Msg = |
| 743 | std::string("Inconsistent number of indirect call sites: ") + |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 744 | F.getName().str(); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 745 | auto &Ctx = M->getContext(); |
| 746 | Ctx.diagnose( |
| 747 | DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); |
| 748 | return; |
| 749 | } |
| 750 | |
Rong Xu | 0eb3603 | 2016-04-01 23:16:44 +0000 | [diff] [blame] | 751 | for (auto &I : IndirectCallSites) { |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 752 | DEBUG(dbgs() << "Read one indirect call instrumentation: Index=" |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 753 | << IndirectCallSiteIndex << " out of " << NumValueSites |
| 754 | << "\n"); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 755 | annotateValueSite(*M, *I, ProfileRecord, IPVK_IndirectCallTarget, |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 756 | IndirectCallSiteIndex, MaxNumAnnotations); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 757 | IndirectCallSiteIndex++; |
| 758 | } |
| 759 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 760 | } // end anonymous namespace |
| 761 | |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 762 | // Create a COMDAT variable IR_LEVEL_PROF_VARNAME to make the runtime |
| 763 | // aware this is an ir_level profile so it can set the version flag. |
| 764 | static void createIRLevelProfileFlagVariable(Module &M) { |
| 765 | Type *IntTy64 = Type::getInt64Ty(M.getContext()); |
| 766 | uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 767 | auto IRLevelVersionVariable = new GlobalVariable( |
| 768 | M, IntTy64, true, GlobalVariable::ExternalLinkage, |
| 769 | Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), |
| 770 | INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR)); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 771 | IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility); |
| 772 | Triple TT(M.getTargetTriple()); |
| 773 | if (TT.isOSBinFormatMachO()) |
Rong Xu | b6211a0 | 2016-05-10 17:45:33 +0000 | [diff] [blame] | 774 | IRLevelVersionVariable->setLinkage(GlobalValue::LinkOnceAnyLinkage); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 775 | else |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 776 | IRLevelVersionVariable->setComdat(M.getOrInsertComdat( |
| 777 | StringRef(INSTR_PROF_QUOTE(IR_LEVEL_PROF_VERSION_VAR)))); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 778 | } |
| 779 | |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 780 | static bool InstrumentAllFunctions( |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 781 | Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, |
| 782 | function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 783 | createIRLevelProfileFlagVariable(M); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 784 | for (auto &F : M) { |
| 785 | if (F.isDeclaration()) |
| 786 | continue; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 787 | auto *BPI = LookupBPI(F); |
| 788 | auto *BFI = LookupBFI(F); |
| 789 | instrumentOneFunc(F, &M, BPI, BFI); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 790 | } |
| 791 | return true; |
| 792 | } |
| 793 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 794 | bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) { |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 795 | if (skipModule(M)) |
| 796 | return false; |
| 797 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 798 | auto LookupBPI = [this](Function &F) { |
| 799 | return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 800 | }; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 801 | auto LookupBFI = [this](Function &F) { |
| 802 | return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 803 | }; |
| 804 | return InstrumentAllFunctions(M, LookupBPI, LookupBFI); |
| 805 | } |
| 806 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 807 | PreservedAnalyses PGOInstrumentationGen::run(Module &M, |
| 808 | AnalysisManager<Module> &AM) { |
| 809 | |
| 810 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 811 | auto LookupBPI = [&FAM](Function &F) { |
| 812 | return &FAM.getResult<BranchProbabilityAnalysis>(F); |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 813 | }; |
| 814 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 815 | auto LookupBFI = [&FAM](Function &F) { |
| 816 | return &FAM.getResult<BlockFrequencyAnalysis>(F); |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 817 | }; |
| 818 | |
| 819 | if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI)) |
| 820 | return PreservedAnalyses::all(); |
| 821 | |
| 822 | return PreservedAnalyses::none(); |
| 823 | } |
| 824 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 825 | static void setPGOCountOnFunc(PGOUseFunc &Func, |
| 826 | IndexedInstrProfReader *PGOReader) { |
| 827 | if (Func.readCounters(PGOReader)) { |
| 828 | Func.populateCounters(); |
| 829 | Func.setBranchWeights(); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 830 | Func.annotateIndirectCallSites(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 831 | } |
| 832 | } |
| 833 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame^] | 834 | static bool annotateAllFunctions( |
| 835 | Module &M, StringRef ProfileFileName, |
| 836 | function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 837 | function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 838 | DEBUG(dbgs() << "Read in profile counters: "); |
| 839 | auto &Ctx = M.getContext(); |
| 840 | // Read the counter array from file. |
| 841 | auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName); |
| 842 | if (std::error_code EC = ReaderOrErr.getError()) { |
| 843 | Ctx.diagnose( |
| 844 | DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message())); |
| 845 | return false; |
| 846 | } |
| 847 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame^] | 848 | std::unique_ptr<IndexedInstrProfReader> PGOReader = |
| 849 | std::move(ReaderOrErr.get()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 850 | if (!PGOReader) { |
| 851 | Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(), |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame^] | 852 | StringRef("Cannot get PGOReader"))); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 853 | return false; |
| 854 | } |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 855 | // TODO: might need to change the warning once the clang option is finalized. |
| 856 | if (!PGOReader->isIRLevelProfile()) { |
| 857 | Ctx.diagnose(DiagnosticInfoPGOProfile( |
| 858 | ProfileFileName.data(), "Not an IR level instrumentation profile")); |
| 859 | return false; |
| 860 | } |
| 861 | |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 862 | std::vector<Function *> HotFunctions; |
| 863 | std::vector<Function *> ColdFunctions; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 864 | for (auto &F : M) { |
| 865 | if (F.isDeclaration()) |
| 866 | continue; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 867 | auto *BPI = LookupBPI(F); |
| 868 | auto *BFI = LookupBFI(F); |
| 869 | PGOUseFunc Func(F, &M, BPI, BFI); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 870 | setPGOCountOnFunc(Func, PGOReader.get()); |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 871 | PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr(); |
| 872 | if (FreqAttr == PGOUseFunc::FFA_Cold) |
| 873 | ColdFunctions.push_back(&F); |
| 874 | else if (FreqAttr == PGOUseFunc::FFA_Hot) |
| 875 | HotFunctions.push_back(&F); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 876 | } |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 877 | |
| 878 | // Set function hotness attribute from the profile. |
| 879 | for (auto &F : HotFunctions) { |
| 880 | F->addFnAttr(llvm::Attribute::InlineHint); |
| 881 | DEBUG(dbgs() << "Set inline attribute to function: " << F->getName() |
| 882 | << "\n"); |
| 883 | } |
| 884 | for (auto &F : ColdFunctions) { |
| 885 | F->addFnAttr(llvm::Attribute::Cold); |
| 886 | DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n"); |
| 887 | } |
| 888 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 889 | return true; |
| 890 | } |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 891 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame^] | 892 | PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename) |
| 893 | : ProfileFileName(Filename) { |
| 894 | if (!PGOTestProfileFile.empty()) |
| 895 | ProfileFileName = PGOTestProfileFile; |
| 896 | } |
| 897 | |
| 898 | PreservedAnalyses PGOInstrumentationUse::run(Module &M, |
| 899 | AnalysisManager<Module> &AM) { |
| 900 | |
| 901 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
| 902 | auto LookupBPI = [&FAM](Function &F) { |
| 903 | return &FAM.getResult<BranchProbabilityAnalysis>(F); |
| 904 | }; |
| 905 | |
| 906 | auto LookupBFI = [&FAM](Function &F) { |
| 907 | return &FAM.getResult<BlockFrequencyAnalysis>(F); |
| 908 | }; |
| 909 | |
| 910 | if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI)) |
| 911 | return PreservedAnalyses::all(); |
| 912 | |
| 913 | return PreservedAnalyses::none(); |
| 914 | } |
| 915 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 916 | bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) { |
| 917 | if (skipModule(M)) |
| 918 | return false; |
| 919 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 920 | auto LookupBPI = [this](Function &F) { |
| 921 | return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 922 | }; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 923 | auto LookupBFI = [this](Function &F) { |
| 924 | return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 925 | }; |
| 926 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame^] | 927 | return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI); |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 928 | } |