1 //===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements PGO instrumentation using a minimum spanning tree based 10 // on the following paper: 11 // [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points 12 // for program frequency counts. BIT Numerical Mathematics 1973, Volume 13, 13 // Issue 3, pp 313-322 14 // The idea of the algorithm based on the fact that for each node (except for 15 // the entry and exit), the sum of incoming edge counts equals the sum of 16 // outgoing edge counts. The count of edge on spanning tree can be derived from 17 // those edges not on the spanning tree. Knuth proves this method instruments 18 // the minimum number of edges. 19 // 20 // The minimal spanning tree here is actually a maximum weight tree -- on-tree 21 // edges have higher frequencies (more likely to execute). The idea is to 22 // instrument those less frequently executed edges to reduce the runtime 23 // overhead of instrumented binaries. 24 // 25 // This file contains two passes: 26 // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge 27 // count profile, and generates the instrumentation for indirect call 28 // profiling. 29 // (2) Pass PGOInstrumentationUse which reads the edge count profile and 30 // annotates the branch weights. It also reads the indirect call value 31 // profiling records and annotate the indirect call instructions. 32 // 33 // To get the precise counter information, These two passes need to invoke at 34 // the same compilation point (so they see the same IR). For pass 35 // PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For 36 // pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and 37 // the profile is opened in module level and passed to each PGOUseFunc instance. 38 // The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put 39 // in class FuncPGOInstrumentation. 40 // 41 // Class PGOEdge represents a CFG edge and some auxiliary information. Class 42 // BBInfo contains auxiliary information for each BB. These two classes are used 43 // in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived 44 // class of PGOEdge and BBInfo, respectively. They contains extra data structure 45 // used in populating profile counters. 46 // The MST implementation is in Class CFGMST (CFGMST.h). 47 // 48 //===----------------------------------------------------------------------===// 49 50 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h" 51 #include "CFGMST.h" 52 #include "ValueProfileCollector.h" 53 #include "llvm/ADT/APInt.h" 54 #include "llvm/ADT/ArrayRef.h" 55 #include "llvm/ADT/STLExtras.h" 56 #include "llvm/ADT/SmallVector.h" 57 #include "llvm/ADT/Statistic.h" 58 #include "llvm/ADT/StringRef.h" 59 #include "llvm/ADT/Triple.h" 60 #include "llvm/ADT/Twine.h" 61 #include "llvm/ADT/iterator.h" 62 #include "llvm/ADT/iterator_range.h" 63 #include "llvm/Analysis/BlockFrequencyInfo.h" 64 #include "llvm/Analysis/BranchProbabilityInfo.h" 65 #include "llvm/Analysis/CFG.h" 66 #include "llvm/Analysis/EHPersonalities.h" 67 #include "llvm/Analysis/LoopInfo.h" 68 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 69 #include "llvm/Analysis/ProfileSummaryInfo.h" 70 #include "llvm/Analysis/TargetLibraryInfo.h" 71 #include "llvm/IR/Attributes.h" 72 #include "llvm/IR/BasicBlock.h" 73 #include "llvm/IR/CFG.h" 74 #include "llvm/IR/Comdat.h" 75 #include "llvm/IR/Constant.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DiagnosticInfo.h" 78 #include "llvm/IR/Dominators.h" 79 #include "llvm/IR/Function.h" 80 #include "llvm/IR/GlobalAlias.h" 81 #include "llvm/IR/GlobalValue.h" 82 #include "llvm/IR/GlobalVariable.h" 83 #include "llvm/IR/IRBuilder.h" 84 #include "llvm/IR/InstVisitor.h" 85 #include "llvm/IR/InstrTypes.h" 86 #include "llvm/IR/Instruction.h" 87 #include "llvm/IR/Instructions.h" 88 #include "llvm/IR/IntrinsicInst.h" 89 #include "llvm/IR/Intrinsics.h" 90 #include "llvm/IR/LLVMContext.h" 91 #include "llvm/IR/MDBuilder.h" 92 #include "llvm/IR/Module.h" 93 #include "llvm/IR/PassManager.h" 94 #include "llvm/IR/ProfileSummary.h" 95 #include "llvm/IR/Type.h" 96 #include "llvm/IR/Value.h" 97 #include "llvm/ProfileData/InstrProf.h" 98 #include "llvm/ProfileData/InstrProfReader.h" 99 #include "llvm/Support/BranchProbability.h" 100 #include "llvm/Support/CRC.h" 101 #include "llvm/Support/Casting.h" 102 #include "llvm/Support/CommandLine.h" 103 #include "llvm/Support/DOTGraphTraits.h" 104 #include "llvm/Support/Debug.h" 105 #include "llvm/Support/Error.h" 106 #include "llvm/Support/ErrorHandling.h" 107 #include "llvm/Support/GraphWriter.h" 108 #include "llvm/Support/raw_ostream.h" 109 #include "llvm/Transforms/Instrumentation.h" 110 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 111 #include "llvm/Transforms/Utils/MisExpect.h" 112 #include "llvm/Transforms/Utils/ModuleUtils.h" 113 #include <algorithm> 114 #include <cassert> 115 #include <cstdint> 116 #include <memory> 117 #include <numeric> 118 #include <string> 119 #include <unordered_map> 120 #include <utility> 121 #include <vector> 122 123 using namespace llvm; 124 using ProfileCount = Function::ProfileCount; 125 using VPCandidateInfo = ValueProfileCollector::CandidateInfo; 126 127 #define DEBUG_TYPE "pgo-instrumentation" 128 129 STATISTIC(NumOfPGOInstrument, "Number of edges instrumented."); 130 STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented."); 131 STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented."); 132 STATISTIC(NumOfPGOEdge, "Number of edges."); 133 STATISTIC(NumOfPGOBB, "Number of basic-blocks."); 134 STATISTIC(NumOfPGOSplit, "Number of critical edge splits."); 135 STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts."); 136 STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile."); 137 STATISTIC(NumOfPGOMissing, "Number of functions without profile."); 138 STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations."); 139 STATISTIC(NumOfCSPGOInstrument, "Number of edges instrumented in CSPGO."); 140 STATISTIC(NumOfCSPGOSelectInsts, 141 "Number of select instruction instrumented in CSPGO."); 142 STATISTIC(NumOfCSPGOMemIntrinsics, 143 "Number of mem intrinsics instrumented in CSPGO."); 144 STATISTIC(NumOfCSPGOEdge, "Number of edges in CSPGO."); 145 STATISTIC(NumOfCSPGOBB, "Number of basic-blocks in CSPGO."); 146 STATISTIC(NumOfCSPGOSplit, "Number of critical edge splits in CSPGO."); 147 STATISTIC(NumOfCSPGOFunc, 148 "Number of functions having valid profile counts in CSPGO."); 149 STATISTIC(NumOfCSPGOMismatch, 150 "Number of functions having mismatch profile in CSPGO."); 151 STATISTIC(NumOfCSPGOMissing, "Number of functions without profile in CSPGO."); 152 153 // Command line option to specify the file to read profile from. This is 154 // mainly used for testing. 155 static cl::opt<std::string> 156 PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, 157 cl::value_desc("filename"), 158 cl::desc("Specify the path of profile data file. This is" 159 "mainly for test purpose.")); 160 static cl::opt<std::string> PGOTestProfileRemappingFile( 161 "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden, 162 cl::value_desc("filename"), 163 cl::desc("Specify the path of profile remapping file. This is mainly for " 164 "test purpose.")); 165 166 // Command line option to disable value profiling. The default is false: 167 // i.e. value profiling is enabled by default. This is for debug purpose. 168 static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false), 169 cl::Hidden, 170 cl::desc("Disable Value Profiling")); 171 172 // Command line option to set the maximum number of VP annotations to write to 173 // the metadata for a single indirect call callsite. 174 static cl::opt<unsigned> MaxNumAnnotations( 175 "icp-max-annotations", cl::init(3), cl::Hidden, 176 cl::desc("Max number of annotations for a single indirect " 177 "call callsite")); 178 179 // Command line option to set the maximum number of value annotations 180 // to write to the metadata for a single memop intrinsic. 181 static cl::opt<unsigned> MaxNumMemOPAnnotations( 182 "memop-max-annotations", cl::init(4), cl::Hidden, 183 cl::desc("Max number of preicise value annotations for a single memop" 184 "intrinsic")); 185 186 // Command line option to control appending FunctionHash to the name of a COMDAT 187 // function. This is to avoid the hash mismatch caused by the preinliner. 188 static cl::opt<bool> DoComdatRenaming( 189 "do-comdat-renaming", cl::init(false), cl::Hidden, 190 cl::desc("Append function hash to the name of COMDAT function to avoid " 191 "function hash mismatch due to the preinliner")); 192 193 // Command line option to enable/disable the warning about missing profile 194 // information. 195 static cl::opt<bool> 196 PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden, 197 cl::desc("Use this option to turn on/off " 198 "warnings about missing profile data for " 199 "functions.")); 200 201 namespace llvm { 202 // Command line option to enable/disable the warning about a hash mismatch in 203 // the profile data. 204 cl::opt<bool> 205 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden, 206 cl::desc("Use this option to turn off/on " 207 "warnings about profile cfg mismatch.")); 208 } // namespace llvm 209 210 // Command line option to enable/disable the warning about a hash mismatch in 211 // the profile data for Comdat functions, which often turns out to be false 212 // positive due to the pre-instrumentation inline. 213 static cl::opt<bool> NoPGOWarnMismatchComdatWeak( 214 "no-pgo-warn-mismatch-comdat-weak", cl::init(true), cl::Hidden, 215 cl::desc("The option is used to turn on/off " 216 "warnings about hash mismatch for comdat " 217 "or weak functions.")); 218 219 // Command line option to enable/disable select instruction instrumentation. 220 static cl::opt<bool> 221 PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden, 222 cl::desc("Use this option to turn on/off SELECT " 223 "instruction instrumentation. ")); 224 225 // Command line option to turn on CFG dot or text dump of raw profile counts 226 static cl::opt<PGOViewCountsType> PGOViewRawCounts( 227 "pgo-view-raw-counts", cl::Hidden, 228 cl::desc("A boolean option to show CFG dag or text " 229 "with raw profile counts from " 230 "profile data. See also option " 231 "-pgo-view-counts. To limit graph " 232 "display to only one function, use " 233 "filtering option -view-bfi-func-name."), 234 cl::values(clEnumValN(PGOVCT_None, "none", "do not show."), 235 clEnumValN(PGOVCT_Graph, "graph", "show a graph."), 236 clEnumValN(PGOVCT_Text, "text", "show in text."))); 237 238 // Command line option to enable/disable memop intrinsic call.size profiling. 239 static cl::opt<bool> 240 PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden, 241 cl::desc("Use this option to turn on/off " 242 "memory intrinsic size profiling.")); 243 244 // Emit branch probability as optimization remarks. 245 static cl::opt<bool> 246 EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden, 247 cl::desc("When this option is on, the annotated " 248 "branch probability will be emitted as " 249 "optimization remarks: -{Rpass|" 250 "pass-remarks}=pgo-instrumentation")); 251 252 static cl::opt<bool> PGOInstrumentEntry( 253 "pgo-instrument-entry", cl::init(false), cl::Hidden, 254 cl::desc("Force to instrument function entry basicblock.")); 255 256 static cl::opt<bool> PGOFunctionEntryCoverage( 257 "pgo-function-entry-coverage", cl::Hidden, 258 cl::desc( 259 "Use this option to enable function entry coverage instrumentation.")); 260 261 static cl::opt<bool> 262 PGOFixEntryCount("pgo-fix-entry-count", cl::init(true), cl::Hidden, 263 cl::desc("Fix function entry count in profile use.")); 264 265 static cl::opt<bool> PGOVerifyHotBFI( 266 "pgo-verify-hot-bfi", cl::init(false), cl::Hidden, 267 cl::desc("Print out the non-match BFI count if a hot raw profile count " 268 "becomes non-hot, or a cold raw profile count becomes hot. " 269 "The print is enabled under -Rpass-analysis=pgo, or " 270 "internal option -pass-remakrs-analysis=pgo.")); 271 272 static cl::opt<bool> PGOVerifyBFI( 273 "pgo-verify-bfi", cl::init(false), cl::Hidden, 274 cl::desc("Print out mismatched BFI counts after setting profile metadata " 275 "The print is enabled under -Rpass-analysis=pgo, or " 276 "internal option -pass-remakrs-analysis=pgo.")); 277 278 static cl::opt<unsigned> PGOVerifyBFIRatio( 279 "pgo-verify-bfi-ratio", cl::init(2), cl::Hidden, 280 cl::desc("Set the threshold for pgo-verify-bfi: only print out " 281 "mismatched BFI if the difference percentage is greater than " 282 "this value (in percentage).")); 283 284 static cl::opt<unsigned> PGOVerifyBFICutoff( 285 "pgo-verify-bfi-cutoff", cl::init(5), cl::Hidden, 286 cl::desc("Set the threshold for pgo-verify-bfi: skip the counts whose " 287 "profile count value is below.")); 288 289 static cl::opt<std::string> PGOTraceFuncHash( 290 "pgo-trace-func-hash", cl::init("-"), cl::Hidden, 291 cl::value_desc("function name"), 292 cl::desc("Trace the hash of the function with this name.")); 293 294 namespace llvm { 295 // Command line option to turn on CFG dot dump after profile annotation. 296 // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts 297 extern cl::opt<PGOViewCountsType> PGOViewCounts; 298 299 // Command line option to specify the name of the function for CFG dump 300 // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= 301 extern cl::opt<std::string> ViewBlockFreqFuncName; 302 303 extern cl::opt<bool> DebugInfoCorrelate; 304 } // namespace llvm 305 306 static cl::opt<bool> 307 PGOOldCFGHashing("pgo-instr-old-cfg-hashing", cl::init(false), cl::Hidden, 308 cl::desc("Use the old CFG function hashing")); 309 310 // Return a string describing the branch condition that can be 311 // used in static branch probability heuristics: 312 static std::string getBranchCondString(Instruction *TI) { 313 BranchInst *BI = dyn_cast<BranchInst>(TI); 314 if (!BI || !BI->isConditional()) 315 return std::string(); 316 317 Value *Cond = BI->getCondition(); 318 ICmpInst *CI = dyn_cast<ICmpInst>(Cond); 319 if (!CI) 320 return std::string(); 321 322 std::string result; 323 raw_string_ostream OS(result); 324 OS << CmpInst::getPredicateName(CI->getPredicate()) << "_"; 325 CI->getOperand(0)->getType()->print(OS, true); 326 327 Value *RHS = CI->getOperand(1); 328 ConstantInt *CV = dyn_cast<ConstantInt>(RHS); 329 if (CV) { 330 if (CV->isZero()) 331 OS << "_Zero"; 332 else if (CV->isOne()) 333 OS << "_One"; 334 else if (CV->isMinusOne()) 335 OS << "_MinusOne"; 336 else 337 OS << "_Const"; 338 } 339 OS.flush(); 340 return result; 341 } 342 343 static const char *ValueProfKindDescr[] = { 344 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr, 345 #include "llvm/ProfileData/InstrProfData.inc" 346 }; 347 348 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime 349 // aware this is an ir_level profile so it can set the version flag. 350 static GlobalVariable *createIRLevelProfileFlagVar(Module &M, bool IsCS) { 351 const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)); 352 Type *IntTy64 = Type::getInt64Ty(M.getContext()); 353 uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF); 354 if (IsCS) 355 ProfileVersion |= VARIANT_MASK_CSIR_PROF; 356 if (PGOInstrumentEntry) 357 ProfileVersion |= VARIANT_MASK_INSTR_ENTRY; 358 if (DebugInfoCorrelate) 359 ProfileVersion |= VARIANT_MASK_DBG_CORRELATE; 360 if (PGOFunctionEntryCoverage) 361 ProfileVersion |= 362 VARIANT_MASK_BYTE_COVERAGE | VARIANT_MASK_FUNCTION_ENTRY_ONLY; 363 auto IRLevelVersionVariable = new GlobalVariable( 364 M, IntTy64, true, GlobalValue::WeakAnyLinkage, 365 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), VarName); 366 IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility); 367 Triple TT(M.getTargetTriple()); 368 if (TT.supportsCOMDAT()) { 369 IRLevelVersionVariable->setLinkage(GlobalValue::ExternalLinkage); 370 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName)); 371 } 372 return IRLevelVersionVariable; 373 } 374 375 namespace { 376 377 /// The select instruction visitor plays three roles specified 378 /// by the mode. In \c VM_counting mode, it simply counts the number of 379 /// select instructions. In \c VM_instrument mode, it inserts code to count 380 /// the number times TrueValue of select is taken. In \c VM_annotate mode, 381 /// it reads the profile data and annotate the select instruction with metadata. 382 enum VisitMode { VM_counting, VM_instrument, VM_annotate }; 383 class PGOUseFunc; 384 385 /// Instruction Visitor class to visit select instructions. 386 struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> { 387 Function &F; 388 unsigned NSIs = 0; // Number of select instructions instrumented. 389 VisitMode Mode = VM_counting; // Visiting mode. 390 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index. 391 unsigned TotalNumCtrs = 0; // Total number of counters 392 GlobalVariable *FuncNameVar = nullptr; 393 uint64_t FuncHash = 0; 394 PGOUseFunc *UseFunc = nullptr; 395 396 SelectInstVisitor(Function &Func) : F(Func) {} 397 398 void countSelects(Function &Func) { 399 NSIs = 0; 400 Mode = VM_counting; 401 visit(Func); 402 } 403 404 // Visit the IR stream and instrument all select instructions. \p 405 // Ind is a pointer to the counter index variable; \p TotalNC 406 // is the total number of counters; \p FNV is the pointer to the 407 // PGO function name var; \p FHash is the function hash. 408 void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC, 409 GlobalVariable *FNV, uint64_t FHash) { 410 Mode = VM_instrument; 411 CurCtrIdx = Ind; 412 TotalNumCtrs = TotalNC; 413 FuncHash = FHash; 414 FuncNameVar = FNV; 415 visit(Func); 416 } 417 418 // Visit the IR stream and annotate all select instructions. 419 void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) { 420 Mode = VM_annotate; 421 UseFunc = UF; 422 CurCtrIdx = Ind; 423 visit(Func); 424 } 425 426 void instrumentOneSelectInst(SelectInst &SI); 427 void annotateOneSelectInst(SelectInst &SI); 428 429 // Visit \p SI instruction and perform tasks according to visit mode. 430 void visitSelectInst(SelectInst &SI); 431 432 // Return the number of select instructions. This needs be called after 433 // countSelects(). 434 unsigned getNumOfSelectInsts() const { return NSIs; } 435 }; 436 437 } // end anonymous namespace 438 439 namespace { 440 441 /// An MST based instrumentation for PGO 442 /// 443 /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO 444 /// in the function level. 445 struct PGOEdge { 446 // This class implements the CFG edges. Note the CFG can be a multi-graph. 447 // So there might be multiple edges with same SrcBB and DestBB. 448 const BasicBlock *SrcBB; 449 const BasicBlock *DestBB; 450 uint64_t Weight; 451 bool InMST = false; 452 bool Removed = false; 453 bool IsCritical = false; 454 455 PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1) 456 : SrcBB(Src), DestBB(Dest), Weight(W) {} 457 458 // Return the information string of an edge. 459 std::string infoString() const { 460 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") + 461 (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str(); 462 } 463 }; 464 465 // This class stores the auxiliary information for each BB. 466 struct BBInfo { 467 BBInfo *Group; 468 uint32_t Index; 469 uint32_t Rank = 0; 470 471 BBInfo(unsigned IX) : Group(this), Index(IX) {} 472 473 // Return the information string of this object. 474 std::string infoString() const { 475 return (Twine("Index=") + Twine(Index)).str(); 476 } 477 478 // Empty function -- only applicable to UseBBInfo. 479 void addOutEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {} 480 481 // Empty function -- only applicable to UseBBInfo. 482 void addInEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {} 483 }; 484 485 // This class implements the CFG edges. Note the CFG can be a multi-graph. 486 template <class Edge, class BBInfo> class FuncPGOInstrumentation { 487 private: 488 Function &F; 489 490 // Is this is context-sensitive instrumentation. 491 bool IsCS; 492 493 // A map that stores the Comdat group in function F. 494 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers; 495 496 ValueProfileCollector VPC; 497 498 void computeCFGHash(); 499 void renameComdatFunction(); 500 501 public: 502 std::vector<std::vector<VPCandidateInfo>> ValueSites; 503 SelectInstVisitor SIVisitor; 504 std::string FuncName; 505 GlobalVariable *FuncNameVar; 506 507 // CFG hash value for this function. 508 uint64_t FunctionHash = 0; 509 510 // The Minimum Spanning Tree of function CFG. 511 CFGMST<Edge, BBInfo> MST; 512 513 // Collect all the BBs that will be instrumented, and store them in 514 // InstrumentBBs. 515 void getInstrumentBBs(std::vector<BasicBlock *> &InstrumentBBs); 516 517 // Give an edge, find the BB that will be instrumented. 518 // Return nullptr if there is no BB to be instrumented. 519 BasicBlock *getInstrBB(Edge *E); 520 521 // Return the auxiliary BB information. 522 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); } 523 524 // Return the auxiliary BB information if available. 525 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); } 526 527 // Dump edges and BB information. 528 void dumpInfo(std::string Str = "") const { 529 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " + 530 Twine(FunctionHash) + "\t" + Str); 531 } 532 533 FuncPGOInstrumentation( 534 Function &Func, TargetLibraryInfo &TLI, 535 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, 536 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr, 537 BlockFrequencyInfo *BFI = nullptr, bool IsCS = false, 538 bool InstrumentFuncEntry = true) 539 : F(Func), IsCS(IsCS), ComdatMembers(ComdatMembers), VPC(Func, TLI), 540 ValueSites(IPVK_Last + 1), SIVisitor(Func), 541 MST(F, InstrumentFuncEntry, BPI, BFI) { 542 // This should be done before CFG hash computation. 543 SIVisitor.countSelects(Func); 544 ValueSites[IPVK_MemOPSize] = VPC.get(IPVK_MemOPSize); 545 if (!IsCS) { 546 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts(); 547 NumOfPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size(); 548 NumOfPGOBB += MST.BBInfos.size(); 549 ValueSites[IPVK_IndirectCallTarget] = VPC.get(IPVK_IndirectCallTarget); 550 } else { 551 NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts(); 552 NumOfCSPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size(); 553 NumOfCSPGOBB += MST.BBInfos.size(); 554 } 555 556 FuncName = getPGOFuncName(F); 557 computeCFGHash(); 558 if (!ComdatMembers.empty()) 559 renameComdatFunction(); 560 LLVM_DEBUG(dumpInfo("after CFGMST")); 561 562 for (auto &E : MST.AllEdges) { 563 if (E->Removed) 564 continue; 565 IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++; 566 if (!E->InMST) 567 IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++; 568 } 569 570 if (CreateGlobalVar) 571 FuncNameVar = createPGOFuncNameVar(F, FuncName); 572 } 573 }; 574 575 } // end anonymous namespace 576 577 // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index 578 // value of each BB in the CFG. The higher 32 bits are the CRC32 of the numbers 579 // of selects, indirect calls, mem ops and edges. 580 template <class Edge, class BBInfo> 581 void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() { 582 std::vector<uint8_t> Indexes; 583 JamCRC JC; 584 for (auto &BB : F) { 585 const Instruction *TI = BB.getTerminator(); 586 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) { 587 BasicBlock *Succ = TI->getSuccessor(I); 588 auto BI = findBBInfo(Succ); 589 if (BI == nullptr) 590 continue; 591 uint32_t Index = BI->Index; 592 for (int J = 0; J < 4; J++) 593 Indexes.push_back((uint8_t)(Index >> (J * 8))); 594 } 595 } 596 JC.update(Indexes); 597 598 JamCRC JCH; 599 if (PGOOldCFGHashing) { 600 // Hash format for context sensitive profile. Reserve 4 bits for other 601 // information. 602 FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 | 603 (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 | 604 //(uint64_t)ValueSites[IPVK_MemOPSize].size() << 40 | 605 (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC(); 606 } else { 607 // The higher 32 bits. 608 auto updateJCH = [&JCH](uint64_t Num) { 609 uint8_t Data[8]; 610 support::endian::write64le(Data, Num); 611 JCH.update(Data); 612 }; 613 updateJCH((uint64_t)SIVisitor.getNumOfSelectInsts()); 614 updateJCH((uint64_t)ValueSites[IPVK_IndirectCallTarget].size()); 615 updateJCH((uint64_t)ValueSites[IPVK_MemOPSize].size()); 616 updateJCH((uint64_t)MST.AllEdges.size()); 617 618 // Hash format for context sensitive profile. Reserve 4 bits for other 619 // information. 620 FunctionHash = (((uint64_t)JCH.getCRC()) << 28) + JC.getCRC(); 621 } 622 623 // Reserve bit 60-63 for other information purpose. 624 FunctionHash &= 0x0FFFFFFFFFFFFFFF; 625 if (IsCS) 626 NamedInstrProfRecord::setCSFlagInHash(FunctionHash); 627 LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n" 628 << " CRC = " << JC.getCRC() 629 << ", Selects = " << SIVisitor.getNumOfSelectInsts() 630 << ", Edges = " << MST.AllEdges.size() << ", ICSites = " 631 << ValueSites[IPVK_IndirectCallTarget].size()); 632 if (!PGOOldCFGHashing) { 633 LLVM_DEBUG(dbgs() << ", Memops = " << ValueSites[IPVK_MemOPSize].size() 634 << ", High32 CRC = " << JCH.getCRC()); 635 } 636 LLVM_DEBUG(dbgs() << ", Hash = " << FunctionHash << "\n";); 637 638 if (PGOTraceFuncHash != "-" && F.getName().contains(PGOTraceFuncHash)) 639 dbgs() << "Funcname=" << F.getName() << ", Hash=" << FunctionHash 640 << " in building " << F.getParent()->getSourceFileName() << "\n"; 641 } 642 643 // Check if we can safely rename this Comdat function. 644 static bool canRenameComdat( 645 Function &F, 646 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { 647 if (!DoComdatRenaming || !canRenameComdatFunc(F, true)) 648 return false; 649 650 // FIXME: Current only handle those Comdat groups that only containing one 651 // function. 652 // (1) For a Comdat group containing multiple functions, we need to have a 653 // unique postfix based on the hashes for each function. There is a 654 // non-trivial code refactoring to do this efficiently. 655 // (2) Variables can not be renamed, so we can not rename Comdat function in a 656 // group including global vars. 657 Comdat *C = F.getComdat(); 658 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) { 659 assert(!isa<GlobalAlias>(CM.second)); 660 Function *FM = dyn_cast<Function>(CM.second); 661 if (FM != &F) 662 return false; 663 } 664 return true; 665 } 666 667 // Append the CFGHash to the Comdat function name. 668 template <class Edge, class BBInfo> 669 void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() { 670 if (!canRenameComdat(F, ComdatMembers)) 671 return; 672 std::string OrigName = F.getName().str(); 673 std::string NewFuncName = 674 Twine(F.getName() + "." + Twine(FunctionHash)).str(); 675 F.setName(Twine(NewFuncName)); 676 GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F); 677 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str(); 678 Comdat *NewComdat; 679 Module *M = F.getParent(); 680 // For AvailableExternallyLinkage functions, change the linkage to 681 // LinkOnceODR and put them into comdat. This is because after renaming, there 682 // is no backup external copy available for the function. 683 if (!F.hasComdat()) { 684 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage); 685 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName)); 686 F.setLinkage(GlobalValue::LinkOnceODRLinkage); 687 F.setComdat(NewComdat); 688 return; 689 } 690 691 // This function belongs to a single function Comdat group. 692 Comdat *OrigComdat = F.getComdat(); 693 std::string NewComdatName = 694 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str(); 695 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName)); 696 NewComdat->setSelectionKind(OrigComdat->getSelectionKind()); 697 698 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) { 699 // Must be a function. 700 cast<Function>(CM.second)->setComdat(NewComdat); 701 } 702 } 703 704 // Collect all the BBs that will be instruments and return them in 705 // InstrumentBBs and setup InEdges/OutEdge for UseBBInfo. 706 template <class Edge, class BBInfo> 707 void FuncPGOInstrumentation<Edge, BBInfo>::getInstrumentBBs( 708 std::vector<BasicBlock *> &InstrumentBBs) { 709 // Use a worklist as we will update the vector during the iteration. 710 std::vector<Edge *> EdgeList; 711 EdgeList.reserve(MST.AllEdges.size()); 712 for (auto &E : MST.AllEdges) 713 EdgeList.push_back(E.get()); 714 715 for (auto &E : EdgeList) { 716 BasicBlock *InstrBB = getInstrBB(E); 717 if (InstrBB) 718 InstrumentBBs.push_back(InstrBB); 719 } 720 721 // Set up InEdges/OutEdges for all BBs. 722 for (auto &E : MST.AllEdges) { 723 if (E->Removed) 724 continue; 725 const BasicBlock *SrcBB = E->SrcBB; 726 const BasicBlock *DestBB = E->DestBB; 727 BBInfo &SrcInfo = getBBInfo(SrcBB); 728 BBInfo &DestInfo = getBBInfo(DestBB); 729 SrcInfo.addOutEdge(E.get()); 730 DestInfo.addInEdge(E.get()); 731 } 732 } 733 734 // Given a CFG E to be instrumented, find which BB to place the instrumented 735 // code. The function will split the critical edge if necessary. 736 template <class Edge, class BBInfo> 737 BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) { 738 if (E->InMST || E->Removed) 739 return nullptr; 740 741 BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); 742 BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); 743 // For a fake edge, instrument the real BB. 744 if (SrcBB == nullptr) 745 return DestBB; 746 if (DestBB == nullptr) 747 return SrcBB; 748 749 auto canInstrument = [](BasicBlock *BB) -> BasicBlock * { 750 // There are basic blocks (such as catchswitch) cannot be instrumented. 751 // If the returned first insertion point is the end of BB, skip this BB. 752 if (BB->getFirstInsertionPt() == BB->end()) 753 return nullptr; 754 return BB; 755 }; 756 757 // Instrument the SrcBB if it has a single successor, 758 // otherwise, the DestBB if this is not a critical edge. 759 Instruction *TI = SrcBB->getTerminator(); 760 if (TI->getNumSuccessors() <= 1) 761 return canInstrument(SrcBB); 762 if (!E->IsCritical) 763 return canInstrument(DestBB); 764 765 // Some IndirectBr critical edges cannot be split by the previous 766 // SplitIndirectBrCriticalEdges call. Bail out. 767 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); 768 BasicBlock *InstrBB = 769 isa<IndirectBrInst>(TI) ? nullptr : SplitCriticalEdge(TI, SuccNum); 770 if (!InstrBB) { 771 LLVM_DEBUG( 772 dbgs() << "Fail to split critical edge: not instrument this edge.\n"); 773 return nullptr; 774 } 775 // For a critical edge, we have to split. Instrument the newly 776 // created BB. 777 IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++; 778 LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index 779 << " --> " << getBBInfo(DestBB).Index << "\n"); 780 // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB. 781 MST.addEdge(SrcBB, InstrBB, 0); 782 // Second one: Add new edge of InstrBB->DestBB. 783 Edge &NewEdge1 = MST.addEdge(InstrBB, DestBB, 0); 784 NewEdge1.InMST = true; 785 E->Removed = true; 786 787 return canInstrument(InstrBB); 788 } 789 790 // When generating value profiling calls on Windows routines that make use of 791 // handler funclets for exception processing an operand bundle needs to attached 792 // to the called function. This routine will set \p OpBundles to contain the 793 // funclet information, if any is needed, that should be placed on the generated 794 // value profiling call for the value profile candidate call. 795 static void 796 populateEHOperandBundle(VPCandidateInfo &Cand, 797 DenseMap<BasicBlock *, ColorVector> &BlockColors, 798 SmallVectorImpl<OperandBundleDef> &OpBundles) { 799 auto *OrigCall = dyn_cast<CallBase>(Cand.AnnotatedInst); 800 if (!OrigCall) 801 return; 802 803 if (!isa<IntrinsicInst>(OrigCall)) { 804 // The instrumentation call should belong to the same funclet as a 805 // non-intrinsic call, so just copy the operand bundle, if any exists. 806 Optional<OperandBundleUse> ParentFunclet = 807 OrigCall->getOperandBundle(LLVMContext::OB_funclet); 808 if (ParentFunclet) 809 OpBundles.emplace_back(OperandBundleDef(*ParentFunclet)); 810 } else { 811 // Intrinsics or other instructions do not get funclet information from the 812 // front-end. Need to use the BlockColors that was computed by the routine 813 // colorEHFunclets to determine whether a funclet is needed. 814 if (!BlockColors.empty()) { 815 const ColorVector &CV = BlockColors.find(OrigCall->getParent())->second; 816 assert(CV.size() == 1 && "non-unique color for block!"); 817 Instruction *EHPad = CV.front()->getFirstNonPHI(); 818 if (EHPad->isEHPad()) 819 OpBundles.emplace_back("funclet", EHPad); 820 } 821 } 822 } 823 824 // Visit all edge and instrument the edges not in MST, and do value profiling. 825 // Critical edges will be split. 826 static void instrumentOneFunc( 827 Function &F, Module *M, TargetLibraryInfo &TLI, BranchProbabilityInfo *BPI, 828 BlockFrequencyInfo *BFI, 829 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, 830 bool IsCS) { 831 // Split indirectbr critical edges here before computing the MST rather than 832 // later in getInstrBB() to avoid invalidating it. 833 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI, BFI); 834 835 FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo( 836 F, TLI, ComdatMembers, true, BPI, BFI, IsCS, PGOInstrumentEntry); 837 838 Type *I8PtrTy = Type::getInt8PtrTy(M->getContext()); 839 auto Name = ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy); 840 auto CFGHash = ConstantInt::get(Type::getInt64Ty(M->getContext()), 841 FuncInfo.FunctionHash); 842 if (PGOFunctionEntryCoverage) { 843 auto &EntryBB = F.getEntryBlock(); 844 IRBuilder<> Builder(&EntryBB, EntryBB.getFirstInsertionPt()); 845 // llvm.instrprof.cover(i8* <name>, i64 <hash>, i32 <num-counters>, 846 // i32 <index>) 847 Builder.CreateCall( 848 Intrinsic::getDeclaration(M, Intrinsic::instrprof_cover), 849 {Name, CFGHash, Builder.getInt32(1), Builder.getInt32(0)}); 850 return; 851 } 852 853 std::vector<BasicBlock *> InstrumentBBs; 854 FuncInfo.getInstrumentBBs(InstrumentBBs); 855 unsigned NumCounters = 856 InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts(); 857 858 uint32_t I = 0; 859 for (auto *InstrBB : InstrumentBBs) { 860 IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt()); 861 assert(Builder.GetInsertPoint() != InstrBB->end() && 862 "Cannot get the Instrumentation point"); 863 // llvm.instrprof.increment(i8* <name>, i64 <hash>, i32 <num-counters>, 864 // i32 <index>) 865 Builder.CreateCall( 866 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment), 867 {Name, CFGHash, Builder.getInt32(NumCounters), Builder.getInt32(I++)}); 868 } 869 870 // Now instrument select instructions: 871 FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar, 872 FuncInfo.FunctionHash); 873 assert(I == NumCounters); 874 875 if (DisableValueProfiling) 876 return; 877 878 NumOfPGOICall += FuncInfo.ValueSites[IPVK_IndirectCallTarget].size(); 879 880 // Intrinsic function calls do not have funclet operand bundles needed for 881 // Windows exception handling attached to them. However, if value profiling is 882 // inserted for one of these calls, then a funclet value will need to be set 883 // on the instrumentation call based on the funclet coloring. 884 DenseMap<BasicBlock *, ColorVector> BlockColors; 885 if (F.hasPersonalityFn() && 886 isFuncletEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) 887 BlockColors = colorEHFunclets(F); 888 889 // For each VP Kind, walk the VP candidates and instrument each one. 890 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) { 891 unsigned SiteIndex = 0; 892 if (Kind == IPVK_MemOPSize && !PGOInstrMemOP) 893 continue; 894 895 for (VPCandidateInfo Cand : FuncInfo.ValueSites[Kind]) { 896 LLVM_DEBUG(dbgs() << "Instrument one VP " << ValueProfKindDescr[Kind] 897 << " site: CallSite Index = " << SiteIndex << "\n"); 898 899 IRBuilder<> Builder(Cand.InsertPt); 900 assert(Builder.GetInsertPoint() != Cand.InsertPt->getParent()->end() && 901 "Cannot get the Instrumentation point"); 902 903 Value *ToProfile = nullptr; 904 if (Cand.V->getType()->isIntegerTy()) 905 ToProfile = Builder.CreateZExtOrTrunc(Cand.V, Builder.getInt64Ty()); 906 else if (Cand.V->getType()->isPointerTy()) 907 ToProfile = Builder.CreatePtrToInt(Cand.V, Builder.getInt64Ty()); 908 assert(ToProfile && "value profiling Value is of unexpected type"); 909 910 SmallVector<OperandBundleDef, 1> OpBundles; 911 populateEHOperandBundle(Cand, BlockColors, OpBundles); 912 Builder.CreateCall( 913 Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile), 914 {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), 915 Builder.getInt64(FuncInfo.FunctionHash), ToProfile, 916 Builder.getInt32(Kind), Builder.getInt32(SiteIndex++)}, 917 OpBundles); 918 } 919 } // IPVK_First <= Kind <= IPVK_Last 920 } 921 922 namespace { 923 924 // This class represents a CFG edge in profile use compilation. 925 struct PGOUseEdge : public PGOEdge { 926 bool CountValid = false; 927 uint64_t CountValue = 0; 928 929 PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1) 930 : PGOEdge(Src, Dest, W) {} 931 932 // Set edge count value 933 void setEdgeCount(uint64_t Value) { 934 CountValue = Value; 935 CountValid = true; 936 } 937 938 // Return the information string for this object. 939 std::string infoString() const { 940 if (!CountValid) 941 return PGOEdge::infoString(); 942 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue)) 943 .str(); 944 } 945 }; 946 947 using DirectEdges = SmallVector<PGOUseEdge *, 2>; 948 949 // This class stores the auxiliary information for each BB. 950 struct UseBBInfo : public BBInfo { 951 uint64_t CountValue = 0; 952 bool CountValid; 953 int32_t UnknownCountInEdge = 0; 954 int32_t UnknownCountOutEdge = 0; 955 DirectEdges InEdges; 956 DirectEdges OutEdges; 957 958 UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {} 959 960 UseBBInfo(unsigned IX, uint64_t C) 961 : BBInfo(IX), CountValue(C), CountValid(true) {} 962 963 // Set the profile count value for this BB. 964 void setBBInfoCount(uint64_t Value) { 965 CountValue = Value; 966 CountValid = true; 967 } 968 969 // Return the information string of this object. 970 std::string infoString() const { 971 if (!CountValid) 972 return BBInfo::infoString(); 973 return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str(); 974 } 975 976 // Add an OutEdge and update the edge count. 977 void addOutEdge(PGOUseEdge *E) { 978 OutEdges.push_back(E); 979 UnknownCountOutEdge++; 980 } 981 982 // Add an InEdge and update the edge count. 983 void addInEdge(PGOUseEdge *E) { 984 InEdges.push_back(E); 985 UnknownCountInEdge++; 986 } 987 }; 988 989 } // end anonymous namespace 990 991 // Sum up the count values for all the edges. 992 static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) { 993 uint64_t Total = 0; 994 for (auto &E : Edges) { 995 if (E->Removed) 996 continue; 997 Total += E->CountValue; 998 } 999 return Total; 1000 } 1001 1002 namespace { 1003 1004 class PGOUseFunc { 1005 public: 1006 PGOUseFunc(Function &Func, Module *Modu, TargetLibraryInfo &TLI, 1007 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, 1008 BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFIin, 1009 ProfileSummaryInfo *PSI, bool IsCS, bool InstrumentFuncEntry) 1010 : F(Func), M(Modu), BFI(BFIin), PSI(PSI), 1011 FuncInfo(Func, TLI, ComdatMembers, false, BPI, BFIin, IsCS, 1012 InstrumentFuncEntry), 1013 FreqAttr(FFA_Normal), IsCS(IsCS) {} 1014 1015 // Read counts for the instrumented BB from profile. 1016 bool readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros, 1017 bool &AllMinusOnes); 1018 1019 // Populate the counts for all BBs. 1020 void populateCounters(); 1021 1022 // Set the branch weights based on the count values. 1023 void setBranchWeights(); 1024 1025 // Annotate the value profile call sites for all value kind. 1026 void annotateValueSites(); 1027 1028 // Annotate the value profile call sites for one value kind. 1029 void annotateValueSites(uint32_t Kind); 1030 1031 // Annotate the irreducible loop header weights. 1032 void annotateIrrLoopHeaderWeights(); 1033 1034 // The hotness of the function from the profile count. 1035 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot }; 1036 1037 // Return the function hotness from the profile. 1038 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; } 1039 1040 // Return the function hash. 1041 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; } 1042 1043 // Return the profile record for this function; 1044 InstrProfRecord &getProfileRecord() { return ProfileRecord; } 1045 1046 // Return the auxiliary BB information. 1047 UseBBInfo &getBBInfo(const BasicBlock *BB) const { 1048 return FuncInfo.getBBInfo(BB); 1049 } 1050 1051 // Return the auxiliary BB information if available. 1052 UseBBInfo *findBBInfo(const BasicBlock *BB) const { 1053 return FuncInfo.findBBInfo(BB); 1054 } 1055 1056 Function &getFunc() const { return F; } 1057 1058 void dumpInfo(std::string Str = "") const { 1059 FuncInfo.dumpInfo(Str); 1060 } 1061 1062 uint64_t getProgramMaxCount() const { return ProgramMaxCount; } 1063 private: 1064 Function &F; 1065 Module *M; 1066 BlockFrequencyInfo *BFI; 1067 ProfileSummaryInfo *PSI; 1068 1069 // This member stores the shared information with class PGOGenFunc. 1070 FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo; 1071 1072 // The maximum count value in the profile. This is only used in PGO use 1073 // compilation. 1074 uint64_t ProgramMaxCount; 1075 1076 // Position of counter that remains to be read. 1077 uint32_t CountPosition = 0; 1078 1079 // Total size of the profile count for this function. 1080 uint32_t ProfileCountSize = 0; 1081 1082 // ProfileRecord for this function. 1083 InstrProfRecord ProfileRecord; 1084 1085 // Function hotness info derived from profile. 1086 FuncFreqAttr FreqAttr; 1087 1088 // Is to use the context sensitive profile. 1089 bool IsCS; 1090 1091 // Find the Instrumented BB and set the value. Return false on error. 1092 bool setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile); 1093 1094 // Set the edge counter value for the unknown edge -- there should be only 1095 // one unknown edge. 1096 void setEdgeCount(DirectEdges &Edges, uint64_t Value); 1097 1098 // Return FuncName string; 1099 std::string getFuncName() const { return FuncInfo.FuncName; } 1100 1101 // Set the hot/cold inline hints based on the count values. 1102 // FIXME: This function should be removed once the functionality in 1103 // the inliner is implemented. 1104 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) { 1105 if (PSI->isHotCount(EntryCount)) 1106 FreqAttr = FFA_Hot; 1107 else if (PSI->isColdCount(MaxCount)) 1108 FreqAttr = FFA_Cold; 1109 } 1110 }; 1111 1112 } // end anonymous namespace 1113 1114 // Visit all the edges and assign the count value for the instrumented 1115 // edges and the BB. Return false on error. 1116 bool PGOUseFunc::setInstrumentedCounts( 1117 const std::vector<uint64_t> &CountFromProfile) { 1118 1119 std::vector<BasicBlock *> InstrumentBBs; 1120 FuncInfo.getInstrumentBBs(InstrumentBBs); 1121 unsigned NumCounters = 1122 InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts(); 1123 // The number of counters here should match the number of counters 1124 // in profile. Return if they mismatch. 1125 if (NumCounters != CountFromProfile.size()) { 1126 return false; 1127 } 1128 auto *FuncEntry = &*F.begin(); 1129 1130 // Set the profile count to the Instrumented BBs. 1131 uint32_t I = 0; 1132 for (BasicBlock *InstrBB : InstrumentBBs) { 1133 uint64_t CountValue = CountFromProfile[I++]; 1134 UseBBInfo &Info = getBBInfo(InstrBB); 1135 // If we reach here, we know that we have some nonzero count 1136 // values in this function. The entry count should not be 0. 1137 // Fix it if necessary. 1138 if (InstrBB == FuncEntry && CountValue == 0) 1139 CountValue = 1; 1140 Info.setBBInfoCount(CountValue); 1141 } 1142 ProfileCountSize = CountFromProfile.size(); 1143 CountPosition = I; 1144 1145 // Set the edge count and update the count of unknown edges for BBs. 1146 auto setEdgeCount = [this](PGOUseEdge *E, uint64_t Value) -> void { 1147 E->setEdgeCount(Value); 1148 this->getBBInfo(E->SrcBB).UnknownCountOutEdge--; 1149 this->getBBInfo(E->DestBB).UnknownCountInEdge--; 1150 }; 1151 1152 // Set the profile count the Instrumented edges. There are BBs that not in 1153 // MST but not instrumented. Need to set the edge count value so that we can 1154 // populate the profile counts later. 1155 for (auto &E : FuncInfo.MST.AllEdges) { 1156 if (E->Removed || E->InMST) 1157 continue; 1158 const BasicBlock *SrcBB = E->SrcBB; 1159 UseBBInfo &SrcInfo = getBBInfo(SrcBB); 1160 1161 // If only one out-edge, the edge profile count should be the same as BB 1162 // profile count. 1163 if (SrcInfo.CountValid && SrcInfo.OutEdges.size() == 1) 1164 setEdgeCount(E.get(), SrcInfo.CountValue); 1165 else { 1166 const BasicBlock *DestBB = E->DestBB; 1167 UseBBInfo &DestInfo = getBBInfo(DestBB); 1168 // If only one in-edge, the edge profile count should be the same as BB 1169 // profile count. 1170 if (DestInfo.CountValid && DestInfo.InEdges.size() == 1) 1171 setEdgeCount(E.get(), DestInfo.CountValue); 1172 } 1173 if (E->CountValid) 1174 continue; 1175 // E's count should have been set from profile. If not, this meenas E skips 1176 // the instrumentation. We set the count to 0. 1177 setEdgeCount(E.get(), 0); 1178 } 1179 return true; 1180 } 1181 1182 // Set the count value for the unknown edge. There should be one and only one 1183 // unknown edge in Edges vector. 1184 void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) { 1185 for (auto &E : Edges) { 1186 if (E->CountValid) 1187 continue; 1188 E->setEdgeCount(Value); 1189 1190 getBBInfo(E->SrcBB).UnknownCountOutEdge--; 1191 getBBInfo(E->DestBB).UnknownCountInEdge--; 1192 return; 1193 } 1194 llvm_unreachable("Cannot find the unknown count edge"); 1195 } 1196 1197 // Emit function metadata indicating PGO profile mismatch. 1198 static void annotateFunctionWithHashMismatch(Function &F, 1199 LLVMContext &ctx) { 1200 const char MetadataName[] = "instr_prof_hash_mismatch"; 1201 SmallVector<Metadata *, 2> Names; 1202 // If this metadata already exists, ignore. 1203 auto *Existing = F.getMetadata(LLVMContext::MD_annotation); 1204 if (Existing) { 1205 MDTuple *Tuple = cast<MDTuple>(Existing); 1206 for (auto &N : Tuple->operands()) { 1207 if (cast<MDString>(N.get())->getString() == MetadataName) 1208 return; 1209 Names.push_back(N.get()); 1210 } 1211 } 1212 1213 MDBuilder MDB(ctx); 1214 Names.push_back(MDB.createString(MetadataName)); 1215 MDNode *MD = MDTuple::get(ctx, Names); 1216 F.setMetadata(LLVMContext::MD_annotation, MD); 1217 } 1218 1219 // Read the profile from ProfileFileName and assign the value to the 1220 // instrumented BB and the edges. This function also updates ProgramMaxCount. 1221 // Return true if the profile are successfully read, and false on errors. 1222 bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros, 1223 bool &AllMinusOnes) { 1224 auto &Ctx = M->getContext(); 1225 uint64_t MismatchedFuncSum = 0; 1226 Expected<InstrProfRecord> Result = PGOReader->getInstrProfRecord( 1227 FuncInfo.FuncName, FuncInfo.FunctionHash, &MismatchedFuncSum); 1228 if (Error E = Result.takeError()) { 1229 handleAllErrors(std::move(E), [&](const InstrProfError &IPE) { 1230 auto Err = IPE.get(); 1231 bool SkipWarning = false; 1232 LLVM_DEBUG(dbgs() << "Error in reading profile for Func " 1233 << FuncInfo.FuncName << ": "); 1234 if (Err == instrprof_error::unknown_function) { 1235 IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++; 1236 SkipWarning = !PGOWarnMissing; 1237 LLVM_DEBUG(dbgs() << "unknown function"); 1238 } else if (Err == instrprof_error::hash_mismatch || 1239 Err == instrprof_error::malformed) { 1240 IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++; 1241 SkipWarning = 1242 NoPGOWarnMismatch || 1243 (NoPGOWarnMismatchComdatWeak && 1244 (F.hasComdat() || F.getLinkage() == GlobalValue::WeakAnyLinkage || 1245 F.getLinkage() == GlobalValue::AvailableExternallyLinkage)); 1246 LLVM_DEBUG(dbgs() << "hash mismatch (hash= " << FuncInfo.FunctionHash 1247 << " skip=" << SkipWarning << ")"); 1248 // Emit function metadata indicating PGO profile mismatch. 1249 annotateFunctionWithHashMismatch(F, M->getContext()); 1250 } 1251 1252 LLVM_DEBUG(dbgs() << " IsCS=" << IsCS << "\n"); 1253 if (SkipWarning) 1254 return; 1255 1256 std::string Msg = 1257 IPE.message() + std::string(" ") + F.getName().str() + 1258 std::string(" Hash = ") + std::to_string(FuncInfo.FunctionHash) + 1259 std::string(" up to ") + std::to_string(MismatchedFuncSum) + 1260 std::string(" count discarded"); 1261 1262 Ctx.diagnose( 1263 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); 1264 }); 1265 return false; 1266 } 1267 ProfileRecord = std::move(Result.get()); 1268 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts; 1269 1270 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++; 1271 LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n"); 1272 AllMinusOnes = (CountFromProfile.size() > 0); 1273 uint64_t ValueSum = 0; 1274 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) { 1275 LLVM_DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n"); 1276 ValueSum += CountFromProfile[I]; 1277 if (CountFromProfile[I] != (uint64_t)-1) 1278 AllMinusOnes = false; 1279 } 1280 AllZeros = (ValueSum == 0); 1281 1282 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n"); 1283 1284 getBBInfo(nullptr).UnknownCountOutEdge = 2; 1285 getBBInfo(nullptr).UnknownCountInEdge = 2; 1286 1287 if (!setInstrumentedCounts(CountFromProfile)) { 1288 LLVM_DEBUG( 1289 dbgs() << "Inconsistent number of counts, skipping this function"); 1290 Ctx.diagnose(DiagnosticInfoPGOProfile( 1291 M->getName().data(), 1292 Twine("Inconsistent number of counts in ") + F.getName().str() 1293 + Twine(": the profile may be stale or there is a function name collision."), 1294 DS_Warning)); 1295 return false; 1296 } 1297 ProgramMaxCount = PGOReader->getMaximumFunctionCount(IsCS); 1298 return true; 1299 } 1300 1301 // Populate the counters from instrumented BBs to all BBs. 1302 // In the end of this operation, all BBs should have a valid count value. 1303 void PGOUseFunc::populateCounters() { 1304 bool Changes = true; 1305 unsigned NumPasses = 0; 1306 while (Changes) { 1307 NumPasses++; 1308 Changes = false; 1309 1310 // For efficient traversal, it's better to start from the end as most 1311 // of the instrumented edges are at the end. 1312 for (auto &BB : reverse(F)) { 1313 UseBBInfo *Count = findBBInfo(&BB); 1314 if (Count == nullptr) 1315 continue; 1316 if (!Count->CountValid) { 1317 if (Count->UnknownCountOutEdge == 0) { 1318 Count->CountValue = sumEdgeCount(Count->OutEdges); 1319 Count->CountValid = true; 1320 Changes = true; 1321 } else if (Count->UnknownCountInEdge == 0) { 1322 Count->CountValue = sumEdgeCount(Count->InEdges); 1323 Count->CountValid = true; 1324 Changes = true; 1325 } 1326 } 1327 if (Count->CountValid) { 1328 if (Count->UnknownCountOutEdge == 1) { 1329 uint64_t Total = 0; 1330 uint64_t OutSum = sumEdgeCount(Count->OutEdges); 1331 // If the one of the successor block can early terminate (no-return), 1332 // we can end up with situation where out edge sum count is larger as 1333 // the source BB's count is collected by a post-dominated block. 1334 if (Count->CountValue > OutSum) 1335 Total = Count->CountValue - OutSum; 1336 setEdgeCount(Count->OutEdges, Total); 1337 Changes = true; 1338 } 1339 if (Count->UnknownCountInEdge == 1) { 1340 uint64_t Total = 0; 1341 uint64_t InSum = sumEdgeCount(Count->InEdges); 1342 if (Count->CountValue > InSum) 1343 Total = Count->CountValue - InSum; 1344 setEdgeCount(Count->InEdges, Total); 1345 Changes = true; 1346 } 1347 } 1348 } 1349 } 1350 1351 LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n"); 1352 (void) NumPasses; 1353 #ifndef NDEBUG 1354 // Assert every BB has a valid counter. 1355 for (auto &BB : F) { 1356 auto BI = findBBInfo(&BB); 1357 if (BI == nullptr) 1358 continue; 1359 assert(BI->CountValid && "BB count is not valid"); 1360 } 1361 #endif 1362 uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue; 1363 uint64_t FuncMaxCount = FuncEntryCount; 1364 for (auto &BB : F) { 1365 auto BI = findBBInfo(&BB); 1366 if (BI == nullptr) 1367 continue; 1368 FuncMaxCount = std::max(FuncMaxCount, BI->CountValue); 1369 } 1370 1371 // Fix the obviously inconsistent entry count. 1372 if (FuncMaxCount > 0 && FuncEntryCount == 0) 1373 FuncEntryCount = 1; 1374 F.setEntryCount(ProfileCount(FuncEntryCount, Function::PCT_Real)); 1375 markFunctionAttributes(FuncEntryCount, FuncMaxCount); 1376 1377 // Now annotate select instructions 1378 FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition); 1379 assert(CountPosition == ProfileCountSize); 1380 1381 LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile.")); 1382 } 1383 1384 // Assign the scaled count values to the BB with multiple out edges. 1385 void PGOUseFunc::setBranchWeights() { 1386 // Generate MD_prof metadata for every branch instruction. 1387 LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F.getName() 1388 << " IsCS=" << IsCS << "\n"); 1389 for (auto &BB : F) { 1390 Instruction *TI = BB.getTerminator(); 1391 if (TI->getNumSuccessors() < 2) 1392 continue; 1393 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || 1394 isa<IndirectBrInst>(TI) || isa<InvokeInst>(TI))) 1395 continue; 1396 1397 if (getBBInfo(&BB).CountValue == 0) 1398 continue; 1399 1400 // We have a non-zero Branch BB. 1401 const UseBBInfo &BBCountInfo = getBBInfo(&BB); 1402 unsigned Size = BBCountInfo.OutEdges.size(); 1403 SmallVector<uint64_t, 2> EdgeCounts(Size, 0); 1404 uint64_t MaxCount = 0; 1405 for (unsigned s = 0; s < Size; s++) { 1406 const PGOUseEdge *E = BBCountInfo.OutEdges[s]; 1407 const BasicBlock *SrcBB = E->SrcBB; 1408 const BasicBlock *DestBB = E->DestBB; 1409 if (DestBB == nullptr) 1410 continue; 1411 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); 1412 uint64_t EdgeCount = E->CountValue; 1413 if (EdgeCount > MaxCount) 1414 MaxCount = EdgeCount; 1415 EdgeCounts[SuccNum] = EdgeCount; 1416 } 1417 setProfMetadata(M, TI, EdgeCounts, MaxCount); 1418 } 1419 } 1420 1421 static bool isIndirectBrTarget(BasicBlock *BB) { 1422 for (BasicBlock *Pred : predecessors(BB)) { 1423 if (isa<IndirectBrInst>(Pred->getTerminator())) 1424 return true; 1425 } 1426 return false; 1427 } 1428 1429 void PGOUseFunc::annotateIrrLoopHeaderWeights() { 1430 LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n"); 1431 // Find irr loop headers 1432 for (auto &BB : F) { 1433 // As a heuristic also annotate indrectbr targets as they have a high chance 1434 // to become an irreducible loop header after the indirectbr tail 1435 // duplication. 1436 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) { 1437 Instruction *TI = BB.getTerminator(); 1438 const UseBBInfo &BBCountInfo = getBBInfo(&BB); 1439 setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue); 1440 } 1441 } 1442 } 1443 1444 void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) { 1445 if (PGOFunctionEntryCoverage) 1446 return; 1447 Module *M = F.getParent(); 1448 IRBuilder<> Builder(&SI); 1449 Type *Int64Ty = Builder.getInt64Ty(); 1450 Type *I8PtrTy = Builder.getInt8PtrTy(); 1451 auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty); 1452 Builder.CreateCall( 1453 Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step), 1454 {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy), 1455 Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs), 1456 Builder.getInt32(*CurCtrIdx), Step}); 1457 ++(*CurCtrIdx); 1458 } 1459 1460 void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) { 1461 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts; 1462 assert(*CurCtrIdx < CountFromProfile.size() && 1463 "Out of bound access of counters"); 1464 uint64_t SCounts[2]; 1465 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count 1466 ++(*CurCtrIdx); 1467 uint64_t TotalCount = 0; 1468 auto BI = UseFunc->findBBInfo(SI.getParent()); 1469 if (BI != nullptr) 1470 TotalCount = BI->CountValue; 1471 // False Count 1472 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0); 1473 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]); 1474 if (MaxCount) 1475 setProfMetadata(F.getParent(), &SI, SCounts, MaxCount); 1476 } 1477 1478 void SelectInstVisitor::visitSelectInst(SelectInst &SI) { 1479 if (!PGOInstrSelect) 1480 return; 1481 // FIXME: do not handle this yet. 1482 if (SI.getCondition()->getType()->isVectorTy()) 1483 return; 1484 1485 switch (Mode) { 1486 case VM_counting: 1487 NSIs++; 1488 return; 1489 case VM_instrument: 1490 instrumentOneSelectInst(SI); 1491 return; 1492 case VM_annotate: 1493 annotateOneSelectInst(SI); 1494 return; 1495 } 1496 1497 llvm_unreachable("Unknown visiting mode"); 1498 } 1499 1500 // Traverse all valuesites and annotate the instructions for all value kind. 1501 void PGOUseFunc::annotateValueSites() { 1502 if (DisableValueProfiling) 1503 return; 1504 1505 // Create the PGOFuncName meta data. 1506 createPGOFuncNameMetadata(F, FuncInfo.FuncName); 1507 1508 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) 1509 annotateValueSites(Kind); 1510 } 1511 1512 // Annotate the instructions for a specific value kind. 1513 void PGOUseFunc::annotateValueSites(uint32_t Kind) { 1514 assert(Kind <= IPVK_Last); 1515 unsigned ValueSiteIndex = 0; 1516 auto &ValueSites = FuncInfo.ValueSites[Kind]; 1517 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind); 1518 if (NumValueSites != ValueSites.size()) { 1519 auto &Ctx = M->getContext(); 1520 Ctx.diagnose(DiagnosticInfoPGOProfile( 1521 M->getName().data(), 1522 Twine("Inconsistent number of value sites for ") + 1523 Twine(ValueProfKindDescr[Kind]) + 1524 Twine(" profiling in \"") + F.getName().str() + 1525 Twine("\", possibly due to the use of a stale profile."), 1526 DS_Warning)); 1527 return; 1528 } 1529 1530 for (VPCandidateInfo &I : ValueSites) { 1531 LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind 1532 << "): Index = " << ValueSiteIndex << " out of " 1533 << NumValueSites << "\n"); 1534 annotateValueSite(*M, *I.AnnotatedInst, ProfileRecord, 1535 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex, 1536 Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations 1537 : MaxNumAnnotations); 1538 ValueSiteIndex++; 1539 } 1540 } 1541 1542 // Collect the set of members for each Comdat in module M and store 1543 // in ComdatMembers. 1544 static void collectComdatMembers( 1545 Module &M, 1546 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { 1547 if (!DoComdatRenaming) 1548 return; 1549 for (Function &F : M) 1550 if (Comdat *C = F.getComdat()) 1551 ComdatMembers.insert(std::make_pair(C, &F)); 1552 for (GlobalVariable &GV : M.globals()) 1553 if (Comdat *C = GV.getComdat()) 1554 ComdatMembers.insert(std::make_pair(C, &GV)); 1555 for (GlobalAlias &GA : M.aliases()) 1556 if (Comdat *C = GA.getComdat()) 1557 ComdatMembers.insert(std::make_pair(C, &GA)); 1558 } 1559 1560 static bool InstrumentAllFunctions( 1561 Module &M, function_ref<TargetLibraryInfo &(Function &)> LookupTLI, 1562 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, 1563 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS) { 1564 // For the context-sensitve instrumentation, we should have a separated pass 1565 // (before LTO/ThinLTO linking) to create these variables. 1566 if (!IsCS) 1567 createIRLevelProfileFlagVar(M, /*IsCS=*/false); 1568 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; 1569 collectComdatMembers(M, ComdatMembers); 1570 1571 for (auto &F : M) { 1572 if (F.isDeclaration()) 1573 continue; 1574 if (F.hasFnAttribute(llvm::Attribute::NoProfile)) 1575 continue; 1576 auto &TLI = LookupTLI(F); 1577 auto *BPI = LookupBPI(F); 1578 auto *BFI = LookupBFI(F); 1579 instrumentOneFunc(F, &M, TLI, BPI, BFI, ComdatMembers, IsCS); 1580 } 1581 return true; 1582 } 1583 1584 PreservedAnalyses 1585 PGOInstrumentationGenCreateVar::run(Module &M, ModuleAnalysisManager &AM) { 1586 createProfileFileNameVar(M, CSInstrName); 1587 // The variable in a comdat may be discarded by LTO. Ensure the declaration 1588 // will be retained. 1589 appendToCompilerUsed(M, createIRLevelProfileFlagVar(M, /*IsCS=*/true)); 1590 return PreservedAnalyses::all(); 1591 } 1592 1593 PreservedAnalyses PGOInstrumentationGen::run(Module &M, 1594 ModuleAnalysisManager &AM) { 1595 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1596 auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & { 1597 return FAM.getResult<TargetLibraryAnalysis>(F); 1598 }; 1599 auto LookupBPI = [&FAM](Function &F) { 1600 return &FAM.getResult<BranchProbabilityAnalysis>(F); 1601 }; 1602 auto LookupBFI = [&FAM](Function &F) { 1603 return &FAM.getResult<BlockFrequencyAnalysis>(F); 1604 }; 1605 1606 if (!InstrumentAllFunctions(M, LookupTLI, LookupBPI, LookupBFI, IsCS)) 1607 return PreservedAnalyses::all(); 1608 1609 return PreservedAnalyses::none(); 1610 } 1611 1612 // Using the ratio b/w sums of profile count values and BFI count values to 1613 // adjust the func entry count. 1614 static void fixFuncEntryCount(PGOUseFunc &Func, LoopInfo &LI, 1615 BranchProbabilityInfo &NBPI) { 1616 Function &F = Func.getFunc(); 1617 BlockFrequencyInfo NBFI(F, NBPI, LI); 1618 #ifndef NDEBUG 1619 auto BFIEntryCount = F.getEntryCount(); 1620 assert(BFIEntryCount && (BFIEntryCount->getCount() > 0) && 1621 "Invalid BFI Entrycount"); 1622 #endif 1623 auto SumCount = APFloat::getZero(APFloat::IEEEdouble()); 1624 auto SumBFICount = APFloat::getZero(APFloat::IEEEdouble()); 1625 for (auto &BBI : F) { 1626 uint64_t CountValue = 0; 1627 uint64_t BFICountValue = 0; 1628 if (!Func.findBBInfo(&BBI)) 1629 continue; 1630 auto BFICount = NBFI.getBlockProfileCount(&BBI); 1631 CountValue = Func.getBBInfo(&BBI).CountValue; 1632 BFICountValue = *BFICount; 1633 SumCount.add(APFloat(CountValue * 1.0), APFloat::rmNearestTiesToEven); 1634 SumBFICount.add(APFloat(BFICountValue * 1.0), APFloat::rmNearestTiesToEven); 1635 } 1636 if (SumCount.isZero()) 1637 return; 1638 1639 assert(SumBFICount.compare(APFloat(0.0)) == APFloat::cmpGreaterThan && 1640 "Incorrect sum of BFI counts"); 1641 if (SumBFICount.compare(SumCount) == APFloat::cmpEqual) 1642 return; 1643 double Scale = (SumCount / SumBFICount).convertToDouble(); 1644 if (Scale < 1.001 && Scale > 0.999) 1645 return; 1646 1647 uint64_t FuncEntryCount = Func.getBBInfo(&*F.begin()).CountValue; 1648 uint64_t NewEntryCount = 0.5 + FuncEntryCount * Scale; 1649 if (NewEntryCount == 0) 1650 NewEntryCount = 1; 1651 if (NewEntryCount != FuncEntryCount) { 1652 F.setEntryCount(ProfileCount(NewEntryCount, Function::PCT_Real)); 1653 LLVM_DEBUG(dbgs() << "FixFuncEntryCount: in " << F.getName() 1654 << ", entry_count " << FuncEntryCount << " --> " 1655 << NewEntryCount << "\n"); 1656 } 1657 } 1658 1659 // Compare the profile count values with BFI count values, and print out 1660 // the non-matching ones. 1661 static void verifyFuncBFI(PGOUseFunc &Func, LoopInfo &LI, 1662 BranchProbabilityInfo &NBPI, 1663 uint64_t HotCountThreshold, 1664 uint64_t ColdCountThreshold) { 1665 Function &F = Func.getFunc(); 1666 BlockFrequencyInfo NBFI(F, NBPI, LI); 1667 // bool PrintFunc = false; 1668 bool HotBBOnly = PGOVerifyHotBFI; 1669 std::string Msg; 1670 OptimizationRemarkEmitter ORE(&F); 1671 1672 unsigned BBNum = 0, BBMisMatchNum = 0, NonZeroBBNum = 0; 1673 for (auto &BBI : F) { 1674 uint64_t CountValue = 0; 1675 uint64_t BFICountValue = 0; 1676 1677 if (Func.getBBInfo(&BBI).CountValid) 1678 CountValue = Func.getBBInfo(&BBI).CountValue; 1679 1680 BBNum++; 1681 if (CountValue) 1682 NonZeroBBNum++; 1683 auto BFICount = NBFI.getBlockProfileCount(&BBI); 1684 if (BFICount) 1685 BFICountValue = *BFICount; 1686 1687 if (HotBBOnly) { 1688 bool rawIsHot = CountValue >= HotCountThreshold; 1689 bool BFIIsHot = BFICountValue >= HotCountThreshold; 1690 bool rawIsCold = CountValue <= ColdCountThreshold; 1691 bool ShowCount = false; 1692 if (rawIsHot && !BFIIsHot) { 1693 Msg = "raw-Hot to BFI-nonHot"; 1694 ShowCount = true; 1695 } else if (rawIsCold && BFIIsHot) { 1696 Msg = "raw-Cold to BFI-Hot"; 1697 ShowCount = true; 1698 } 1699 if (!ShowCount) 1700 continue; 1701 } else { 1702 if ((CountValue < PGOVerifyBFICutoff) && 1703 (BFICountValue < PGOVerifyBFICutoff)) 1704 continue; 1705 uint64_t Diff = (BFICountValue >= CountValue) 1706 ? BFICountValue - CountValue 1707 : CountValue - BFICountValue; 1708 if (Diff <= CountValue / 100 * PGOVerifyBFIRatio) 1709 continue; 1710 } 1711 BBMisMatchNum++; 1712 1713 ORE.emit([&]() { 1714 OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "bfi-verify", 1715 F.getSubprogram(), &BBI); 1716 Remark << "BB " << ore::NV("Block", BBI.getName()) 1717 << " Count=" << ore::NV("Count", CountValue) 1718 << " BFI_Count=" << ore::NV("Count", BFICountValue); 1719 if (!Msg.empty()) 1720 Remark << " (" << Msg << ")"; 1721 return Remark; 1722 }); 1723 } 1724 if (BBMisMatchNum) 1725 ORE.emit([&]() { 1726 return OptimizationRemarkAnalysis(DEBUG_TYPE, "bfi-verify", 1727 F.getSubprogram(), &F.getEntryBlock()) 1728 << "In Func " << ore::NV("Function", F.getName()) 1729 << ": Num_of_BB=" << ore::NV("Count", BBNum) 1730 << ", Num_of_non_zerovalue_BB=" << ore::NV("Count", NonZeroBBNum) 1731 << ", Num_of_mis_matching_BB=" << ore::NV("Count", BBMisMatchNum); 1732 }); 1733 } 1734 1735 static bool annotateAllFunctions( 1736 Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName, 1737 function_ref<TargetLibraryInfo &(Function &)> LookupTLI, 1738 function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, 1739 function_ref<BlockFrequencyInfo *(Function &)> LookupBFI, 1740 ProfileSummaryInfo *PSI, bool IsCS) { 1741 LLVM_DEBUG(dbgs() << "Read in profile counters: "); 1742 auto &Ctx = M.getContext(); 1743 // Read the counter array from file. 1744 auto ReaderOrErr = 1745 IndexedInstrProfReader::create(ProfileFileName, ProfileRemappingFileName); 1746 if (Error E = ReaderOrErr.takeError()) { 1747 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { 1748 Ctx.diagnose( 1749 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message())); 1750 }); 1751 return false; 1752 } 1753 1754 std::unique_ptr<IndexedInstrProfReader> PGOReader = 1755 std::move(ReaderOrErr.get()); 1756 if (!PGOReader) { 1757 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(), 1758 StringRef("Cannot get PGOReader"))); 1759 return false; 1760 } 1761 if (!PGOReader->hasCSIRLevelProfile() && IsCS) 1762 return false; 1763 1764 // TODO: might need to change the warning once the clang option is finalized. 1765 if (!PGOReader->isIRLevelProfile()) { 1766 Ctx.diagnose(DiagnosticInfoPGOProfile( 1767 ProfileFileName.data(), "Not an IR level instrumentation profile")); 1768 return false; 1769 } 1770 if (PGOReader->hasSingleByteCoverage()) { 1771 Ctx.diagnose(DiagnosticInfoPGOProfile( 1772 ProfileFileName.data(), 1773 "Cannot use coverage profiles for optimization")); 1774 return false; 1775 } 1776 if (PGOReader->functionEntryOnly()) { 1777 Ctx.diagnose(DiagnosticInfoPGOProfile( 1778 ProfileFileName.data(), 1779 "Function entry profiles are not yet supported for optimization")); 1780 return false; 1781 } 1782 1783 // Add the profile summary (read from the header of the indexed summary) here 1784 // so that we can use it below when reading counters (which checks if the 1785 // function should be marked with a cold or inlinehint attribute). 1786 M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()), 1787 IsCS ? ProfileSummary::PSK_CSInstr 1788 : ProfileSummary::PSK_Instr); 1789 PSI->refresh(); 1790 1791 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; 1792 collectComdatMembers(M, ComdatMembers); 1793 std::vector<Function *> HotFunctions; 1794 std::vector<Function *> ColdFunctions; 1795 1796 // If the profile marked as always instrument the entry BB, do the 1797 // same. Note this can be overwritten by the internal option in CFGMST.h 1798 bool InstrumentFuncEntry = PGOReader->instrEntryBBEnabled(); 1799 if (PGOInstrumentEntry.getNumOccurrences() > 0) 1800 InstrumentFuncEntry = PGOInstrumentEntry; 1801 for (auto &F : M) { 1802 if (F.isDeclaration()) 1803 continue; 1804 auto &TLI = LookupTLI(F); 1805 auto *BPI = LookupBPI(F); 1806 auto *BFI = LookupBFI(F); 1807 // Split indirectbr critical edges here before computing the MST rather than 1808 // later in getInstrBB() to avoid invalidating it. 1809 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI, BFI); 1810 PGOUseFunc Func(F, &M, TLI, ComdatMembers, BPI, BFI, PSI, IsCS, 1811 InstrumentFuncEntry); 1812 // When AllMinusOnes is true, it means the profile for the function 1813 // is unrepresentative and this function is actually hot. Set the 1814 // entry count of the function to be multiple times of hot threshold 1815 // and drop all its internal counters. 1816 bool AllMinusOnes = false; 1817 bool AllZeros = false; 1818 if (!Func.readCounters(PGOReader.get(), AllZeros, AllMinusOnes)) 1819 continue; 1820 if (AllZeros) { 1821 F.setEntryCount(ProfileCount(0, Function::PCT_Real)); 1822 if (Func.getProgramMaxCount() != 0) 1823 ColdFunctions.push_back(&F); 1824 continue; 1825 } 1826 const unsigned MultiplyFactor = 3; 1827 if (AllMinusOnes) { 1828 uint64_t HotThreshold = PSI->getHotCountThreshold(); 1829 if (HotThreshold) 1830 F.setEntryCount( 1831 ProfileCount(HotThreshold * MultiplyFactor, Function::PCT_Real)); 1832 HotFunctions.push_back(&F); 1833 continue; 1834 } 1835 Func.populateCounters(); 1836 Func.setBranchWeights(); 1837 Func.annotateValueSites(); 1838 Func.annotateIrrLoopHeaderWeights(); 1839 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr(); 1840 if (FreqAttr == PGOUseFunc::FFA_Cold) 1841 ColdFunctions.push_back(&F); 1842 else if (FreqAttr == PGOUseFunc::FFA_Hot) 1843 HotFunctions.push_back(&F); 1844 if (PGOViewCounts != PGOVCT_None && 1845 (ViewBlockFreqFuncName.empty() || 1846 F.getName().equals(ViewBlockFreqFuncName))) { 1847 LoopInfo LI{DominatorTree(F)}; 1848 std::unique_ptr<BranchProbabilityInfo> NewBPI = 1849 std::make_unique<BranchProbabilityInfo>(F, LI); 1850 std::unique_ptr<BlockFrequencyInfo> NewBFI = 1851 std::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI); 1852 if (PGOViewCounts == PGOVCT_Graph) 1853 NewBFI->view(); 1854 else if (PGOViewCounts == PGOVCT_Text) { 1855 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n"; 1856 NewBFI->print(dbgs()); 1857 } 1858 } 1859 if (PGOViewRawCounts != PGOVCT_None && 1860 (ViewBlockFreqFuncName.empty() || 1861 F.getName().equals(ViewBlockFreqFuncName))) { 1862 if (PGOViewRawCounts == PGOVCT_Graph) 1863 if (ViewBlockFreqFuncName.empty()) 1864 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName()); 1865 else 1866 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName()); 1867 else if (PGOViewRawCounts == PGOVCT_Text) { 1868 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n"; 1869 Func.dumpInfo(); 1870 } 1871 } 1872 1873 if (PGOVerifyBFI || PGOVerifyHotBFI || PGOFixEntryCount) { 1874 LoopInfo LI{DominatorTree(F)}; 1875 BranchProbabilityInfo NBPI(F, LI); 1876 1877 // Fix func entry count. 1878 if (PGOFixEntryCount) 1879 fixFuncEntryCount(Func, LI, NBPI); 1880 1881 // Verify BlockFrequency information. 1882 uint64_t HotCountThreshold = 0, ColdCountThreshold = 0; 1883 if (PGOVerifyHotBFI) { 1884 HotCountThreshold = PSI->getOrCompHotCountThreshold(); 1885 ColdCountThreshold = PSI->getOrCompColdCountThreshold(); 1886 } 1887 verifyFuncBFI(Func, LI, NBPI, HotCountThreshold, ColdCountThreshold); 1888 } 1889 } 1890 1891 // Set function hotness attribute from the profile. 1892 // We have to apply these attributes at the end because their presence 1893 // can affect the BranchProbabilityInfo of any callers, resulting in an 1894 // inconsistent MST between prof-gen and prof-use. 1895 for (auto &F : HotFunctions) { 1896 F->addFnAttr(Attribute::InlineHint); 1897 LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName() 1898 << "\n"); 1899 } 1900 for (auto &F : ColdFunctions) { 1901 // Only set when there is no Attribute::Hot set by the user. For Hot 1902 // attribute, user's annotation has the precedence over the profile. 1903 if (F->hasFnAttribute(Attribute::Hot)) { 1904 auto &Ctx = M.getContext(); 1905 std::string Msg = std::string("Function ") + F->getName().str() + 1906 std::string(" is annotated as a hot function but" 1907 " the profile is cold"); 1908 Ctx.diagnose( 1909 DiagnosticInfoPGOProfile(M.getName().data(), Msg, DS_Warning)); 1910 continue; 1911 } 1912 F->addFnAttr(Attribute::Cold); 1913 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() 1914 << "\n"); 1915 } 1916 return true; 1917 } 1918 1919 PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename, 1920 std::string RemappingFilename, 1921 bool IsCS) 1922 : ProfileFileName(std::move(Filename)), 1923 ProfileRemappingFileName(std::move(RemappingFilename)), IsCS(IsCS) { 1924 if (!PGOTestProfileFile.empty()) 1925 ProfileFileName = PGOTestProfileFile; 1926 if (!PGOTestProfileRemappingFile.empty()) 1927 ProfileRemappingFileName = PGOTestProfileRemappingFile; 1928 } 1929 1930 PreservedAnalyses PGOInstrumentationUse::run(Module &M, 1931 ModuleAnalysisManager &AM) { 1932 1933 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1934 auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & { 1935 return FAM.getResult<TargetLibraryAnalysis>(F); 1936 }; 1937 auto LookupBPI = [&FAM](Function &F) { 1938 return &FAM.getResult<BranchProbabilityAnalysis>(F); 1939 }; 1940 auto LookupBFI = [&FAM](Function &F) { 1941 return &FAM.getResult<BlockFrequencyAnalysis>(F); 1942 }; 1943 1944 auto *PSI = &AM.getResult<ProfileSummaryAnalysis>(M); 1945 1946 if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName, 1947 LookupTLI, LookupBPI, LookupBFI, PSI, IsCS)) 1948 return PreservedAnalyses::all(); 1949 1950 return PreservedAnalyses::none(); 1951 } 1952 1953 static std::string getSimpleNodeName(const BasicBlock *Node) { 1954 if (!Node->getName().empty()) 1955 return std::string(Node->getName()); 1956 1957 std::string SimpleNodeName; 1958 raw_string_ostream OS(SimpleNodeName); 1959 Node->printAsOperand(OS, false); 1960 return OS.str(); 1961 } 1962 1963 void llvm::setProfMetadata(Module *M, Instruction *TI, 1964 ArrayRef<uint64_t> EdgeCounts, 1965 uint64_t MaxCount) { 1966 MDBuilder MDB(M->getContext()); 1967 assert(MaxCount > 0 && "Bad max count"); 1968 uint64_t Scale = calculateCountScale(MaxCount); 1969 SmallVector<unsigned, 4> Weights; 1970 for (const auto &ECI : EdgeCounts) 1971 Weights.push_back(scaleBranchCount(ECI, Scale)); 1972 1973 LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W 1974 : Weights) { 1975 dbgs() << W << " "; 1976 } dbgs() << "\n";); 1977 1978 misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false); 1979 1980 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); 1981 if (EmitBranchProbability) { 1982 std::string BrCondStr = getBranchCondString(TI); 1983 if (BrCondStr.empty()) 1984 return; 1985 1986 uint64_t WSum = 1987 std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0, 1988 [](uint64_t w1, uint64_t w2) { return w1 + w2; }); 1989 uint64_t TotalCount = 1990 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0, 1991 [](uint64_t c1, uint64_t c2) { return c1 + c2; }); 1992 Scale = calculateCountScale(WSum); 1993 BranchProbability BP(scaleBranchCount(Weights[0], Scale), 1994 scaleBranchCount(WSum, Scale)); 1995 std::string BranchProbStr; 1996 raw_string_ostream OS(BranchProbStr); 1997 OS << BP; 1998 OS << " (total count : " << TotalCount << ")"; 1999 OS.flush(); 2000 Function *F = TI->getParent()->getParent(); 2001 OptimizationRemarkEmitter ORE(F); 2002 ORE.emit([&]() { 2003 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI) 2004 << BrCondStr << " is true with probability : " << BranchProbStr; 2005 }); 2006 } 2007 } 2008 2009 namespace llvm { 2010 2011 void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) { 2012 MDBuilder MDB(M->getContext()); 2013 TI->setMetadata(llvm::LLVMContext::MD_irr_loop, 2014 MDB.createIrrLoopHeaderWeight(Count)); 2015 } 2016 2017 template <> struct GraphTraits<PGOUseFunc *> { 2018 using NodeRef = const BasicBlock *; 2019 using ChildIteratorType = const_succ_iterator; 2020 using nodes_iterator = pointer_iterator<Function::const_iterator>; 2021 2022 static NodeRef getEntryNode(const PGOUseFunc *G) { 2023 return &G->getFunc().front(); 2024 } 2025 2026 static ChildIteratorType child_begin(const NodeRef N) { 2027 return succ_begin(N); 2028 } 2029 2030 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); } 2031 2032 static nodes_iterator nodes_begin(const PGOUseFunc *G) { 2033 return nodes_iterator(G->getFunc().begin()); 2034 } 2035 2036 static nodes_iterator nodes_end(const PGOUseFunc *G) { 2037 return nodes_iterator(G->getFunc().end()); 2038 } 2039 }; 2040 2041 template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits { 2042 explicit DOTGraphTraits(bool isSimple = false) 2043 : DefaultDOTGraphTraits(isSimple) {} 2044 2045 static std::string getGraphName(const PGOUseFunc *G) { 2046 return std::string(G->getFunc().getName()); 2047 } 2048 2049 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) { 2050 std::string Result; 2051 raw_string_ostream OS(Result); 2052 2053 OS << getSimpleNodeName(Node) << ":\\l"; 2054 UseBBInfo *BI = Graph->findBBInfo(Node); 2055 OS << "Count : "; 2056 if (BI && BI->CountValid) 2057 OS << BI->CountValue << "\\l"; 2058 else 2059 OS << "Unknown\\l"; 2060 2061 if (!PGOInstrSelect) 2062 return Result; 2063 2064 for (const Instruction &I : *Node) { 2065 if (!isa<SelectInst>(&I)) 2066 continue; 2067 // Display scaled counts for SELECT instruction: 2068 OS << "SELECT : { T = "; 2069 uint64_t TC, FC; 2070 bool HasProf = I.extractProfMetadata(TC, FC); 2071 if (!HasProf) 2072 OS << "Unknown, F = Unknown }\\l"; 2073 else 2074 OS << TC << ", F = " << FC << " }\\l"; 2075 } 2076 return Result; 2077 } 2078 }; 2079 2080 } // end namespace llvm 2081