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 28 // count profile, and generates the instrumentation for indirect call 29 // profiling. 30 // (2) Pass PGOInstrumentationUse which reads the edge count profile and 31 // annotates the branch weights. It also reads the indirect call value 32 // profiling records and annotate the indirect call instructions. 33 // 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 51 #include "llvm/Transforms/PGOInstrumentation.h" 52 #include "CFGMST.h" 53 #include "llvm/ADT/STLExtras.h" 54 #include "llvm/ADT/SmallVector.h" 55 #include "llvm/ADT/Statistic.h" 56 #include "llvm/ADT/Triple.h" 57 #include "llvm/Analysis/BlockFrequencyInfo.h" 58 #include "llvm/Analysis/BranchProbabilityInfo.h" 59 #include "llvm/Analysis/CFG.h" 60 #include "llvm/Analysis/IndirectCallSiteVisitor.h" 61 #include "llvm/Analysis/LoopInfo.h" 62 #include "llvm/IR/CallSite.h" 63 #include "llvm/IR/DiagnosticInfo.h" 64 #include "llvm/IR/Dominators.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/InstIterator.h" 68 #include "llvm/IR/Instructions.h" 69 #include "llvm/IR/IntrinsicInst.h" 70 #include "llvm/IR/MDBuilder.h" 71 #include "llvm/IR/Module.h" 72 #include "llvm/Pass.h" 73 #include "llvm/ProfileData/InstrProfReader.h" 74 #include "llvm/ProfileData/ProfileCommon.h" 75 #include "llvm/Support/BranchProbability.h" 76 #include "llvm/Support/DOTGraphTraits.h" 77 #include "llvm/Support/Debug.h" 78 #include "llvm/Support/GraphWriter.h" 79 #include "llvm/Support/JamCRC.h" 80 #include "llvm/Transforms/Instrumentation.h" 81 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 82 #include <algorithm> 83 #include <string> 84 #include <unordered_map> 85 #include <utility> 86 #include <vector> 87 88 using namespace llvm; 89 90 #define DEBUG_TYPE "pgo-instrumentation" 91 92 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented."); 93 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented."); 94 STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented."); 95 STATISTIC(NumOfPGOEdge, "Number of edges."); 96 STATISTIC(NumOfPGOBB, "Number of basic-blocks."); 97 STATISTIC(NumOfPGOSplit, "Number of critical edge splits."); 98 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts."); 99 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile."); 100 STATISTIC(NumOfPGOMissing, "Number of functions without profile."); 101 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations."); 102 103 // Command line option to specify the file to read profile from. This is 104 // mainly used for testing. 105 static cl::opt<std::string> 106 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, 107 cl::value_desc("filename"), 108 cl::desc("Specify the path of profile data file. This is" 109 "mainly for test purpose.")); 110 111 // Command line option to disable value profiling. The default is false: 112 // i.e. value profiling is enabled by default. This is for debug purpose. 113 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false), 114 cl::Hidden, 115 cl::desc("Disable Value Profiling")); 116 117 // Command line option to set the maximum number of VP annotations to write to 118 // the metadata for a single indirect call callsite. 119 static cl::opt<unsigned> MaxNumAnnotations( 120 "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore, 121 cl::desc("Max number of annotations for a single indirect " 122 "call callsite")); 123 124 // Command line option to set the maximum number of value annotations 125 // to write to the metadata for a single memop intrinsic. 126 static cl::opt<unsigned> MaxNumMemOPAnnotations( 127 "memop-max-annotations", cl::init(4), cl::Hidden, cl::ZeroOrMore, 128 cl::desc("Max number of preicise value annotations for a single memop" 129 "intrinsic")); 130 131 // Command line option to control appending FunctionHash to the name of a COMDAT 132 // function. This is to avoid the hash mismatch caused by the preinliner. 133 static cl::opt<bool> DoComdatRenaming( 134 "do-comdat-renaming", cl::init(false), cl::Hidden, 135 cl::desc("Append function hash to the name of COMDAT function to avoid " 136 "function hash mismatch due to the preinliner")); 137 138 // Command line option to enable/disable the warning about missing profile 139 // information. 140 static cl::opt<bool> 141 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden, 142 cl::desc("Use this option to turn on/off " 143 "warnings about missing profile data for " 144 "functions.")); 145 146 // Command line option to enable/disable the warning about a hash mismatch in 147 // the profile data. 148 static cl::opt<bool> 149 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden, 150 cl::desc("Use this option to turn off/on " 151 "warnings about profile cfg mismatch.")); 152 153 // Command line option to enable/disable the warning about a hash mismatch in 154 // the profile data for Comdat functions, which often turns out to be false 155 // positive due to the pre-instrumentation inline. 156 static cl::opt<bool> 157 NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true), 158 cl::Hidden, 159 cl::desc("The option is used to turn on/off " 160 "warnings about hash mismatch for comdat " 161 "functions.")); 162 163 // Command line option to enable/disable select instruction instrumentation. 164 static cl::opt<bool> 165 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden, 166 cl::desc("Use this option to turn on/off SELECT " 167 "instruction instrumentation. ")); 168 169 // Command line option to turn on CFG dot dump of raw profile counts 170 static cl::opt<bool> 171 PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden, 172 cl::desc("A boolean option to show CFG dag " 173 "with raw profile counts from " 174 "profile data. See also option " 175 "-pgo-view-counts. To limit graph " 176 "display to only one function, use " 177 "filtering option -view-bfi-func-name.")); 178 179 // Command line option to enable/disable memop intrinsic call.size profiling. 180 static cl::opt<bool> 181 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden, 182 cl::desc("Use this option to turn on/off " 183 "memory instrinsic size profiling.")); 184 185 // Command line option to turn on CFG dot dump after profile annotation. 186 // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts 187 extern cl::opt<bool> PGOViewCounts; 188 189 // Command line option to specify the name of the function for CFG dump 190 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= 191 extern cl::opt<std::string> ViewBlockFreqFuncName; 192 193 namespace { 194 195 /// The select instruction visitor plays three roles specified 196 /// by the mode. In \c VM_counting mode, it simply counts the number of 197 /// select instructions. In \c VM_instrument mode, it inserts code to count 198 /// the number times TrueValue of select is taken. In \c VM_annotate mode, 199 /// it reads the profile data and annotate the select instruction with metadata. 200 enum VisitMode { VM_counting, VM_instrument, VM_annotate }; 201 class PGOUseFunc; 202 203 /// Instruction Visitor class to visit select instructions. 204 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> { 205 Function &F; 206 unsigned NSIs = 0; // Number of select instructions instrumented. 207 VisitMode Mode = VM_counting; // Visiting mode. 208 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index. 209 unsigned TotalNumCtrs = 0; // Total number of counters 210 GlobalVariable *FuncNameVar = nullptr; 211 uint64_t FuncHash = 0; 212 PGOUseFunc *UseFunc = nullptr; 213 214 SelectInstVisitor(Function &Func) : F(Func) {} 215 216 void countSelects(Function &Func) { 217 NSIs = 0; 218 Mode = VM_counting; 219 visit(Func); 220 } 221 // Visit the IR stream and instrument all select instructions. \p 222 // Ind is a pointer to the counter index variable; \p TotalNC 223 // is the total number of counters; \p FNV is the pointer to the 224 // PGO function name var; \p FHash is the function hash. 225 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC, 226 GlobalVariable *FNV, uint64_t FHash) { 227 Mode = VM_instrument; 228 CurCtrIdx = Ind; 229 TotalNumCtrs = TotalNC; 230 FuncHash = FHash; 231 FuncNameVar = FNV; 232 visit(Func); 233 } 234 235 // Visit the IR stream and annotate all select instructions. 236 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) { 237 Mode = VM_annotate; 238 UseFunc = UF; 239 CurCtrIdx = Ind; 240 visit(Func); 241 } 242 243 void instrumentOneSelectInst(SelectInst &SI); 244 void annotateOneSelectInst(SelectInst &SI); 245 // Visit \p SI instruction and perform tasks according to visit mode. 246 void visitSelectInst(SelectInst &SI); 247 // Return the number of select instructions. This needs be called after 248 // countSelects(). 249 unsigned getNumOfSelectInsts() const { return NSIs; } 250 }; 251 252 /// Instruction Visitor class to visit memory intrinsic calls. 253 struct MemIntrinsicVisitor : public InstVisitor<MemIntrinsicVisitor> { 254 Function &F; 255 unsigned NMemIs = 0; // Number of memIntrinsics instrumented. 256 VisitMode Mode = VM_counting; // Visiting mode. 257 unsigned CurCtrId = 0; // Current counter index. 258 unsigned TotalNumCtrs = 0; // Total number of counters 259 GlobalVariable *FuncNameVar = nullptr; 260 uint64_t FuncHash = 0; 261 PGOUseFunc *UseFunc = nullptr; 262 std::vector<Instruction *> Candidates; 263 264 MemIntrinsicVisitor(Function &Func) : F(Func) {} 265 266 void countMemIntrinsics(Function &Func) { 267 NMemIs = 0; 268 Mode = VM_counting; 269 visit(Func); 270 } 271 272 void instrumentMemIntrinsics(Function &Func, unsigned TotalNC, 273 GlobalVariable *FNV, uint64_t FHash) { 274 Mode = VM_instrument; 275 TotalNumCtrs = TotalNC; 276 FuncHash = FHash; 277 FuncNameVar = FNV; 278 visit(Func); 279 } 280 281 std::vector<Instruction *> findMemIntrinsics(Function &Func) { 282 Candidates.clear(); 283 Mode = VM_annotate; 284 visit(Func); 285 return Candidates; 286 } 287 288 // Visit the IR stream and annotate all mem intrinsic call instructions. 289 void instrumentOneMemIntrinsic(MemIntrinsic &MI); 290 // Visit \p MI instruction and perform tasks according to visit mode. 291 void visitMemIntrinsic(MemIntrinsic &SI); 292 unsigned getNumOfMemIntrinsics() const { return NMemIs; } 293 }; 294 295 class PGOInstrumentationGenLegacyPass : public ModulePass { 296 public: 297 static char ID; 298 299 PGOInstrumentationGenLegacyPass() : ModulePass(ID) { 300 initializePGOInstrumentationGenLegacyPassPass( 301 *PassRegistry::getPassRegistry()); 302 } 303 304 StringRef getPassName() const override { return "PGOInstrumentationGenPass"; } 305 306 private: 307 bool runOnModule(Module &M) override; 308 309 void getAnalysisUsage(AnalysisUsage &AU) const override { 310 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 311 } 312 }; 313 314 class PGOInstrumentationUseLegacyPass : public ModulePass { 315 public: 316 static char ID; 317 318 // Provide the profile filename as the parameter. 319 PGOInstrumentationUseLegacyPass(std::string Filename = "") 320 : ModulePass(ID), ProfileFileName(std::move(Filename)) { 321 if (!PGOTestProfileFile.empty()) 322 ProfileFileName = PGOTestProfileFile; 323 initializePGOInstrumentationUseLegacyPassPass( 324 *PassRegistry::getPassRegistry()); 325 } 326 327 StringRef getPassName() const override { return "PGOInstrumentationUsePass"; } 328 329 private: 330 std::string ProfileFileName; 331 332 bool runOnModule(Module &M) override; 333 void getAnalysisUsage(AnalysisUsage &AU) const override { 334 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 335 } 336 }; 337 338 } // end anonymous namespace 339 340 char PGOInstrumentationGenLegacyPass::ID = 0; 341 INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", 342 "PGO instrumentation.", false, false) 343 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 344 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 345 INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", 346 "PGO instrumentation.", false, false) 347 348 ModulePass *llvm::createPGOInstrumentationGenLegacyPass() { 349 return new PGOInstrumentationGenLegacyPass(); 350 } 351 352 char PGOInstrumentationUseLegacyPass::ID = 0; 353 INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use", 354 "Read PGO instrumentation profile.", false, false) 355 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 356 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) 357 INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use", 358 "Read PGO instrumentation profile.", false, false) 359 360 ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) { 361 return new PGOInstrumentationUseLegacyPass(Filename.str()); 362 } 363 364 namespace { 365 /// \brief An MST based instrumentation for PGO 366 /// 367 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO 368 /// in the function level. 369 struct PGOEdge { 370 // This class implements the CFG edges. Note the CFG can be a multi-graph. 371 // So there might be multiple edges with same SrcBB and DestBB. 372 const BasicBlock *SrcBB; 373 const BasicBlock *DestBB; 374 uint64_t Weight; 375 bool InMST; 376 bool Removed; 377 bool IsCritical; 378 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) 379 : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false), 380 IsCritical(false) {} 381 // Return the information string of an edge. 382 const std::string infoString() const { 383 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") + 384 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str(); 385 } 386 }; 387 388 // This class stores the auxiliary information for each BB. 389 struct BBInfo { 390 BBInfo *Group; 391 uint32_t Index; 392 uint32_t Rank; 393 394 BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {} 395 396 // Return the information string of this object. 397 const std::string infoString() const { 398 return (Twine("Index=") + Twine(Index)).str(); 399 } 400 }; 401 402 // This class implements the CFG edges. Note the CFG can be a multi-graph. 403 template <class Edge, class BBInfo> class FuncPGOInstrumentation { 404 private: 405 Function &F; 406 void computeCFGHash(); 407 void renameComdatFunction(); 408 // A map that stores the Comdat group in function F. 409 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers; 410 411 public: 412 std::vector<std::vector<Instruction *>> ValueSites; 413 SelectInstVisitor SIVisitor; 414 MemIntrinsicVisitor MIVisitor; 415 std::string FuncName; 416 GlobalVariable *FuncNameVar; 417 // CFG hash value for this function. 418 uint64_t FunctionHash; 419 420 // The Minimum Spanning Tree of function CFG. 421 CFGMST<Edge, BBInfo> MST; 422 423 // Give an edge, find the BB that will be instrumented. 424 // Return nullptr if there is no BB to be instrumented. 425 BasicBlock *getInstrBB(Edge *E); 426 427 // Return the auxiliary BB information. 428 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); } 429 430 // Return the auxiliary BB information if available. 431 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); } 432 433 // Dump edges and BB information. 434 void dumpInfo(std::string Str = "") const { 435 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " + 436 Twine(FunctionHash) + "\t" + Str); 437 } 438 439 FuncPGOInstrumentation( 440 Function &Func, 441 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, 442 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr, 443 BlockFrequencyInfo *BFI = nullptr) 444 : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1), 445 SIVisitor(Func), MIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) { 446 447 // This should be done before CFG hash computation. 448 SIVisitor.countSelects(Func); 449 MIVisitor.countMemIntrinsics(Func); 450 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts(); 451 NumOfPGOMemIntrinsics += MIVisitor.getNumOfMemIntrinsics(); 452 ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func); 453 ValueSites[IPVK_MemOPSize] = MIVisitor.findMemIntrinsics(Func); 454 455 FuncName = getPGOFuncName(F); 456 computeCFGHash(); 457 if (ComdatMembers.size()) 458 renameComdatFunction(); 459 DEBUG(dumpInfo("after CFGMST")); 460 461 NumOfPGOBB += MST.BBInfos.size(); 462 for (auto &E : MST.AllEdges) { 463 if (E->Removed) 464 continue; 465 NumOfPGOEdge++; 466 if (!E->InMST) 467 NumOfPGOInstrument++; 468 } 469 470 if (CreateGlobalVar) 471 FuncNameVar = createPGOFuncNameVar(F, FuncName); 472 } 473 474 // Return the number of profile counters needed for the function. 475 unsigned getNumCounters() { 476 unsigned NumCounters = 0; 477 for (auto &E : this->MST.AllEdges) { 478 if (!E->InMST && !E->Removed) 479 NumCounters++; 480 } 481 return NumCounters + SIVisitor.getNumOfSelectInsts(); 482 } 483 }; 484 485 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index 486 // value of each BB in the CFG. The higher 32 bits record the number of edges. 487 template <class Edge, class BBInfo> 488 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() { 489 std::vector<char> Indexes; 490 JamCRC JC; 491 for (auto &BB : F) { 492 const TerminatorInst *TI = BB.getTerminator(); 493 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) { 494 BasicBlock *Succ = TI->getSuccessor(I); 495 auto BI = findBBInfo(Succ); 496 if (BI == nullptr) 497 continue; 498 uint32_t Index = BI->Index; 499 for (int J = 0; J < 4; J++) 500 Indexes.push_back((char)(Index >> (J * 8))); 501 } 502 } 503 JC.update(Indexes); 504 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 | 505 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 | 506 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC(); 507 } 508 509 // Check if we can safely rename this Comdat function. 510 static bool canRenameComdat( 511 Function &F, 512 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { 513 if (!DoComdatRenaming || !canRenameComdatFunc(F, true)) 514 return false; 515 516 // FIXME: Current only handle those Comdat groups that only containing one 517 // function and function aliases. 518 // (1) For a Comdat group containing multiple functions, we need to have a 519 // unique postfix based on the hashes for each function. There is a 520 // non-trivial code refactoring to do this efficiently. 521 // (2) Variables can not be renamed, so we can not rename Comdat function in a 522 // group including global vars. 523 Comdat *C = F.getComdat(); 524 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) { 525 if (dyn_cast<GlobalAlias>(CM.second)) 526 continue; 527 Function *FM = dyn_cast<Function>(CM.second); 528 if (FM != &F) 529 return false; 530 } 531 return true; 532 } 533 534 // Append the CFGHash to the Comdat function name. 535 template <class Edge, class BBInfo> 536 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() { 537 if (!canRenameComdat(F, ComdatMembers)) 538 return; 539 std::string OrigName = F.getName().str(); 540 std::string NewFuncName = 541 Twine(F.getName() + "." + Twine(FunctionHash)).str(); 542 F.setName(Twine(NewFuncName)); 543 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F); 544 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str(); 545 Comdat *NewComdat; 546 Module *M = F.getParent(); 547 // For AvailableExternallyLinkage functions, change the linkage to 548 // LinkOnceODR and put them into comdat. This is because after renaming, there 549 // is no backup external copy available for the function. 550 if (!F.hasComdat()) { 551 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage); 552 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName)); 553 F.setLinkage(GlobalValue::LinkOnceODRLinkage); 554 F.setComdat(NewComdat); 555 return; 556 } 557 558 // This function belongs to a single function Comdat group. 559 Comdat *OrigComdat = F.getComdat(); 560 std::string NewComdatName = 561 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str(); 562 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName)); 563 NewComdat->setSelectionKind(OrigComdat->getSelectionKind()); 564 565 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) { 566 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) { 567 // For aliases, change the name directly. 568 assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F); 569 std::string OrigGAName = GA->getName().str(); 570 GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash))); 571 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA); 572 continue; 573 } 574 // Must be a function. 575 Function *CF = dyn_cast<Function>(CM.second); 576 assert(CF); 577 CF->setComdat(NewComdat); 578 } 579 } 580 581 // Given a CFG E to be instrumented, find which BB to place the instrumented 582 // code. The function will split the critical edge if necessary. 583 template <class Edge, class BBInfo> 584 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) { 585 if (E->InMST || E->Removed) 586 return nullptr; 587 588 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); 589 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); 590 // For a fake edge, instrument the real BB. 591 if (SrcBB == nullptr) 592 return DestBB; 593 if (DestBB == nullptr) 594 return SrcBB; 595 596 // Instrument the SrcBB if it has a single successor, 597 // otherwise, the DestBB if this is not a critical edge. 598 TerminatorInst *TI = SrcBB->getTerminator(); 599 if (TI->getNumSuccessors() <= 1) 600 return SrcBB; 601 if (!E->IsCritical) 602 return DestBB; 603 604 // For a critical edge, we have to split. Instrument the newly 605 // created BB. 606 NumOfPGOSplit++; 607 DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> " 608 << getBBInfo(DestBB).Index << "\n"); 609 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); 610 BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum); 611 assert(InstrBB && "Critical edge is not split"); 612 613 E->Removed = true; 614 return InstrBB; 615 } 616 617 // Visit all edge and instrument the edges not in MST, and do value profiling. 618 // Critical edges will be split. 619 static void instrumentOneFunc( 620 Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI, 621 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { 622 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI, 623 BFI); 624 unsigned NumCounters = FuncInfo.getNumCounters(); 625 626 uint32_t I = 0; 627 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext()); 628 for (auto &E : FuncInfo.MST.AllEdges) { 629 BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get()); 630 if (!InstrBB) 631 continue; 632 633 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt()); 634 assert(Builder.GetInsertPoint() != InstrBB->end() && 635 "Cannot get the Instrumentation point"); 636 Builder.CreateCall( 637 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment), 638 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), 639 Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters), 640 Builder.getInt32(I++)}); 641 } 642 643 // Now instrument select instructions: 644 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar, 645 FuncInfo.FunctionHash); 646 assert(I == NumCounters); 647 648 if (DisableValueProfiling) 649 return; 650 651 unsigned NumIndirectCallSites = 0; 652 for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) { 653 CallSite CS(I); 654 Value *Callee = CS.getCalledValue(); 655 DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = " 656 << NumIndirectCallSites << "\n"); 657 IRBuilder<> Builder(I); 658 assert(Builder.GetInsertPoint() != I->getParent()->end() && 659 "Cannot get the Instrumentation point"); 660 Builder.CreateCall( 661 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile), 662 {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), 663 Builder.getInt64(FuncInfo.FunctionHash), 664 Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()), 665 Builder.getInt32(IPVK_IndirectCallTarget), 666 Builder.getInt32(NumIndirectCallSites++)}); 667 } 668 NumOfPGOICall += NumIndirectCallSites; 669 670 // Now instrument memop intrinsic calls. 671 FuncInfo.MIVisitor.instrumentMemIntrinsics( 672 F, NumCounters, FuncInfo.FuncNameVar, FuncInfo.FunctionHash); 673 } 674 675 // This class represents a CFG edge in profile use compilation. 676 struct PGOUseEdge : public PGOEdge { 677 bool CountValid; 678 uint64_t CountValue; 679 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) 680 : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {} 681 682 // Set edge count value 683 void setEdgeCount(uint64_t Value) { 684 CountValue = Value; 685 CountValid = true; 686 } 687 688 // Return the information string for this object. 689 const std::string infoString() const { 690 if (!CountValid) 691 return PGOEdge::infoString(); 692 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue)) 693 .str(); 694 } 695 }; 696 697 typedef SmallVector<PGOUseEdge *, 2> DirectEdges; 698 699 // This class stores the auxiliary information for each BB. 700 struct UseBBInfo : public BBInfo { 701 uint64_t CountValue; 702 bool CountValid; 703 int32_t UnknownCountInEdge; 704 int32_t UnknownCountOutEdge; 705 DirectEdges InEdges; 706 DirectEdges OutEdges; 707 UseBBInfo(unsigned IX) 708 : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0), 709 UnknownCountOutEdge(0) {} 710 UseBBInfo(unsigned IX, uint64_t C) 711 : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0), 712 UnknownCountOutEdge(0) {} 713 714 // Set the profile count value for this BB. 715 void setBBInfoCount(uint64_t Value) { 716 CountValue = Value; 717 CountValid = true; 718 } 719 720 // Return the information string of this object. 721 const std::string infoString() const { 722 if (!CountValid) 723 return BBInfo::infoString(); 724 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str(); 725 } 726 }; 727 728 // Sum up the count values for all the edges. 729 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) { 730 uint64_t Total = 0; 731 for (auto &E : Edges) { 732 if (E->Removed) 733 continue; 734 Total += E->CountValue; 735 } 736 return Total; 737 } 738 739 class PGOUseFunc { 740 public: 741 PGOUseFunc(Function &Func, Module *Modu, 742 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, 743 BranchProbabilityInfo *BPI = nullptr, 744 BlockFrequencyInfo *BFI = nullptr) 745 : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI), 746 CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {} 747 748 // Read counts for the instrumented BB from profile. 749 bool readCounters(IndexedInstrProfReader *PGOReader); 750 751 // Populate the counts for all BBs. 752 void populateCounters(); 753 754 // Set the branch weights based on the count values. 755 void setBranchWeights(); 756 757 // Annotate the value profile call sites all all value kind. 758 void annotateValueSites(); 759 760 // Annotate the value profile call sites for one value kind. 761 void annotateValueSites(uint32_t Kind); 762 763 // The hotness of the function from the profile count. 764 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot }; 765 766 // Return the function hotness from the profile. 767 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; } 768 769 // Return the function hash. 770 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; } 771 // Return the profile record for this function; 772 InstrProfRecord &getProfileRecord() { return ProfileRecord; } 773 774 // Return the auxiliary BB information. 775 UseBBInfo &getBBInfo(const BasicBlock *BB) const { 776 return FuncInfo.getBBInfo(BB); 777 } 778 779 // Return the auxiliary BB information if available. 780 UseBBInfo *findBBInfo(const BasicBlock *BB) const { 781 return FuncInfo.findBBInfo(BB); 782 } 783 784 Function &getFunc() const { return F; } 785 786 private: 787 Function &F; 788 Module *M; 789 // This member stores the shared information with class PGOGenFunc. 790 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo; 791 792 // The maximum count value in the profile. This is only used in PGO use 793 // compilation. 794 uint64_t ProgramMaxCount; 795 796 // Position of counter that remains to be read. 797 uint32_t CountPosition; 798 799 // Total size of the profile count for this function. 800 uint32_t ProfileCountSize; 801 802 // ProfileRecord for this function. 803 InstrProfRecord ProfileRecord; 804 805 // Function hotness info derived from profile. 806 FuncFreqAttr FreqAttr; 807 808 // Find the Instrumented BB and set the value. 809 void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile); 810 811 // Set the edge counter value for the unknown edge -- there should be only 812 // one unknown edge. 813 void setEdgeCount(DirectEdges &Edges, uint64_t Value); 814 815 // Return FuncName string; 816 const std::string getFuncName() const { return FuncInfo.FuncName; } 817 818 // Set the hot/cold inline hints based on the count values. 819 // FIXME: This function should be removed once the functionality in 820 // the inliner is implemented. 821 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) { 822 if (ProgramMaxCount == 0) 823 return; 824 // Threshold of the hot functions. 825 const BranchProbability HotFunctionThreshold(1, 100); 826 // Threshold of the cold functions. 827 const BranchProbability ColdFunctionThreshold(2, 10000); 828 if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount)) 829 FreqAttr = FFA_Hot; 830 else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount)) 831 FreqAttr = FFA_Cold; 832 } 833 }; 834 835 // Visit all the edges and assign the count value for the instrumented 836 // edges and the BB. 837 void PGOUseFunc::setInstrumentedCounts( 838 const std::vector<uint64_t> &CountFromProfile) { 839 840 assert(FuncInfo.getNumCounters() == CountFromProfile.size()); 841 // Use a worklist as we will update the vector during the iteration. 842 std::vector<PGOUseEdge *> WorkList; 843 for (auto &E : FuncInfo.MST.AllEdges) 844 WorkList.push_back(E.get()); 845 846 uint32_t I = 0; 847 for (auto &E : WorkList) { 848 BasicBlock *InstrBB = FuncInfo.getInstrBB(E); 849 if (!InstrBB) 850 continue; 851 uint64_t CountValue = CountFromProfile[I++]; 852 if (!E->Removed) { 853 getBBInfo(InstrBB).setBBInfoCount(CountValue); 854 E->setEdgeCount(CountValue); 855 continue; 856 } 857 858 // Need to add two new edges. 859 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); 860 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); 861 // Add new edge of SrcBB->InstrBB. 862 PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0); 863 NewEdge.setEdgeCount(CountValue); 864 // Add new edge of InstrBB->DestBB. 865 PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0); 866 NewEdge1.setEdgeCount(CountValue); 867 NewEdge1.InMST = true; 868 getBBInfo(InstrBB).setBBInfoCount(CountValue); 869 } 870 ProfileCountSize = CountFromProfile.size(); 871 CountPosition = I; 872 } 873 874 // Set the count value for the unknown edge. There should be one and only one 875 // unknown edge in Edges vector. 876 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) { 877 for (auto &E : Edges) { 878 if (E->CountValid) 879 continue; 880 E->setEdgeCount(Value); 881 882 getBBInfo(E->SrcBB).UnknownCountOutEdge--; 883 getBBInfo(E->DestBB).UnknownCountInEdge--; 884 return; 885 } 886 llvm_unreachable("Cannot find the unknown count edge"); 887 } 888 889 // Read the profile from ProfileFileName and assign the value to the 890 // instrumented BB and the edges. This function also updates ProgramMaxCount. 891 // Return true if the profile are successfully read, and false on errors. 892 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) { 893 auto &Ctx = M->getContext(); 894 Expected<InstrProfRecord> Result = 895 PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash); 896 if (Error E = Result.takeError()) { 897 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) { 898 auto Err = IPE.get(); 899 bool SkipWarning = false; 900 if (Err == instrprof_error::unknown_function) { 901 NumOfPGOMissing++; 902 SkipWarning = !PGOWarnMissing; 903 } else if (Err == instrprof_error::hash_mismatch || 904 Err == instrprof_error::malformed) { 905 NumOfPGOMismatch++; 906 SkipWarning = 907 NoPGOWarnMismatch || 908 (NoPGOWarnMismatchComdat && 909 (F.hasComdat() || 910 F.getLinkage() == GlobalValue::AvailableExternallyLinkage)); 911 } 912 913 if (SkipWarning) 914 return; 915 916 std::string Msg = IPE.message() + std::string(" ") + F.getName().str(); 917 Ctx.diagnose( 918 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); 919 }); 920 return false; 921 } 922 ProfileRecord = std::move(Result.get()); 923 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts; 924 925 NumOfPGOFunc++; 926 DEBUG(dbgs() << CountFromProfile.size() << " counts\n"); 927 uint64_t ValueSum = 0; 928 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) { 929 DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n"); 930 ValueSum += CountFromProfile[I]; 931 } 932 933 DEBUG(dbgs() << "SUM = " << ValueSum << "\n"); 934 935 getBBInfo(nullptr).UnknownCountOutEdge = 2; 936 getBBInfo(nullptr).UnknownCountInEdge = 2; 937 938 setInstrumentedCounts(CountFromProfile); 939 ProgramMaxCount = PGOReader->getMaximumFunctionCount(); 940 return true; 941 } 942 943 // Populate the counters from instrumented BBs to all BBs. 944 // In the end of this operation, all BBs should have a valid count value. 945 void PGOUseFunc::populateCounters() { 946 // First set up Count variable for all BBs. 947 for (auto &E : FuncInfo.MST.AllEdges) { 948 if (E->Removed) 949 continue; 950 951 const BasicBlock *SrcBB = E->SrcBB; 952 const BasicBlock *DestBB = E->DestBB; 953 UseBBInfo &SrcInfo = getBBInfo(SrcBB); 954 UseBBInfo &DestInfo = getBBInfo(DestBB); 955 SrcInfo.OutEdges.push_back(E.get()); 956 DestInfo.InEdges.push_back(E.get()); 957 SrcInfo.UnknownCountOutEdge++; 958 DestInfo.UnknownCountInEdge++; 959 960 if (!E->CountValid) 961 continue; 962 DestInfo.UnknownCountInEdge--; 963 SrcInfo.UnknownCountOutEdge--; 964 } 965 966 bool Changes = true; 967 unsigned NumPasses = 0; 968 while (Changes) { 969 NumPasses++; 970 Changes = false; 971 972 // For efficient traversal, it's better to start from the end as most 973 // of the instrumented edges are at the end. 974 for (auto &BB : reverse(F)) { 975 UseBBInfo *Count = findBBInfo(&BB); 976 if (Count == nullptr) 977 continue; 978 if (!Count->CountValid) { 979 if (Count->UnknownCountOutEdge == 0) { 980 Count->CountValue = sumEdgeCount(Count->OutEdges); 981 Count->CountValid = true; 982 Changes = true; 983 } else if (Count->UnknownCountInEdge == 0) { 984 Count->CountValue = sumEdgeCount(Count->InEdges); 985 Count->CountValid = true; 986 Changes = true; 987 } 988 } 989 if (Count->CountValid) { 990 if (Count->UnknownCountOutEdge == 1) { 991 uint64_t Total = 0; 992 uint64_t OutSum = sumEdgeCount(Count->OutEdges); 993 // If the one of the successor block can early terminate (no-return), 994 // we can end up with situation where out edge sum count is larger as 995 // the source BB's count is collected by a post-dominated block. 996 if (Count->CountValue > OutSum) 997 Total = Count->CountValue - OutSum; 998 setEdgeCount(Count->OutEdges, Total); 999 Changes = true; 1000 } 1001 if (Count->UnknownCountInEdge == 1) { 1002 uint64_t Total = 0; 1003 uint64_t InSum = sumEdgeCount(Count->InEdges); 1004 if (Count->CountValue > InSum) 1005 Total = Count->CountValue - InSum; 1006 setEdgeCount(Count->InEdges, Total); 1007 Changes = true; 1008 } 1009 } 1010 } 1011 } 1012 1013 DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n"); 1014 #ifndef NDEBUG 1015 // Assert every BB has a valid counter. 1016 for (auto &BB : F) { 1017 auto BI = findBBInfo(&BB); 1018 if (BI == nullptr) 1019 continue; 1020 assert(BI->CountValid && "BB count is not valid"); 1021 } 1022 #endif 1023 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue; 1024 F.setEntryCount(FuncEntryCount); 1025 uint64_t FuncMaxCount = FuncEntryCount; 1026 for (auto &BB : F) { 1027 auto BI = findBBInfo(&BB); 1028 if (BI == nullptr) 1029 continue; 1030 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue); 1031 } 1032 markFunctionAttributes(FuncEntryCount, FuncMaxCount); 1033 1034 // Now annotate select instructions 1035 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition); 1036 assert(CountPosition == ProfileCountSize); 1037 1038 DEBUG(FuncInfo.dumpInfo("after reading profile.")); 1039 } 1040 1041 static void setProfMetadata(Module *M, Instruction *TI, 1042 ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) { 1043 MDBuilder MDB(M->getContext()); 1044 assert(MaxCount > 0 && "Bad max count"); 1045 uint64_t Scale = calculateCountScale(MaxCount); 1046 SmallVector<unsigned, 4> Weights; 1047 for (const auto &ECI : EdgeCounts) 1048 Weights.push_back(scaleBranchCount(ECI, Scale)); 1049 1050 DEBUG(dbgs() << "Weight is: "; 1051 for (const auto &W : Weights) { dbgs() << W << " "; } 1052 dbgs() << "\n";); 1053 TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); 1054 } 1055 1056 // Assign the scaled count values to the BB with multiple out edges. 1057 void PGOUseFunc::setBranchWeights() { 1058 // Generate MD_prof metadata for every branch instruction. 1059 DEBUG(dbgs() << "\nSetting branch weights.\n"); 1060 for (auto &BB : F) { 1061 TerminatorInst *TI = BB.getTerminator(); 1062 if (TI->getNumSuccessors() < 2) 1063 continue; 1064 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) 1065 continue; 1066 if (getBBInfo(&BB).CountValue == 0) 1067 continue; 1068 1069 // We have a non-zero Branch BB. 1070 const UseBBInfo &BBCountInfo = getBBInfo(&BB); 1071 unsigned Size = BBCountInfo.OutEdges.size(); 1072 SmallVector<uint64_t, 2> EdgeCounts(Size, 0); 1073 uint64_t MaxCount = 0; 1074 for (unsigned s = 0; s < Size; s++) { 1075 const PGOUseEdge *E = BBCountInfo.OutEdges[s]; 1076 const BasicBlock *SrcBB = E->SrcBB; 1077 const BasicBlock *DestBB = E->DestBB; 1078 if (DestBB == nullptr) 1079 continue; 1080 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); 1081 uint64_t EdgeCount = E->CountValue; 1082 if (EdgeCount > MaxCount) 1083 MaxCount = EdgeCount; 1084 EdgeCounts[SuccNum] = EdgeCount; 1085 } 1086 setProfMetadata(M, TI, EdgeCounts, MaxCount); 1087 } 1088 } 1089 1090 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) { 1091 Module *M = F.getParent(); 1092 IRBuilder<> Builder(&SI); 1093 Type *Int64Ty = Builder.getInt64Ty(); 1094 Type *I8PtrTy = Builder.getInt8PtrTy(); 1095 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty); 1096 Builder.CreateCall( 1097 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step), 1098 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy), 1099 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs), 1100 Builder.getInt32(*CurCtrIdx), Step}); 1101 ++(*CurCtrIdx); 1102 } 1103 1104 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) { 1105 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts; 1106 assert(*CurCtrIdx < CountFromProfile.size() && 1107 "Out of bound access of counters"); 1108 uint64_t SCounts[2]; 1109 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count 1110 ++(*CurCtrIdx); 1111 uint64_t TotalCount = 0; 1112 auto BI = UseFunc->findBBInfo(SI.getParent()); 1113 if (BI != nullptr) 1114 TotalCount = BI->CountValue; 1115 // False Count 1116 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0); 1117 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]); 1118 if (MaxCount) 1119 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount); 1120 } 1121 1122 void SelectInstVisitor::visitSelectInst(SelectInst &SI) { 1123 if (!PGOInstrSelect) 1124 return; 1125 // FIXME: do not handle this yet. 1126 if (SI.getCondition()->getType()->isVectorTy()) 1127 return; 1128 1129 switch (Mode) { 1130 case VM_counting: 1131 NSIs++; 1132 return; 1133 case VM_instrument: 1134 instrumentOneSelectInst(SI); 1135 return; 1136 case VM_annotate: 1137 annotateOneSelectInst(SI); 1138 return; 1139 } 1140 1141 llvm_unreachable("Unknown visiting mode"); 1142 } 1143 1144 void MemIntrinsicVisitor::instrumentOneMemIntrinsic(MemIntrinsic &MI) { 1145 Module *M = F.getParent(); 1146 IRBuilder<> Builder(&MI); 1147 Type *Int64Ty = Builder.getInt64Ty(); 1148 Type *I8PtrTy = Builder.getInt8PtrTy(); 1149 Value *Length = MI.getLength(); 1150 assert(!dyn_cast<ConstantInt>(Length)); 1151 Builder.CreateCall( 1152 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile), 1153 {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy), 1154 Builder.getInt64(FuncHash), Builder.CreatePtrToInt(Length, Int64Ty), 1155 Builder.getInt32(IPVK_MemOPSize), Builder.getInt32(CurCtrId)}); 1156 ++CurCtrId; 1157 } 1158 1159 void MemIntrinsicVisitor::visitMemIntrinsic(MemIntrinsic &MI) { 1160 if (!PGOInstrMemOP) 1161 return; 1162 Value *Length = MI.getLength(); 1163 // Not instrument constant length calls. 1164 if (dyn_cast<ConstantInt>(Length)) 1165 return; 1166 1167 switch (Mode) { 1168 case VM_counting: 1169 NMemIs++; 1170 return; 1171 case VM_instrument: 1172 instrumentOneMemIntrinsic(MI); 1173 return; 1174 case VM_annotate: 1175 Candidates.push_back(&MI); 1176 return; 1177 } 1178 llvm_unreachable("Unknown visiting mode"); 1179 } 1180 1181 // Traverse all valuesites and annotate the instructions for all value kind. 1182 void PGOUseFunc::annotateValueSites() { 1183 if (DisableValueProfiling) 1184 return; 1185 1186 // Create the PGOFuncName meta data. 1187 createPGOFuncNameMetadata(F, FuncInfo.FuncName); 1188 1189 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) 1190 annotateValueSites(Kind); 1191 } 1192 1193 // Annotate the instructions for a specific value kind. 1194 void PGOUseFunc::annotateValueSites(uint32_t Kind) { 1195 unsigned ValueSiteIndex = 0; 1196 auto &ValueSites = FuncInfo.ValueSites[Kind]; 1197 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind); 1198 if (NumValueSites != ValueSites.size()) { 1199 auto &Ctx = M->getContext(); 1200 Ctx.diagnose(DiagnosticInfoPGOProfile( 1201 M->getName().data(), 1202 Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) + 1203 " in " + F.getName().str(), 1204 DS_Warning)); 1205 return; 1206 } 1207 1208 for (auto &I : ValueSites) { 1209 DEBUG(dbgs() << "Read one value site profile (kind = " << Kind 1210 << "): Index = " << ValueSiteIndex << " out of " 1211 << NumValueSites << "\n"); 1212 annotateValueSite(*M, *I, ProfileRecord, 1213 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex, 1214 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations 1215 : MaxNumAnnotations); 1216 ValueSiteIndex++; 1217 } 1218 } 1219 } // end anonymous namespace 1220 1221 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime 1222 // aware this is an ir_level profile so it can set the version flag. 1223 static void createIRLevelProfileFlagVariable(Module &M) { 1224 Type *IntTy64 = Type::getInt64Ty(M.getContext()); 1225 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF); 1226 auto IRLevelVersionVariable = new GlobalVariable( 1227 M, IntTy64, true, GlobalVariable::ExternalLinkage, 1228 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), 1229 INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)); 1230 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility); 1231 Triple TT(M.getTargetTriple()); 1232 if (!TT.supportsCOMDAT()) 1233 IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage); 1234 else 1235 IRLevelVersionVariable->setComdat(M.getOrInsertComdat( 1236 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)))); 1237 } 1238 1239 // Collect the set of members for each Comdat in module M and store 1240 // in ComdatMembers. 1241 static void collectComdatMembers( 1242 Module &M, 1243 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { 1244 if (!DoComdatRenaming) 1245 return; 1246 for (Function &F : M) 1247 if (Comdat *C = F.getComdat()) 1248 ComdatMembers.insert(std::make_pair(C, &F)); 1249 for (GlobalVariable &GV : M.globals()) 1250 if (Comdat *C = GV.getComdat()) 1251 ComdatMembers.insert(std::make_pair(C, &GV)); 1252 for (GlobalAlias &GA : M.aliases()) 1253 if (Comdat *C = GA.getComdat()) 1254 ComdatMembers.insert(std::make_pair(C, &GA)); 1255 } 1256 1257 static bool InstrumentAllFunctions( 1258 Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, 1259 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { 1260 createIRLevelProfileFlagVariable(M); 1261 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; 1262 collectComdatMembers(M, ComdatMembers); 1263 1264 for (auto &F : M) { 1265 if (F.isDeclaration()) 1266 continue; 1267 auto *BPI = LookupBPI(F); 1268 auto *BFI = LookupBFI(F); 1269 instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers); 1270 } 1271 return true; 1272 } 1273 1274 bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) { 1275 if (skipModule(M)) 1276 return false; 1277 1278 auto LookupBPI = [this](Function &F) { 1279 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); 1280 }; 1281 auto LookupBFI = [this](Function &F) { 1282 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); 1283 }; 1284 return InstrumentAllFunctions(M, LookupBPI, LookupBFI); 1285 } 1286 1287 PreservedAnalyses PGOInstrumentationGen::run(Module &M, 1288 ModuleAnalysisManager &AM) { 1289 1290 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1291 auto LookupBPI = [&FAM](Function &F) { 1292 return &FAM.getResult<BranchProbabilityAnalysis>(F); 1293 }; 1294 1295 auto LookupBFI = [&FAM](Function &F) { 1296 return &FAM.getResult<BlockFrequencyAnalysis>(F); 1297 }; 1298 1299 if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI)) 1300 return PreservedAnalyses::all(); 1301 1302 return PreservedAnalyses::none(); 1303 } 1304 1305 static bool annotateAllFunctions( 1306 Module &M, StringRef ProfileFileName, 1307 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, 1308 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { 1309 DEBUG(dbgs() << "Read in profile counters: "); 1310 auto &Ctx = M.getContext(); 1311 // Read the counter array from file. 1312 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName); 1313 if (Error E = ReaderOrErr.takeError()) { 1314 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { 1315 Ctx.diagnose( 1316 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message())); 1317 }); 1318 return false; 1319 } 1320 1321 std::unique_ptr<IndexedInstrProfReader> PGOReader = 1322 std::move(ReaderOrErr.get()); 1323 if (!PGOReader) { 1324 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(), 1325 StringRef("Cannot get PGOReader"))); 1326 return false; 1327 } 1328 // TODO: might need to change the warning once the clang option is finalized. 1329 if (!PGOReader->isIRLevelProfile()) { 1330 Ctx.diagnose(DiagnosticInfoPGOProfile( 1331 ProfileFileName.data(), "Not an IR level instrumentation profile")); 1332 return false; 1333 } 1334 1335 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; 1336 collectComdatMembers(M, ComdatMembers); 1337 std::vector<Function *> HotFunctions; 1338 std::vector<Function *> ColdFunctions; 1339 for (auto &F : M) { 1340 if (F.isDeclaration()) 1341 continue; 1342 auto *BPI = LookupBPI(F); 1343 auto *BFI = LookupBFI(F); 1344 PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI); 1345 if (!Func.readCounters(PGOReader.get())) 1346 continue; 1347 Func.populateCounters(); 1348 Func.setBranchWeights(); 1349 Func.annotateValueSites(); 1350 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr(); 1351 if (FreqAttr == PGOUseFunc::FFA_Cold) 1352 ColdFunctions.push_back(&F); 1353 else if (FreqAttr == PGOUseFunc::FFA_Hot) 1354 HotFunctions.push_back(&F); 1355 if (PGOViewCounts && (ViewBlockFreqFuncName.empty() || 1356 F.getName().equals(ViewBlockFreqFuncName))) { 1357 LoopInfo LI{DominatorTree(F)}; 1358 std::unique_ptr<BranchProbabilityInfo> NewBPI = 1359 llvm::make_unique<BranchProbabilityInfo>(F, LI); 1360 std::unique_ptr<BlockFrequencyInfo> NewBFI = 1361 llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI); 1362 1363 NewBFI->view(); 1364 } 1365 if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() || 1366 F.getName().equals(ViewBlockFreqFuncName))) { 1367 if (ViewBlockFreqFuncName.empty()) 1368 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName()); 1369 else 1370 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName()); 1371 } 1372 } 1373 M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext())); 1374 // Set function hotness attribute from the profile. 1375 // We have to apply these attributes at the end because their presence 1376 // can affect the BranchProbabilityInfo of any callers, resulting in an 1377 // inconsistent MST between prof-gen and prof-use. 1378 for (auto &F : HotFunctions) { 1379 F->addFnAttr(llvm::Attribute::InlineHint); 1380 DEBUG(dbgs() << "Set inline attribute to function: " << F->getName() 1381 << "\n"); 1382 } 1383 for (auto &F : ColdFunctions) { 1384 F->addFnAttr(llvm::Attribute::Cold); 1385 DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n"); 1386 } 1387 return true; 1388 } 1389 1390 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename) 1391 : ProfileFileName(std::move(Filename)) { 1392 if (!PGOTestProfileFile.empty()) 1393 ProfileFileName = PGOTestProfileFile; 1394 } 1395 1396 PreservedAnalyses PGOInstrumentationUse::run(Module &M, 1397 ModuleAnalysisManager &AM) { 1398 1399 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1400 auto LookupBPI = [&FAM](Function &F) { 1401 return &FAM.getResult<BranchProbabilityAnalysis>(F); 1402 }; 1403 1404 auto LookupBFI = [&FAM](Function &F) { 1405 return &FAM.getResult<BlockFrequencyAnalysis>(F); 1406 }; 1407 1408 if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI)) 1409 return PreservedAnalyses::all(); 1410 1411 return PreservedAnalyses::none(); 1412 } 1413 1414 bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) { 1415 if (skipModule(M)) 1416 return false; 1417 1418 auto LookupBPI = [this](Function &F) { 1419 return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); 1420 }; 1421 auto LookupBFI = [this](Function &F) { 1422 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); 1423 }; 1424 1425 return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI); 1426 } 1427 1428 namespace llvm { 1429 template <> struct GraphTraits<PGOUseFunc *> { 1430 typedef const BasicBlock *NodeRef; 1431 typedef succ_const_iterator ChildIteratorType; 1432 typedef pointer_iterator<Function::const_iterator> nodes_iterator; 1433 1434 static NodeRef getEntryNode(const PGOUseFunc *G) { 1435 return &G->getFunc().front(); 1436 } 1437 static ChildIteratorType child_begin(const NodeRef N) { 1438 return succ_begin(N); 1439 } 1440 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); } 1441 static nodes_iterator nodes_begin(const PGOUseFunc *G) { 1442 return nodes_iterator(G->getFunc().begin()); 1443 } 1444 static nodes_iterator nodes_end(const PGOUseFunc *G) { 1445 return nodes_iterator(G->getFunc().end()); 1446 } 1447 }; 1448 1449 static std::string getSimpleNodeName(const BasicBlock *Node) { 1450 if (!Node->getName().empty()) 1451 return Node->getName(); 1452 1453 std::string SimpleNodeName; 1454 raw_string_ostream OS(SimpleNodeName); 1455 Node->printAsOperand(OS, false); 1456 return OS.str(); 1457 } 1458 1459 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits { 1460 explicit DOTGraphTraits(bool isSimple = false) 1461 : DefaultDOTGraphTraits(isSimple) {} 1462 1463 static std::string getGraphName(const PGOUseFunc *G) { 1464 return G->getFunc().getName(); 1465 } 1466 1467 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) { 1468 std::string Result; 1469 raw_string_ostream OS(Result); 1470 1471 OS << getSimpleNodeName(Node) << ":\\l"; 1472 UseBBInfo *BI = Graph->findBBInfo(Node); 1473 OS << "Count : "; 1474 if (BI && BI->CountValid) 1475 OS << BI->CountValue << "\\l"; 1476 else 1477 OS << "Unknown\\l"; 1478 1479 if (!PGOInstrSelect) 1480 return Result; 1481 1482 for (auto BI = Node->begin(); BI != Node->end(); ++BI) { 1483 auto *I = &*BI; 1484 if (!isa<SelectInst>(I)) 1485 continue; 1486 // Display scaled counts for SELECT instruction: 1487 OS << "SELECT : { T = "; 1488 uint64_t TC, FC; 1489 bool HasProf = I->extractProfMetadata(TC, FC); 1490 if (!HasProf) 1491 OS << "Unknown, F = Unknown }\\l"; 1492 else 1493 OS << TC << ", F = " << FC << " }\\l"; 1494 } 1495 return Result; 1496 } 1497 }; 1498 } // namespace llvm 1499