1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===// 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 the SampleProfileLoader transformation. This pass 10 // reads a profile file generated by a sampling profiler (e.g. Linux Perf - 11 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the 12 // profile information in the given profile. 13 // 14 // This pass generates branch weight annotations on the IR: 15 // 16 // - prof: Represents branch weights. This annotation is added to branches 17 // to indicate the weights of each edge coming out of the branch. 18 // The weight of each edge is the weight of the target block for 19 // that edge. The weight of a block B is computed as the maximum 20 // number of samples found in B. 21 // 22 //===----------------------------------------------------------------------===// 23 24 #include "llvm/Transforms/IPO/SampleProfile.h" 25 #include "llvm/ADT/ArrayRef.h" 26 #include "llvm/ADT/DenseMap.h" 27 #include "llvm/ADT/DenseSet.h" 28 #include "llvm/ADT/None.h" 29 #include "llvm/ADT/PriorityQueue.h" 30 #include "llvm/ADT/SCCIterator.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringMap.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/Analysis/AssumptionCache.h" 39 #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 40 #include "llvm/Analysis/CallGraph.h" 41 #include "llvm/Analysis/CallGraphSCCPass.h" 42 #include "llvm/Analysis/InlineAdvisor.h" 43 #include "llvm/Analysis/InlineCost.h" 44 #include "llvm/Analysis/LoopInfo.h" 45 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 46 #include "llvm/Analysis/PostDominators.h" 47 #include "llvm/Analysis/ProfileSummaryInfo.h" 48 #include "llvm/Analysis/ReplayInlineAdvisor.h" 49 #include "llvm/Analysis/TargetLibraryInfo.h" 50 #include "llvm/Analysis/TargetTransformInfo.h" 51 #include "llvm/IR/BasicBlock.h" 52 #include "llvm/IR/CFG.h" 53 #include "llvm/IR/DebugInfoMetadata.h" 54 #include "llvm/IR/DebugLoc.h" 55 #include "llvm/IR/DiagnosticInfo.h" 56 #include "llvm/IR/Dominators.h" 57 #include "llvm/IR/Function.h" 58 #include "llvm/IR/GlobalValue.h" 59 #include "llvm/IR/InstrTypes.h" 60 #include "llvm/IR/Instruction.h" 61 #include "llvm/IR/Instructions.h" 62 #include "llvm/IR/IntrinsicInst.h" 63 #include "llvm/IR/LLVMContext.h" 64 #include "llvm/IR/MDBuilder.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/PassManager.h" 67 #include "llvm/IR/ValueSymbolTable.h" 68 #include "llvm/InitializePasses.h" 69 #include "llvm/Pass.h" 70 #include "llvm/ProfileData/InstrProf.h" 71 #include "llvm/ProfileData/SampleProf.h" 72 #include "llvm/ProfileData/SampleProfReader.h" 73 #include "llvm/Support/Casting.h" 74 #include "llvm/Support/CommandLine.h" 75 #include "llvm/Support/Debug.h" 76 #include "llvm/Support/ErrorHandling.h" 77 #include "llvm/Support/ErrorOr.h" 78 #include "llvm/Support/GenericDomTree.h" 79 #include "llvm/Support/raw_ostream.h" 80 #include "llvm/Transforms/IPO.h" 81 #include "llvm/Transforms/IPO/ProfiledCallGraph.h" 82 #include "llvm/Transforms/IPO/SampleContextTracker.h" 83 #include "llvm/Transforms/IPO/SampleProfileProbe.h" 84 #include "llvm/Transforms/Instrumentation.h" 85 #include "llvm/Transforms/Utils/CallPromotionUtils.h" 86 #include "llvm/Transforms/Utils/Cloning.h" 87 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h" 88 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstdint> 92 #include <functional> 93 #include <limits> 94 #include <map> 95 #include <memory> 96 #include <queue> 97 #include <string> 98 #include <system_error> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 using namespace sampleprof; 104 using namespace llvm::sampleprofutil; 105 using ProfileCount = Function::ProfileCount; 106 #define DEBUG_TYPE "sample-profile" 107 #define CSINLINE_DEBUG DEBUG_TYPE "-inline" 108 109 STATISTIC(NumCSInlined, 110 "Number of functions inlined with context sensitive profile"); 111 STATISTIC(NumCSNotInlined, 112 "Number of functions not inlined with context sensitive profile"); 113 STATISTIC(NumMismatchedProfile, 114 "Number of functions with CFG mismatched profile"); 115 STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile"); 116 STATISTIC(NumDuplicatedInlinesite, 117 "Number of inlined callsites with a partial distribution factor"); 118 119 STATISTIC(NumCSInlinedHitMinLimit, 120 "Number of functions with FDO inline stopped due to min size limit"); 121 STATISTIC(NumCSInlinedHitMaxLimit, 122 "Number of functions with FDO inline stopped due to max size limit"); 123 STATISTIC( 124 NumCSInlinedHitGrowthLimit, 125 "Number of functions with FDO inline stopped due to growth size limit"); 126 127 // Command line option to specify the file to read samples from. This is 128 // mainly used for debugging. 129 static cl::opt<std::string> SampleProfileFile( 130 "sample-profile-file", cl::init(""), cl::value_desc("filename"), 131 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden); 132 133 // The named file contains a set of transformations that may have been applied 134 // to the symbol names between the program from which the sample data was 135 // collected and the current program's symbols. 136 static cl::opt<std::string> SampleProfileRemappingFile( 137 "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"), 138 cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden); 139 140 static cl::opt<bool> ProfileSampleAccurate( 141 "profile-sample-accurate", cl::Hidden, cl::init(false), 142 cl::desc("If the sample profile is accurate, we will mark all un-sampled " 143 "callsite and function as having 0 samples. Otherwise, treat " 144 "un-sampled callsites and functions conservatively as unknown. ")); 145 146 static cl::opt<bool> ProfileAccurateForSymsInList( 147 "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore, 148 cl::init(true), 149 cl::desc("For symbols in profile symbol list, regard their profiles to " 150 "be accurate. It may be overriden by profile-sample-accurate. ")); 151 152 static cl::opt<bool> ProfileMergeInlinee( 153 "sample-profile-merge-inlinee", cl::Hidden, cl::init(true), 154 cl::desc("Merge past inlinee's profile to outline version if sample " 155 "profile loader decided not to inline a call site. It will " 156 "only be enabled when top-down order of profile loading is " 157 "enabled. ")); 158 159 static cl::opt<bool> ProfileTopDownLoad( 160 "sample-profile-top-down-load", cl::Hidden, cl::init(true), 161 cl::desc("Do profile annotation and inlining for functions in top-down " 162 "order of call graph during sample profile loading. It only " 163 "works for new pass manager. ")); 164 165 static cl::opt<bool> 166 UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden, 167 cl::desc("Process functions in a top-down order " 168 "defined by the profiled call graph when " 169 "-sample-profile-top-down-load is on.")); 170 171 static cl::opt<bool> ProfileSizeInline( 172 "sample-profile-inline-size", cl::Hidden, cl::init(false), 173 cl::desc("Inline cold call sites in profile loader if it's beneficial " 174 "for code size.")); 175 176 cl::opt<int> ProfileInlineGrowthLimit( 177 "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12), 178 cl::desc("The size growth ratio limit for proirity-based sample profile " 179 "loader inlining.")); 180 181 cl::opt<int> ProfileInlineLimitMin( 182 "sample-profile-inline-limit-min", cl::Hidden, cl::init(100), 183 cl::desc("The lower bound of size growth limit for " 184 "proirity-based sample profile loader inlining.")); 185 186 cl::opt<int> ProfileInlineLimitMax( 187 "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000), 188 cl::desc("The upper bound of size growth limit for " 189 "proirity-based sample profile loader inlining.")); 190 191 cl::opt<int> SampleHotCallSiteThreshold( 192 "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000), 193 cl::desc("Hot callsite threshold for proirity-based sample profile loader " 194 "inlining.")); 195 196 cl::opt<int> SampleColdCallSiteThreshold( 197 "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45), 198 cl::desc("Threshold for inlining cold callsites")); 199 200 static cl::opt<unsigned> ProfileICPRelativeHotness( 201 "sample-profile-icp-relative-hotness", cl::Hidden, cl::init(25), 202 cl::desc( 203 "Relative hotness percentage threshold for indirect " 204 "call promotion in proirity-based sample profile loader inlining.")); 205 206 static cl::opt<unsigned> ProfileICPRelativeHotnessSkip( 207 "sample-profile-icp-relative-hotness-skip", cl::Hidden, cl::init(1), 208 cl::desc( 209 "Skip relative hotness check for ICP up to given number of targets.")); 210 211 static cl::opt<bool> CallsitePrioritizedInline( 212 "sample-profile-prioritized-inline", cl::Hidden, cl::ZeroOrMore, 213 cl::init(false), 214 cl::desc("Use call site prioritized inlining for sample profile loader." 215 "Currently only CSSPGO is supported.")); 216 217 static cl::opt<bool> UsePreInlinerDecision( 218 "sample-profile-use-preinliner", cl::Hidden, cl::ZeroOrMore, 219 cl::init(false), 220 cl::desc("Use the preinliner decisions stored in profile context.")); 221 222 static cl::opt<std::string> ProfileInlineReplayFile( 223 "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"), 224 cl::desc( 225 "Optimization remarks file containing inline remarks to be replayed " 226 "by inlining from sample profile loader."), 227 cl::Hidden); 228 229 static cl::opt<unsigned> 230 MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden, 231 cl::ZeroOrMore, 232 cl::desc("Max number of promotions for a single indirect " 233 "call callsite in sample profile loader")); 234 235 static cl::opt<bool> OverwriteExistingWeights( 236 "overwrite-existing-weights", cl::Hidden, cl::init(false), 237 cl::desc("Ignore existing branch weights on IR and always overwrite.")); 238 239 namespace { 240 241 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>; 242 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>; 243 using Edge = std::pair<const BasicBlock *, const BasicBlock *>; 244 using EdgeWeightMap = DenseMap<Edge, uint64_t>; 245 using BlockEdgeMap = 246 DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>; 247 248 class GUIDToFuncNameMapper { 249 public: 250 GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader, 251 DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap) 252 : CurrentReader(Reader), CurrentModule(M), 253 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) { 254 if (!CurrentReader.useMD5()) 255 return; 256 257 for (const auto &F : CurrentModule) { 258 StringRef OrigName = F.getName(); 259 CurrentGUIDToFuncNameMap.insert( 260 {Function::getGUID(OrigName), OrigName}); 261 262 // Local to global var promotion used by optimization like thinlto 263 // will rename the var and add suffix like ".llvm.xxx" to the 264 // original local name. In sample profile, the suffixes of function 265 // names are all stripped. Since it is possible that the mapper is 266 // built in post-thin-link phase and var promotion has been done, 267 // we need to add the substring of function name without the suffix 268 // into the GUIDToFuncNameMap. 269 StringRef CanonName = FunctionSamples::getCanonicalFnName(F); 270 if (CanonName != OrigName) 271 CurrentGUIDToFuncNameMap.insert( 272 {Function::getGUID(CanonName), CanonName}); 273 } 274 275 // Update GUIDToFuncNameMap for each function including inlinees. 276 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap); 277 } 278 279 ~GUIDToFuncNameMapper() { 280 if (!CurrentReader.useMD5()) 281 return; 282 283 CurrentGUIDToFuncNameMap.clear(); 284 285 // Reset GUIDToFuncNameMap for of each function as they're no 286 // longer valid at this point. 287 SetGUIDToFuncNameMapForAll(nullptr); 288 } 289 290 private: 291 void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) { 292 std::queue<FunctionSamples *> FSToUpdate; 293 for (auto &IFS : CurrentReader.getProfiles()) { 294 FSToUpdate.push(&IFS.second); 295 } 296 297 while (!FSToUpdate.empty()) { 298 FunctionSamples *FS = FSToUpdate.front(); 299 FSToUpdate.pop(); 300 FS->GUIDToFuncNameMap = Map; 301 for (const auto &ICS : FS->getCallsiteSamples()) { 302 const FunctionSamplesMap &FSMap = ICS.second; 303 for (auto &IFS : FSMap) { 304 FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second); 305 FSToUpdate.push(&FS); 306 } 307 } 308 } 309 } 310 311 SampleProfileReader &CurrentReader; 312 Module &CurrentModule; 313 DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap; 314 }; 315 316 // Inline candidate used by iterative callsite prioritized inliner 317 struct InlineCandidate { 318 CallBase *CallInstr; 319 const FunctionSamples *CalleeSamples; 320 // Prorated callsite count, which will be used to guide inlining. For example, 321 // if a callsite is duplicated in LTO prelink, then in LTO postlink the two 322 // copies will get their own distribution factors and their prorated counts 323 // will be used to decide if they should be inlined independently. 324 uint64_t CallsiteCount; 325 // Call site distribution factor to prorate the profile samples for a 326 // duplicated callsite. Default value is 1.0. 327 float CallsiteDistribution; 328 }; 329 330 // Inline candidate comparer using call site weight 331 struct CandidateComparer { 332 bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) { 333 if (LHS.CallsiteCount != RHS.CallsiteCount) 334 return LHS.CallsiteCount < RHS.CallsiteCount; 335 336 const FunctionSamples *LCS = LHS.CalleeSamples; 337 const FunctionSamples *RCS = RHS.CalleeSamples; 338 assert(LCS && RCS && "Expect non-null FunctionSamples"); 339 340 // Tie breaker using number of samples try to favor smaller functions first 341 if (LCS->getBodySamples().size() != RCS->getBodySamples().size()) 342 return LCS->getBodySamples().size() > RCS->getBodySamples().size(); 343 344 // Tie breaker using GUID so we have stable/deterministic inlining order 345 return LCS->getGUID(LCS->getName()) < RCS->getGUID(RCS->getName()); 346 } 347 }; 348 349 using CandidateQueue = 350 PriorityQueue<InlineCandidate, std::vector<InlineCandidate>, 351 CandidateComparer>; 352 353 /// Sample profile pass. 354 /// 355 /// This pass reads profile data from the file specified by 356 /// -sample-profile-file and annotates every affected function with the 357 /// profile information found in that file. 358 class SampleProfileLoader final 359 : public SampleProfileLoaderBaseImpl<BasicBlock> { 360 public: 361 SampleProfileLoader( 362 StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase, 363 std::function<AssumptionCache &(Function &)> GetAssumptionCache, 364 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo, 365 std::function<const TargetLibraryInfo &(Function &)> GetTLI) 366 : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName)), 367 GetAC(std::move(GetAssumptionCache)), 368 GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)), 369 LTOPhase(LTOPhase) {} 370 371 bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr); 372 bool runOnModule(Module &M, ModuleAnalysisManager *AM, 373 ProfileSummaryInfo *_PSI, CallGraph *CG); 374 375 protected: 376 bool runOnFunction(Function &F, ModuleAnalysisManager *AM); 377 bool emitAnnotations(Function &F); 378 ErrorOr<uint64_t> getInstWeight(const Instruction &I) override; 379 ErrorOr<uint64_t> getProbeWeight(const Instruction &I); 380 const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const; 381 const FunctionSamples * 382 findFunctionSamples(const Instruction &I) const override; 383 std::vector<const FunctionSamples *> 384 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const; 385 void findExternalInlineCandidate(const FunctionSamples *Samples, 386 DenseSet<GlobalValue::GUID> &InlinedGUIDs, 387 const StringMap<Function *> &SymbolMap, 388 uint64_t Threshold); 389 // Attempt to promote indirect call and also inline the promoted call 390 bool tryPromoteAndInlineCandidate( 391 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, 392 uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr); 393 bool inlineHotFunctions(Function &F, 394 DenseSet<GlobalValue::GUID> &InlinedGUIDs); 395 InlineCost shouldInlineCandidate(InlineCandidate &Candidate); 396 bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB); 397 bool 398 tryInlineCandidate(InlineCandidate &Candidate, 399 SmallVector<CallBase *, 8> *InlinedCallSites = nullptr); 400 bool 401 inlineHotFunctionsWithPriority(Function &F, 402 DenseSet<GlobalValue::GUID> &InlinedGUIDs); 403 // Inline cold/small functions in addition to hot ones 404 bool shouldInlineColdCallee(CallBase &CallInst); 405 void emitOptimizationRemarksForInlineCandidates( 406 const SmallVectorImpl<CallBase *> &Candidates, const Function &F, 407 bool Hot); 408 std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG); 409 std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(CallGraph &CG); 410 void generateMDProfMetadata(Function &F); 411 412 /// Map from function name to Function *. Used to find the function from 413 /// the function name. If the function name contains suffix, additional 414 /// entry is added to map from the stripped name to the function if there 415 /// is one-to-one mapping. 416 StringMap<Function *> SymbolMap; 417 418 std::function<AssumptionCache &(Function &)> GetAC; 419 std::function<TargetTransformInfo &(Function &)> GetTTI; 420 std::function<const TargetLibraryInfo &(Function &)> GetTLI; 421 422 /// Profile tracker for different context. 423 std::unique_ptr<SampleContextTracker> ContextTracker; 424 425 /// Flag indicating whether input profile is context-sensitive 426 bool ProfileIsCS = false; 427 428 /// Flag indicating which LTO/ThinLTO phase the pass is invoked in. 429 /// 430 /// We need to know the LTO phase because for example in ThinLTOPrelink 431 /// phase, in annotation, we should not promote indirect calls. Instead, 432 /// we will mark GUIDs that needs to be annotated to the function. 433 ThinOrFullLTOPhase LTOPhase; 434 435 /// Profle Symbol list tells whether a function name appears in the binary 436 /// used to generate the current profile. 437 std::unique_ptr<ProfileSymbolList> PSL; 438 439 /// Total number of samples collected in this profile. 440 /// 441 /// This is the sum of all the samples collected in all the functions executed 442 /// at runtime. 443 uint64_t TotalCollectedSamples = 0; 444 445 // Information recorded when we declined to inline a call site 446 // because we have determined it is too cold is accumulated for 447 // each callee function. Initially this is just the entry count. 448 struct NotInlinedProfileInfo { 449 uint64_t entryCount; 450 }; 451 DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo; 452 453 // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for 454 // all the function symbols defined or declared in current module. 455 DenseMap<uint64_t, StringRef> GUIDToFuncNameMap; 456 457 // All the Names used in FunctionSamples including outline function 458 // names, inline instance names and call target names. 459 StringSet<> NamesInProfile; 460 461 // For symbol in profile symbol list, whether to regard their profiles 462 // to be accurate. It is mainly decided by existance of profile symbol 463 // list and -profile-accurate-for-symsinlist flag, but it can be 464 // overriden by -profile-sample-accurate or profile-sample-accurate 465 // attribute. 466 bool ProfAccForSymsInList; 467 468 // External inline advisor used to replay inline decision from remarks. 469 std::unique_ptr<ReplayInlineAdvisor> ExternalInlineAdvisor; 470 471 // A pseudo probe helper to correlate the imported sample counts. 472 std::unique_ptr<PseudoProbeManager> ProbeManager; 473 }; 474 475 class SampleProfileLoaderLegacyPass : public ModulePass { 476 public: 477 // Class identification, replacement for typeinfo 478 static char ID; 479 480 SampleProfileLoaderLegacyPass( 481 StringRef Name = SampleProfileFile, 482 ThinOrFullLTOPhase LTOPhase = ThinOrFullLTOPhase::None) 483 : ModulePass(ID), SampleLoader( 484 Name, SampleProfileRemappingFile, LTOPhase, 485 [&](Function &F) -> AssumptionCache & { 486 return ACT->getAssumptionCache(F); 487 }, 488 [&](Function &F) -> TargetTransformInfo & { 489 return TTIWP->getTTI(F); 490 }, 491 [&](Function &F) -> TargetLibraryInfo & { 492 return TLIWP->getTLI(F); 493 }) { 494 initializeSampleProfileLoaderLegacyPassPass( 495 *PassRegistry::getPassRegistry()); 496 } 497 498 void dump() { SampleLoader.dump(); } 499 500 bool doInitialization(Module &M) override { 501 return SampleLoader.doInitialization(M); 502 } 503 504 StringRef getPassName() const override { return "Sample profile pass"; } 505 bool runOnModule(Module &M) override; 506 507 void getAnalysisUsage(AnalysisUsage &AU) const override { 508 AU.addRequired<AssumptionCacheTracker>(); 509 AU.addRequired<TargetTransformInfoWrapperPass>(); 510 AU.addRequired<TargetLibraryInfoWrapperPass>(); 511 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 512 } 513 514 private: 515 SampleProfileLoader SampleLoader; 516 AssumptionCacheTracker *ACT = nullptr; 517 TargetTransformInfoWrapperPass *TTIWP = nullptr; 518 TargetLibraryInfoWrapperPass *TLIWP = nullptr; 519 }; 520 521 } // end anonymous namespace 522 523 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) { 524 if (FunctionSamples::ProfileIsProbeBased) 525 return getProbeWeight(Inst); 526 527 const DebugLoc &DLoc = Inst.getDebugLoc(); 528 if (!DLoc) 529 return std::error_code(); 530 531 // Ignore all intrinsics, phinodes and branch instructions. 532 // Branch and phinodes instruction usually contains debug info from sources 533 // outside of the residing basic block, thus we ignore them during annotation. 534 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst)) 535 return std::error_code(); 536 537 // For non-CS profile, if a direct call/invoke instruction is inlined in 538 // profile (findCalleeFunctionSamples returns non-empty result), but not 539 // inlined here, it means that the inlined callsite has no sample, thus the 540 // call instruction should have 0 count. 541 // For CS profile, the callsite count of previously inlined callees is 542 // populated with the entry count of the callees. 543 if (!ProfileIsCS) 544 if (const auto *CB = dyn_cast<CallBase>(&Inst)) 545 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB)) 546 return 0; 547 548 return getInstWeightImpl(Inst); 549 } 550 551 // Here use error_code to represent: 1) The dangling probe. 2) Ignore the weight 552 // of non-probe instruction. So if all instructions of the BB give error_code, 553 // tell the inference algorithm to infer the BB weight. 554 ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) { 555 assert(FunctionSamples::ProfileIsProbeBased && 556 "Profile is not pseudo probe based"); 557 Optional<PseudoProbe> Probe = extractProbe(Inst); 558 // Ignore the non-probe instruction. If none of the instruction in the BB is 559 // probe, we choose to infer the BB's weight. 560 if (!Probe) 561 return std::error_code(); 562 563 const FunctionSamples *FS = findFunctionSamples(Inst); 564 // If none of the instruction has FunctionSample, we choose to return zero 565 // value sample to indicate the BB is cold. This could happen when the 566 // instruction is from inlinee and no profile data is found. 567 // FIXME: This should not be affected by the source drift issue as 1) if the 568 // newly added function is top-level inliner, it won't match the CFG checksum 569 // in the function profile or 2) if it's the inlinee, the inlinee should have 570 // a profile, otherwise it wouldn't be inlined. For non-probe based profile, 571 // we can improve it by adding a switch for profile-sample-block-accurate for 572 // block level counts in the future. 573 if (!FS) 574 return 0; 575 576 // For non-CS profile, If a direct call/invoke instruction is inlined in 577 // profile (findCalleeFunctionSamples returns non-empty result), but not 578 // inlined here, it means that the inlined callsite has no sample, thus the 579 // call instruction should have 0 count. 580 // For CS profile, the callsite count of previously inlined callees is 581 // populated with the entry count of the callees. 582 if (!ProfileIsCS) 583 if (const auto *CB = dyn_cast<CallBase>(&Inst)) 584 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB)) 585 return 0; 586 587 const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0); 588 if (R) { 589 uint64_t Samples = R.get() * Probe->Factor; 590 bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples); 591 if (FirstMark) { 592 ORE->emit([&]() { 593 OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst); 594 Remark << "Applied " << ore::NV("NumSamples", Samples); 595 Remark << " samples from profile (ProbeId="; 596 Remark << ore::NV("ProbeId", Probe->Id); 597 Remark << ", Factor="; 598 Remark << ore::NV("Factor", Probe->Factor); 599 Remark << ", OriginalSamples="; 600 Remark << ore::NV("OriginalSamples", R.get()); 601 Remark << ")"; 602 return Remark; 603 }); 604 } 605 LLVM_DEBUG(dbgs() << " " << Probe->Id << ":" << Inst 606 << " - weight: " << R.get() << " - factor: " 607 << format("%0.2f", Probe->Factor) << ")\n"); 608 return Samples; 609 } 610 return R; 611 } 612 613 /// Get the FunctionSamples for a call instruction. 614 /// 615 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined 616 /// instance in which that call instruction is calling to. It contains 617 /// all samples that resides in the inlined instance. We first find the 618 /// inlined instance in which the call instruction is from, then we 619 /// traverse its children to find the callsite with the matching 620 /// location. 621 /// 622 /// \param Inst Call/Invoke instruction to query. 623 /// 624 /// \returns The FunctionSamples pointer to the inlined instance. 625 const FunctionSamples * 626 SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const { 627 const DILocation *DIL = Inst.getDebugLoc(); 628 if (!DIL) { 629 return nullptr; 630 } 631 632 StringRef CalleeName; 633 if (Function *Callee = Inst.getCalledFunction()) 634 CalleeName = Callee->getName(); 635 636 if (ProfileIsCS) 637 return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName); 638 639 const FunctionSamples *FS = findFunctionSamples(Inst); 640 if (FS == nullptr) 641 return nullptr; 642 643 return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL), 644 CalleeName, Reader->getRemapper()); 645 } 646 647 /// Returns a vector of FunctionSamples that are the indirect call targets 648 /// of \p Inst. The vector is sorted by the total number of samples. Stores 649 /// the total call count of the indirect call in \p Sum. 650 std::vector<const FunctionSamples *> 651 SampleProfileLoader::findIndirectCallFunctionSamples( 652 const Instruction &Inst, uint64_t &Sum) const { 653 const DILocation *DIL = Inst.getDebugLoc(); 654 std::vector<const FunctionSamples *> R; 655 656 if (!DIL) { 657 return R; 658 } 659 660 auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) { 661 assert(L && R && "Expect non-null FunctionSamples"); 662 if (L->getEntrySamples() != R->getEntrySamples()) 663 return L->getEntrySamples() > R->getEntrySamples(); 664 return FunctionSamples::getGUID(L->getName()) < 665 FunctionSamples::getGUID(R->getName()); 666 }; 667 668 if (ProfileIsCS) { 669 auto CalleeSamples = 670 ContextTracker->getIndirectCalleeContextSamplesFor(DIL); 671 if (CalleeSamples.empty()) 672 return R; 673 674 // For CSSPGO, we only use target context profile's entry count 675 // as that already includes both inlined callee and non-inlined ones.. 676 Sum = 0; 677 for (const auto *const FS : CalleeSamples) { 678 Sum += FS->getEntrySamples(); 679 R.push_back(FS); 680 } 681 llvm::sort(R, FSCompare); 682 return R; 683 } 684 685 const FunctionSamples *FS = findFunctionSamples(Inst); 686 if (FS == nullptr) 687 return R; 688 689 auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL); 690 auto T = FS->findCallTargetMapAt(CallSite); 691 Sum = 0; 692 if (T) 693 for (const auto &T_C : T.get()) 694 Sum += T_C.second; 695 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) { 696 if (M->empty()) 697 return R; 698 for (const auto &NameFS : *M) { 699 Sum += NameFS.second.getEntrySamples(); 700 R.push_back(&NameFS.second); 701 } 702 llvm::sort(R, FSCompare); 703 } 704 return R; 705 } 706 707 const FunctionSamples * 708 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const { 709 if (FunctionSamples::ProfileIsProbeBased) { 710 Optional<PseudoProbe> Probe = extractProbe(Inst); 711 if (!Probe) 712 return nullptr; 713 } 714 715 const DILocation *DIL = Inst.getDebugLoc(); 716 if (!DIL) 717 return Samples; 718 719 auto it = DILocation2SampleMap.try_emplace(DIL,nullptr); 720 if (it.second) { 721 if (ProfileIsCS) 722 it.first->second = ContextTracker->getContextSamplesFor(DIL); 723 else 724 it.first->second = 725 Samples->findFunctionSamples(DIL, Reader->getRemapper()); 726 } 727 return it.first->second; 728 } 729 730 /// Check whether the indirect call promotion history of \p Inst allows 731 /// the promotion for \p Candidate. 732 /// If the profile count for the promotion candidate \p Candidate is 733 /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted 734 /// for \p Inst. If we already have at least MaxNumPromotions 735 /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we 736 /// cannot promote for \p Inst anymore. 737 static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) { 738 uint32_t NumVals = 0; 739 uint64_t TotalCount = 0; 740 std::unique_ptr<InstrProfValueData[]> ValueData = 741 std::make_unique<InstrProfValueData[]>(MaxNumPromotions); 742 bool Valid = 743 getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions, 744 ValueData.get(), NumVals, TotalCount, true); 745 // No valid value profile so no promoted targets have been recorded 746 // before. Ok to do ICP. 747 if (!Valid) 748 return true; 749 750 unsigned NumPromoted = 0; 751 for (uint32_t I = 0; I < NumVals; I++) { 752 if (ValueData[I].Count != NOMORE_ICP_MAGICNUM) 753 continue; 754 755 // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the 756 // metadata, it means the candidate has been promoted for this 757 // indirect call. 758 if (ValueData[I].Value == Function::getGUID(Candidate)) 759 return false; 760 NumPromoted++; 761 // If already have MaxNumPromotions promotion, don't do it anymore. 762 if (NumPromoted == MaxNumPromotions) 763 return false; 764 } 765 return true; 766 } 767 768 /// Update indirect call target profile metadata for \p Inst. 769 /// Usually \p Sum is the sum of counts of all the targets for \p Inst. 770 /// If it is 0, it means updateIDTMetaData is used to mark a 771 /// certain target to be promoted already. If it is not zero, 772 /// we expect to use it to update the total count in the value profile. 773 static void 774 updateIDTMetaData(Instruction &Inst, 775 const SmallVectorImpl<InstrProfValueData> &CallTargets, 776 uint64_t Sum) { 777 uint32_t NumVals = 0; 778 // OldSum is the existing total count in the value profile data. 779 uint64_t OldSum = 0; 780 std::unique_ptr<InstrProfValueData[]> ValueData = 781 std::make_unique<InstrProfValueData[]>(MaxNumPromotions); 782 bool Valid = 783 getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions, 784 ValueData.get(), NumVals, OldSum, true); 785 786 DenseMap<uint64_t, uint64_t> ValueCountMap; 787 if (Sum == 0) { 788 assert((CallTargets.size() == 1 && 789 CallTargets[0].Count == NOMORE_ICP_MAGICNUM) && 790 "If sum is 0, assume only one element in CallTargets " 791 "with count being NOMORE_ICP_MAGICNUM"); 792 // Initialize ValueCountMap with existing value profile data. 793 if (Valid) { 794 for (uint32_t I = 0; I < NumVals; I++) 795 ValueCountMap[ValueData[I].Value] = ValueData[I].Count; 796 } 797 auto Pair = 798 ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count); 799 // If the target already exists in value profile, decrease the total 800 // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM. 801 if (!Pair.second) { 802 OldSum -= Pair.first->second; 803 Pair.first->second = NOMORE_ICP_MAGICNUM; 804 } 805 Sum = OldSum; 806 } else { 807 // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM 808 // counts in the value profile. 809 if (Valid) { 810 for (uint32_t I = 0; I < NumVals; I++) { 811 if (ValueData[I].Count == NOMORE_ICP_MAGICNUM) 812 ValueCountMap[ValueData[I].Value] = ValueData[I].Count; 813 } 814 } 815 816 for (const auto &Data : CallTargets) { 817 auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count); 818 if (Pair.second) 819 continue; 820 // The target represented by Data.Value has already been promoted. 821 // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease 822 // Sum by Data.Count. 823 assert(Sum >= Data.Count && "Sum should never be less than Data.Count"); 824 Sum -= Data.Count; 825 } 826 } 827 828 SmallVector<InstrProfValueData, 8> NewCallTargets; 829 for (const auto &ValueCount : ValueCountMap) { 830 NewCallTargets.emplace_back( 831 InstrProfValueData{ValueCount.first, ValueCount.second}); 832 } 833 834 llvm::sort(NewCallTargets, 835 [](const InstrProfValueData &L, const InstrProfValueData &R) { 836 if (L.Count != R.Count) 837 return L.Count > R.Count; 838 return L.Value > R.Value; 839 }); 840 841 uint32_t MaxMDCount = 842 std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions)); 843 annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst, 844 NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount); 845 } 846 847 /// Attempt to promote indirect call and also inline the promoted call. 848 /// 849 /// \param F Caller function. 850 /// \param Candidate ICP and inline candidate. 851 /// \param SumOrigin Original sum of target counts for indirect call before 852 /// promoting given candidate. 853 /// \param Sum Prorated sum of remaining target counts for indirect call 854 /// after promoting given candidate. 855 /// \param InlinedCallSite Output vector for new call sites exposed after 856 /// inlining. 857 bool SampleProfileLoader::tryPromoteAndInlineCandidate( 858 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum, 859 SmallVector<CallBase *, 8> *InlinedCallSite) { 860 auto CalleeFunctionName = Candidate.CalleeSamples->getFuncName(); 861 auto R = SymbolMap.find(CalleeFunctionName); 862 if (R == SymbolMap.end() || !R->getValue()) 863 return false; 864 865 auto &CI = *Candidate.CallInstr; 866 if (!doesHistoryAllowICP(CI, R->getValue()->getName())) 867 return false; 868 869 const char *Reason = "Callee function not available"; 870 // R->getValue() != &F is to prevent promoting a recursive call. 871 // If it is a recursive call, we do not inline it as it could bloat 872 // the code exponentially. There is way to better handle this, e.g. 873 // clone the caller first, and inline the cloned caller if it is 874 // recursive. As llvm does not inline recursive calls, we will 875 // simply ignore it instead of handling it explicitly. 876 if (!R->getValue()->isDeclaration() && R->getValue()->getSubprogram() && 877 R->getValue()->hasFnAttribute("use-sample-profile") && 878 R->getValue() != &F && isLegalToPromote(CI, R->getValue(), &Reason)) { 879 // For promoted target, set its value with NOMORE_ICP_MAGICNUM count 880 // in the value profile metadata so the target won't be promoted again. 881 SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{ 882 Function::getGUID(R->getValue()->getName()), NOMORE_ICP_MAGICNUM}}; 883 updateIDTMetaData(CI, SortedCallTargets, 0); 884 885 auto *DI = &pgo::promoteIndirectCall( 886 CI, R->getValue(), Candidate.CallsiteCount, Sum, false, ORE); 887 if (DI) { 888 Sum -= Candidate.CallsiteCount; 889 // Do not prorate the indirect callsite distribution since the original 890 // distribution will be used to scale down non-promoted profile target 891 // counts later. By doing this we lose track of the real callsite count 892 // for the leftover indirect callsite as a trade off for accurate call 893 // target counts. 894 // TODO: Ideally we would have two separate factors, one for call site 895 // counts and one is used to prorate call target counts. 896 // Do not update the promoted direct callsite distribution at this 897 // point since the original distribution combined with the callee profile 898 // will be used to prorate callsites from the callee if inlined. Once not 899 // inlined, the direct callsite distribution should be prorated so that 900 // the it will reflect the real callsite counts. 901 Candidate.CallInstr = DI; 902 if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) { 903 bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite); 904 if (!Inlined) { 905 // Prorate the direct callsite distribution so that it reflects real 906 // callsite counts. 907 setProbeDistributionFactor( 908 *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin); 909 } 910 return Inlined; 911 } 912 } 913 } else { 914 LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to " 915 << Candidate.CalleeSamples->getFuncName() << " because " 916 << Reason << "\n"); 917 } 918 return false; 919 } 920 921 bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) { 922 if (!ProfileSizeInline) 923 return false; 924 925 Function *Callee = CallInst.getCalledFunction(); 926 if (Callee == nullptr) 927 return false; 928 929 InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee), 930 GetAC, GetTLI); 931 932 if (Cost.isNever()) 933 return false; 934 935 if (Cost.isAlways()) 936 return true; 937 938 return Cost.getCost() <= SampleColdCallSiteThreshold; 939 } 940 941 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates( 942 const SmallVectorImpl<CallBase *> &Candidates, const Function &F, 943 bool Hot) { 944 for (auto I : Candidates) { 945 Function *CalledFunction = I->getCalledFunction(); 946 if (CalledFunction) { 947 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt", 948 I->getDebugLoc(), I->getParent()) 949 << "previous inlining reattempted for " 950 << (Hot ? "hotness: '" : "size: '") 951 << ore::NV("Callee", CalledFunction) << "' into '" 952 << ore::NV("Caller", &F) << "'"); 953 } 954 } 955 } 956 957 void SampleProfileLoader::findExternalInlineCandidate( 958 const FunctionSamples *Samples, DenseSet<GlobalValue::GUID> &InlinedGUIDs, 959 const StringMap<Function *> &SymbolMap, uint64_t Threshold) { 960 assert(Samples && "expect non-null caller profile"); 961 962 // For AutoFDO profile, retrieve candidate profiles by walking over 963 // the nested inlinee profiles. 964 if (!ProfileIsCS) { 965 Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold); 966 return; 967 } 968 969 ContextTrieNode *Caller = 970 ContextTracker->getContextFor(Samples->getContext()); 971 std::queue<ContextTrieNode *> CalleeList; 972 CalleeList.push(Caller); 973 while (!CalleeList.empty()) { 974 ContextTrieNode *Node = CalleeList.front(); 975 CalleeList.pop(); 976 FunctionSamples *CalleeSample = Node->getFunctionSamples(); 977 // For CSSPGO profile, retrieve candidate profile by walking over the 978 // trie built for context profile. Note that also take call targets 979 // even if callee doesn't have a corresponding context profile. 980 if (!CalleeSample || CalleeSample->getEntrySamples() < Threshold) 981 continue; 982 983 StringRef Name = CalleeSample->getFuncName(); 984 Function *Func = SymbolMap.lookup(Name); 985 // Add to the import list only when it's defined out of module. 986 if (!Func || Func->isDeclaration()) 987 InlinedGUIDs.insert(FunctionSamples::getGUID(Name)); 988 989 // Import hot CallTargets, which may not be available in IR because full 990 // profile annotation cannot be done until backend compilation in ThinLTO. 991 for (const auto &BS : CalleeSample->getBodySamples()) 992 for (const auto &TS : BS.second.getCallTargets()) 993 if (TS.getValue() > Threshold) { 994 StringRef CalleeName = CalleeSample->getFuncName(TS.getKey()); 995 const Function *Callee = SymbolMap.lookup(CalleeName); 996 if (!Callee || Callee->isDeclaration()) 997 InlinedGUIDs.insert(FunctionSamples::getGUID(CalleeName)); 998 } 999 1000 // Import hot child context profile associted with callees. Note that this 1001 // may have some overlap with the call target loop above, but doing this 1002 // based child context profile again effectively allow us to use the max of 1003 // entry count and call target count to determine importing. 1004 for (auto &Child : Node->getAllChildContext()) { 1005 ContextTrieNode *CalleeNode = &Child.second; 1006 CalleeList.push(CalleeNode); 1007 } 1008 } 1009 } 1010 1011 /// Iteratively inline hot callsites of a function. 1012 /// 1013 /// Iteratively traverse all callsites of the function \p F, and find if 1014 /// the corresponding inlined instance exists and is hot in profile. If 1015 /// it is hot enough, inline the callsites and adds new callsites of the 1016 /// callee into the caller. If the call is an indirect call, first promote 1017 /// it to direct call. Each indirect call is limited with a single target. 1018 /// 1019 /// \param F function to perform iterative inlining. 1020 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are 1021 /// inlined in the profiled binary. 1022 /// 1023 /// \returns True if there is any inline happened. 1024 bool SampleProfileLoader::inlineHotFunctions( 1025 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) { 1026 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure 1027 // Profile symbol list is ignored when profile-sample-accurate is on. 1028 assert((!ProfAccForSymsInList || 1029 (!ProfileSampleAccurate && 1030 !F.hasFnAttribute("profile-sample-accurate"))) && 1031 "ProfAccForSymsInList should be false when profile-sample-accurate " 1032 "is enabled"); 1033 1034 DenseMap<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites; 1035 bool Changed = false; 1036 bool LocalChanged = true; 1037 while (LocalChanged) { 1038 LocalChanged = false; 1039 SmallVector<CallBase *, 10> CIS; 1040 for (auto &BB : F) { 1041 bool Hot = false; 1042 SmallVector<CallBase *, 10> AllCandidates; 1043 SmallVector<CallBase *, 10> ColdCandidates; 1044 for (auto &I : BB.getInstList()) { 1045 const FunctionSamples *FS = nullptr; 1046 if (auto *CB = dyn_cast<CallBase>(&I)) { 1047 if (!isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(*CB))) { 1048 assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) && 1049 "GUIDToFuncNameMap has to be populated"); 1050 AllCandidates.push_back(CB); 1051 if (FS->getEntrySamples() > 0 || ProfileIsCS) 1052 LocalNotInlinedCallSites.try_emplace(CB, FS); 1053 if (callsiteIsHot(FS, PSI, ProfAccForSymsInList)) 1054 Hot = true; 1055 else if (shouldInlineColdCallee(*CB)) 1056 ColdCandidates.push_back(CB); 1057 } 1058 } 1059 } 1060 if (Hot || ExternalInlineAdvisor) { 1061 CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end()); 1062 emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true); 1063 } else { 1064 CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end()); 1065 emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false); 1066 } 1067 } 1068 for (CallBase *I : CIS) { 1069 Function *CalledFunction = I->getCalledFunction(); 1070 InlineCandidate Candidate = { 1071 I, 1072 LocalNotInlinedCallSites.count(I) ? LocalNotInlinedCallSites[I] 1073 : nullptr, 1074 0 /* dummy count */, 1.0 /* dummy distribution factor */}; 1075 // Do not inline recursive calls. 1076 if (CalledFunction == &F) 1077 continue; 1078 if (I->isIndirectCall()) { 1079 uint64_t Sum; 1080 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) { 1081 uint64_t SumOrigin = Sum; 1082 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) { 1083 findExternalInlineCandidate(FS, InlinedGUIDs, SymbolMap, 1084 PSI->getOrCompHotCountThreshold()); 1085 continue; 1086 } 1087 if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList)) 1088 continue; 1089 1090 Candidate = {I, FS, FS->getEntrySamples(), 1.0}; 1091 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) { 1092 LocalNotInlinedCallSites.erase(I); 1093 LocalChanged = true; 1094 } 1095 } 1096 } else if (CalledFunction && CalledFunction->getSubprogram() && 1097 !CalledFunction->isDeclaration()) { 1098 if (tryInlineCandidate(Candidate)) { 1099 LocalNotInlinedCallSites.erase(I); 1100 LocalChanged = true; 1101 } 1102 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) { 1103 findExternalInlineCandidate(findCalleeFunctionSamples(*I), InlinedGUIDs, 1104 SymbolMap, 1105 PSI->getOrCompHotCountThreshold()); 1106 } 1107 } 1108 Changed |= LocalChanged; 1109 } 1110 1111 // For CS profile, profile for not inlined context will be merged when 1112 // base profile is being trieved 1113 if (ProfileIsCS) 1114 return Changed; 1115 1116 // Accumulate not inlined callsite information into notInlinedSamples 1117 for (const auto &Pair : LocalNotInlinedCallSites) { 1118 CallBase *I = Pair.getFirst(); 1119 Function *Callee = I->getCalledFunction(); 1120 if (!Callee || Callee->isDeclaration()) 1121 continue; 1122 1123 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline", 1124 I->getDebugLoc(), I->getParent()) 1125 << "previous inlining not repeated: '" 1126 << ore::NV("Callee", Callee) << "' into '" 1127 << ore::NV("Caller", &F) << "'"); 1128 1129 ++NumCSNotInlined; 1130 const FunctionSamples *FS = Pair.getSecond(); 1131 if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) { 1132 continue; 1133 } 1134 1135 if (ProfileMergeInlinee) { 1136 // A function call can be replicated by optimizations like callsite 1137 // splitting or jump threading and the replicates end up sharing the 1138 // sample nested callee profile instead of slicing the original inlinee's 1139 // profile. We want to do merge exactly once by filtering out callee 1140 // profiles with a non-zero head sample count. 1141 if (FS->getHeadSamples() == 0) { 1142 // Use entry samples as head samples during the merge, as inlinees 1143 // don't have head samples. 1144 const_cast<FunctionSamples *>(FS)->addHeadSamples( 1145 FS->getEntrySamples()); 1146 1147 // Note that we have to do the merge right after processing function. 1148 // This allows OutlineFS's profile to be used for annotation during 1149 // top-down processing of functions' annotation. 1150 FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee); 1151 OutlineFS->merge(*FS); 1152 } 1153 } else { 1154 auto pair = 1155 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0}); 1156 pair.first->second.entryCount += FS->getEntrySamples(); 1157 } 1158 } 1159 return Changed; 1160 } 1161 1162 bool SampleProfileLoader::tryInlineCandidate( 1163 InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) { 1164 1165 CallBase &CB = *Candidate.CallInstr; 1166 Function *CalledFunction = CB.getCalledFunction(); 1167 assert(CalledFunction && "Expect a callee with definition"); 1168 DebugLoc DLoc = CB.getDebugLoc(); 1169 BasicBlock *BB = CB.getParent(); 1170 1171 InlineCost Cost = shouldInlineCandidate(Candidate); 1172 if (Cost.isNever()) { 1173 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB) 1174 << "incompatible inlining"); 1175 return false; 1176 } 1177 1178 if (!Cost) 1179 return false; 1180 1181 InlineFunctionInfo IFI(nullptr, GetAC); 1182 IFI.UpdateProfile = false; 1183 if (InlineFunction(CB, IFI).isSuccess()) { 1184 // Merge the attributes based on the inlining. 1185 AttributeFuncs::mergeAttributesForInlining(*BB->getParent(), 1186 *CalledFunction); 1187 1188 // The call to InlineFunction erases I, so we can't pass it here. 1189 emitInlinedInto(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(), Cost, 1190 true, CSINLINE_DEBUG); 1191 1192 // Now populate the list of newly exposed call sites. 1193 if (InlinedCallSites) { 1194 InlinedCallSites->clear(); 1195 for (auto &I : IFI.InlinedCallSites) 1196 InlinedCallSites->push_back(I); 1197 } 1198 1199 if (ProfileIsCS) 1200 ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples); 1201 ++NumCSInlined; 1202 1203 // Prorate inlined probes for a duplicated inlining callsite which probably 1204 // has a distribution less than 100%. Samples for an inlinee should be 1205 // distributed among the copies of the original callsite based on each 1206 // callsite's distribution factor for counts accuracy. Note that an inlined 1207 // probe may come with its own distribution factor if it has been duplicated 1208 // in the inlinee body. The two factor are multiplied to reflect the 1209 // aggregation of duplication. 1210 if (Candidate.CallsiteDistribution < 1) { 1211 for (auto &I : IFI.InlinedCallSites) { 1212 if (Optional<PseudoProbe> Probe = extractProbe(*I)) 1213 setProbeDistributionFactor(*I, Probe->Factor * 1214 Candidate.CallsiteDistribution); 1215 } 1216 NumDuplicatedInlinesite++; 1217 } 1218 1219 return true; 1220 } 1221 return false; 1222 } 1223 1224 bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate, 1225 CallBase *CB) { 1226 assert(CB && "Expect non-null call instruction"); 1227 1228 if (isa<IntrinsicInst>(CB)) 1229 return false; 1230 1231 // Find the callee's profile. For indirect call, find hottest target profile. 1232 const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB); 1233 if (!CalleeSamples) 1234 return false; 1235 1236 float Factor = 1.0; 1237 if (Optional<PseudoProbe> Probe = extractProbe(*CB)) 1238 Factor = Probe->Factor; 1239 1240 uint64_t CallsiteCount = 0; 1241 ErrorOr<uint64_t> Weight = getBlockWeight(CB->getParent()); 1242 if (Weight) 1243 CallsiteCount = Weight.get(); 1244 if (CalleeSamples) 1245 CallsiteCount = std::max( 1246 CallsiteCount, uint64_t(CalleeSamples->getEntrySamples() * Factor)); 1247 1248 *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor}; 1249 return true; 1250 } 1251 1252 InlineCost 1253 SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) { 1254 std::unique_ptr<InlineAdvice> Advice = nullptr; 1255 if (ExternalInlineAdvisor) { 1256 Advice = ExternalInlineAdvisor->getAdvice(*Candidate.CallInstr); 1257 if (!Advice->isInliningRecommended()) { 1258 Advice->recordUnattemptedInlining(); 1259 return InlineCost::getNever("not previously inlined"); 1260 } 1261 Advice->recordInlining(); 1262 return InlineCost::getAlways("previously inlined"); 1263 } 1264 1265 // Adjust threshold based on call site hotness, only do this for callsite 1266 // prioritized inliner because otherwise cost-benefit check is done earlier. 1267 int SampleThreshold = SampleColdCallSiteThreshold; 1268 if (CallsitePrioritizedInline) { 1269 if (Candidate.CallsiteCount > PSI->getHotCountThreshold()) 1270 SampleThreshold = SampleHotCallSiteThreshold; 1271 else if (!ProfileSizeInline) 1272 return InlineCost::getNever("cold callsite"); 1273 } 1274 1275 Function *Callee = Candidate.CallInstr->getCalledFunction(); 1276 assert(Callee && "Expect a definition for inline candidate of direct call"); 1277 1278 InlineParams Params = getInlineParams(); 1279 Params.ComputeFullInlineCost = true; 1280 // Checks if there is anything in the reachable portion of the callee at 1281 // this callsite that makes this inlining potentially illegal. Need to 1282 // set ComputeFullInlineCost, otherwise getInlineCost may return early 1283 // when cost exceeds threshold without checking all IRs in the callee. 1284 // The acutal cost does not matter because we only checks isNever() to 1285 // see if it is legal to inline the callsite. 1286 InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params, 1287 GetTTI(*Callee), GetAC, GetTLI); 1288 1289 // Honor always inline and never inline from call analyzer 1290 if (Cost.isNever() || Cost.isAlways()) 1291 return Cost; 1292 1293 // With CSSPGO, the preinliner in llvm-profgen can estimate global inline 1294 // decisions based on hotness as well as accurate function byte sizes for 1295 // given context using function/inlinee sizes from previous build. It 1296 // stores the decision in profile, and also adjust/merge context profile 1297 // aiming at better context-sensitive post-inline profile quality, assuming 1298 // all inline decision estimates are going to be honored by compiler. Here 1299 // we replay that inline decision under `sample-profile-use-preinliner`. 1300 if (UsePreInlinerDecision) { 1301 if (Candidate.CalleeSamples->getContext().hasAttribute( 1302 ContextShouldBeInlined)) 1303 return InlineCost::getAlways("preinliner"); 1304 else 1305 return InlineCost::getNever("preinliner"); 1306 } 1307 1308 // For old FDO inliner, we inline the call site as long as cost is not 1309 // "Never". The cost-benefit check is done earlier. 1310 if (!CallsitePrioritizedInline) { 1311 return InlineCost::get(Cost.getCost(), INT_MAX); 1312 } 1313 1314 // Otherwise only use the cost from call analyzer, but overwite threshold with 1315 // Sample PGO threshold. 1316 return InlineCost::get(Cost.getCost(), SampleThreshold); 1317 } 1318 1319 bool SampleProfileLoader::inlineHotFunctionsWithPriority( 1320 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) { 1321 assert(ProfileIsCS && "Prioritiy based inliner only works with CSSPGO now"); 1322 1323 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure 1324 // Profile symbol list is ignored when profile-sample-accurate is on. 1325 assert((!ProfAccForSymsInList || 1326 (!ProfileSampleAccurate && 1327 !F.hasFnAttribute("profile-sample-accurate"))) && 1328 "ProfAccForSymsInList should be false when profile-sample-accurate " 1329 "is enabled"); 1330 1331 // Populating worklist with initial call sites from root inliner, along 1332 // with call site weights. 1333 CandidateQueue CQueue; 1334 InlineCandidate NewCandidate; 1335 for (auto &BB : F) { 1336 for (auto &I : BB.getInstList()) { 1337 auto *CB = dyn_cast<CallBase>(&I); 1338 if (!CB) 1339 continue; 1340 if (getInlineCandidate(&NewCandidate, CB)) 1341 CQueue.push(NewCandidate); 1342 } 1343 } 1344 1345 // Cap the size growth from profile guided inlining. This is needed even 1346 // though cost of each inline candidate already accounts for callee size, 1347 // because with top-down inlining, we can grow inliner size significantly 1348 // with large number of smaller inlinees each pass the cost check. 1349 assert(ProfileInlineLimitMax >= ProfileInlineLimitMin && 1350 "Max inline size limit should not be smaller than min inline size " 1351 "limit."); 1352 unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit; 1353 SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax); 1354 SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin); 1355 if (ExternalInlineAdvisor) 1356 SizeLimit = std::numeric_limits<unsigned>::max(); 1357 1358 // Perform iterative BFS call site prioritized inlining 1359 bool Changed = false; 1360 while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) { 1361 InlineCandidate Candidate = CQueue.top(); 1362 CQueue.pop(); 1363 CallBase *I = Candidate.CallInstr; 1364 Function *CalledFunction = I->getCalledFunction(); 1365 1366 if (CalledFunction == &F) 1367 continue; 1368 if (I->isIndirectCall()) { 1369 uint64_t Sum = 0; 1370 auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum); 1371 uint64_t SumOrigin = Sum; 1372 Sum *= Candidate.CallsiteDistribution; 1373 unsigned ICPCount = 0; 1374 for (const auto *FS : CalleeSamples) { 1375 // TODO: Consider disable pre-lTO ICP for MonoLTO as well 1376 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) { 1377 findExternalInlineCandidate(FS, InlinedGUIDs, SymbolMap, 1378 PSI->getOrCompHotCountThreshold()); 1379 continue; 1380 } 1381 uint64_t EntryCountDistributed = 1382 FS->getEntrySamples() * Candidate.CallsiteDistribution; 1383 // In addition to regular inline cost check, we also need to make sure 1384 // ICP isn't introducing excessive speculative checks even if individual 1385 // target looks beneficial to promote and inline. That means we should 1386 // only do ICP when there's a small number dominant targets. 1387 if (ICPCount >= ProfileICPRelativeHotnessSkip && 1388 EntryCountDistributed * 100 < SumOrigin * ProfileICPRelativeHotness) 1389 break; 1390 // TODO: Fix CallAnalyzer to handle all indirect calls. 1391 // For indirect call, we don't run CallAnalyzer to get InlineCost 1392 // before actual inlining. This is because we could see two different 1393 // types from the same definition, which makes CallAnalyzer choke as 1394 // it's expecting matching parameter type on both caller and callee 1395 // side. See example from PR18962 for the triggering cases (the bug was 1396 // fixed, but we generate different types). 1397 if (!PSI->isHotCount(EntryCountDistributed)) 1398 break; 1399 SmallVector<CallBase *, 8> InlinedCallSites; 1400 // Attach function profile for promoted indirect callee, and update 1401 // call site count for the promoted inline candidate too. 1402 Candidate = {I, FS, EntryCountDistributed, 1403 Candidate.CallsiteDistribution}; 1404 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum, 1405 &InlinedCallSites)) { 1406 for (auto *CB : InlinedCallSites) { 1407 if (getInlineCandidate(&NewCandidate, CB)) 1408 CQueue.emplace(NewCandidate); 1409 } 1410 ICPCount++; 1411 Changed = true; 1412 } 1413 } 1414 } else if (CalledFunction && CalledFunction->getSubprogram() && 1415 !CalledFunction->isDeclaration()) { 1416 SmallVector<CallBase *, 8> InlinedCallSites; 1417 if (tryInlineCandidate(Candidate, &InlinedCallSites)) { 1418 for (auto *CB : InlinedCallSites) { 1419 if (getInlineCandidate(&NewCandidate, CB)) 1420 CQueue.emplace(NewCandidate); 1421 } 1422 Changed = true; 1423 } 1424 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) { 1425 findExternalInlineCandidate(Candidate.CalleeSamples, InlinedGUIDs, 1426 SymbolMap, PSI->getOrCompHotCountThreshold()); 1427 } 1428 } 1429 1430 if (!CQueue.empty()) { 1431 if (SizeLimit == (unsigned)ProfileInlineLimitMax) 1432 ++NumCSInlinedHitMaxLimit; 1433 else if (SizeLimit == (unsigned)ProfileInlineLimitMin) 1434 ++NumCSInlinedHitMinLimit; 1435 else 1436 ++NumCSInlinedHitGrowthLimit; 1437 } 1438 1439 return Changed; 1440 } 1441 1442 /// Returns the sorted CallTargetMap \p M by count in descending order. 1443 static SmallVector<InstrProfValueData, 2> 1444 GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) { 1445 SmallVector<InstrProfValueData, 2> R; 1446 for (const auto &I : SampleRecord::SortCallTargets(M)) { 1447 R.emplace_back( 1448 InstrProfValueData{FunctionSamples::getGUID(I.first), I.second}); 1449 } 1450 return R; 1451 } 1452 1453 // Generate MD_prof metadata for every branch instruction using the 1454 // edge weights computed during propagation. 1455 void SampleProfileLoader::generateMDProfMetadata(Function &F) { 1456 // Generate MD_prof metadata for every branch instruction using the 1457 // edge weights computed during propagation. 1458 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n"); 1459 LLVMContext &Ctx = F.getContext(); 1460 MDBuilder MDB(Ctx); 1461 for (auto &BI : F) { 1462 BasicBlock *BB = &BI; 1463 1464 if (BlockWeights[BB]) { 1465 for (auto &I : BB->getInstList()) { 1466 if (!isa<CallInst>(I) && !isa<InvokeInst>(I)) 1467 continue; 1468 if (!cast<CallBase>(I).getCalledFunction()) { 1469 const DebugLoc &DLoc = I.getDebugLoc(); 1470 if (!DLoc) 1471 continue; 1472 const DILocation *DIL = DLoc; 1473 const FunctionSamples *FS = findFunctionSamples(I); 1474 if (!FS) 1475 continue; 1476 auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL); 1477 auto T = FS->findCallTargetMapAt(CallSite); 1478 if (!T || T.get().empty()) 1479 continue; 1480 if (FunctionSamples::ProfileIsProbeBased) { 1481 // Prorate the callsite counts based on the pre-ICP distribution 1482 // factor to reflect what is already done to the callsite before 1483 // ICP, such as calliste cloning. 1484 if (Optional<PseudoProbe> Probe = extractProbe(I)) { 1485 if (Probe->Factor < 1) 1486 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor); 1487 } 1488 } 1489 SmallVector<InstrProfValueData, 2> SortedCallTargets = 1490 GetSortedValueDataFromCallTargets(T.get()); 1491 uint64_t Sum = 0; 1492 for (const auto &C : T.get()) 1493 Sum += C.second; 1494 // With CSSPGO all indirect call targets are counted torwards the 1495 // original indirect call site in the profile, including both 1496 // inlined and non-inlined targets. 1497 if (!FunctionSamples::ProfileIsCS) { 1498 if (const FunctionSamplesMap *M = 1499 FS->findFunctionSamplesMapAt(CallSite)) { 1500 for (const auto &NameFS : *M) 1501 Sum += NameFS.second.getEntrySamples(); 1502 } 1503 } 1504 if (Sum) 1505 updateIDTMetaData(I, SortedCallTargets, Sum); 1506 else if (OverwriteExistingWeights) 1507 I.setMetadata(LLVMContext::MD_prof, nullptr); 1508 } else if (!isa<IntrinsicInst>(&I)) { 1509 I.setMetadata(LLVMContext::MD_prof, 1510 MDB.createBranchWeights( 1511 {static_cast<uint32_t>(BlockWeights[BB])})); 1512 } 1513 } 1514 } else if (OverwriteExistingWeights) { 1515 // Set profile metadata (possibly annotated by LTO prelink) to zero or 1516 // clear it for cold code. 1517 for (auto &I : BB->getInstList()) { 1518 if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 1519 if (cast<CallBase>(I).isIndirectCall()) 1520 I.setMetadata(LLVMContext::MD_prof, nullptr); 1521 else 1522 I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(0)); 1523 } 1524 } 1525 } 1526 1527 Instruction *TI = BB->getTerminator(); 1528 if (TI->getNumSuccessors() == 1) 1529 continue; 1530 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI) && 1531 !isa<IndirectBrInst>(TI)) 1532 continue; 1533 1534 DebugLoc BranchLoc = TI->getDebugLoc(); 1535 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line " 1536 << ((BranchLoc) ? Twine(BranchLoc.getLine()) 1537 : Twine("<UNKNOWN LOCATION>")) 1538 << ".\n"); 1539 SmallVector<uint32_t, 4> Weights; 1540 uint32_t MaxWeight = 0; 1541 Instruction *MaxDestInst; 1542 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) { 1543 BasicBlock *Succ = TI->getSuccessor(I); 1544 Edge E = std::make_pair(BB, Succ); 1545 uint64_t Weight = EdgeWeights[E]; 1546 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E)); 1547 // Use uint32_t saturated arithmetic to adjust the incoming weights, 1548 // if needed. Sample counts in profiles are 64-bit unsigned values, 1549 // but internally branch weights are expressed as 32-bit values. 1550 if (Weight > std::numeric_limits<uint32_t>::max()) { 1551 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)"); 1552 Weight = std::numeric_limits<uint32_t>::max(); 1553 } 1554 // Weight is added by one to avoid propagation errors introduced by 1555 // 0 weights. 1556 Weights.push_back(static_cast<uint32_t>(Weight + 1)); 1557 if (Weight != 0) { 1558 if (Weight > MaxWeight) { 1559 MaxWeight = Weight; 1560 MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime(); 1561 } 1562 } 1563 } 1564 1565 uint64_t TempWeight; 1566 // Only set weights if there is at least one non-zero weight. 1567 // In any other case, let the analyzer set weights. 1568 // Do not set weights if the weights are present unless under 1569 // OverwriteExistingWeights. In ThinLTO, the profile annotation is done 1570 // twice. If the first annotation already set the weights, the second pass 1571 // does not need to set it. With OverwriteExistingWeights, Blocks with zero 1572 // weight should have their existing metadata (possibly annotated by LTO 1573 // prelink) cleared. 1574 if (MaxWeight > 0 && 1575 (!TI->extractProfTotalWeight(TempWeight) || OverwriteExistingWeights)) { 1576 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n"); 1577 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); 1578 ORE->emit([&]() { 1579 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst) 1580 << "most popular destination for conditional branches at " 1581 << ore::NV("CondBranchesLoc", BranchLoc); 1582 }); 1583 } else { 1584 if (OverwriteExistingWeights) { 1585 TI->setMetadata(LLVMContext::MD_prof, nullptr); 1586 LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n"); 1587 } else { 1588 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n"); 1589 } 1590 } 1591 } 1592 } 1593 1594 /// Once all the branch weights are computed, we emit the MD_prof 1595 /// metadata on BB using the computed values for each of its branches. 1596 /// 1597 /// \param F The function to query. 1598 /// 1599 /// \returns true if \p F was modified. Returns false, otherwise. 1600 bool SampleProfileLoader::emitAnnotations(Function &F) { 1601 bool Changed = false; 1602 1603 if (FunctionSamples::ProfileIsProbeBased) { 1604 if (!ProbeManager->profileIsValid(F, *Samples)) { 1605 LLVM_DEBUG( 1606 dbgs() << "Profile is invalid due to CFG mismatch for Function " 1607 << F.getName()); 1608 ++NumMismatchedProfile; 1609 return false; 1610 } 1611 ++NumMatchedProfile; 1612 } else { 1613 if (getFunctionLoc(F) == 0) 1614 return false; 1615 1616 LLVM_DEBUG(dbgs() << "Line number for the first instruction in " 1617 << F.getName() << ": " << getFunctionLoc(F) << "\n"); 1618 } 1619 1620 DenseSet<GlobalValue::GUID> InlinedGUIDs; 1621 if (ProfileIsCS && CallsitePrioritizedInline) 1622 Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs); 1623 else 1624 Changed |= inlineHotFunctions(F, InlinedGUIDs); 1625 1626 Changed |= computeAndPropagateWeights(F, InlinedGUIDs); 1627 1628 if (Changed) 1629 generateMDProfMetadata(F); 1630 1631 emitCoverageRemarks(F); 1632 return Changed; 1633 } 1634 1635 char SampleProfileLoaderLegacyPass::ID = 0; 1636 1637 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile", 1638 "Sample Profile loader", false, false) 1639 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1640 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1641 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1642 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 1643 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile", 1644 "Sample Profile loader", false, false) 1645 1646 std::unique_ptr<ProfiledCallGraph> 1647 SampleProfileLoader::buildProfiledCallGraph(CallGraph &CG) { 1648 std::unique_ptr<ProfiledCallGraph> ProfiledCG; 1649 if (ProfileIsCS) 1650 ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker); 1651 else 1652 ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles()); 1653 1654 // Add all functions into the profiled call graph even if they are not in 1655 // the profile. This makes sure functions missing from the profile still 1656 // gets a chance to be processed. 1657 for (auto &Node : CG) { 1658 const auto *F = Node.first; 1659 if (!F || F->isDeclaration() || !F->hasFnAttribute("use-sample-profile")) 1660 continue; 1661 ProfiledCG->addProfiledFunction(FunctionSamples::getCanonicalFnName(*F)); 1662 } 1663 1664 return ProfiledCG; 1665 } 1666 1667 std::vector<Function *> 1668 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) { 1669 std::vector<Function *> FunctionOrderList; 1670 FunctionOrderList.reserve(M.size()); 1671 1672 if (!ProfileTopDownLoad && UseProfiledCallGraph) 1673 errs() << "WARNING: -use-profiled-call-graph ignored, should be used " 1674 "together with -sample-profile-top-down-load.\n"; 1675 1676 if (!ProfileTopDownLoad || CG == nullptr) { 1677 if (ProfileMergeInlinee) { 1678 // Disable ProfileMergeInlinee if profile is not loaded in top down order, 1679 // because the profile for a function may be used for the profile 1680 // annotation of its outline copy before the profile merging of its 1681 // non-inlined inline instances, and that is not the way how 1682 // ProfileMergeInlinee is supposed to work. 1683 ProfileMergeInlinee = false; 1684 } 1685 1686 for (Function &F : M) 1687 if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile")) 1688 FunctionOrderList.push_back(&F); 1689 return FunctionOrderList; 1690 } 1691 1692 assert(&CG->getModule() == &M); 1693 1694 if (UseProfiledCallGraph || 1695 (ProfileIsCS && !UseProfiledCallGraph.getNumOccurrences())) { 1696 // Use profiled call edges to augment the top-down order. There are cases 1697 // that the top-down order computed based on the static call graph doesn't 1698 // reflect real execution order. For example 1699 // 1700 // 1. Incomplete static call graph due to unknown indirect call targets. 1701 // Adjusting the order by considering indirect call edges from the 1702 // profile can enable the inlining of indirect call targets by allowing 1703 // the caller processed before them. 1704 // 2. Mutual call edges in an SCC. The static processing order computed for 1705 // an SCC may not reflect the call contexts in the context-sensitive 1706 // profile, thus may cause potential inlining to be overlooked. The 1707 // function order in one SCC is being adjusted to a top-down order based 1708 // on the profile to favor more inlining. This is only a problem with CS 1709 // profile. 1710 // 3. Transitive indirect call edges due to inlining. When a callee function 1711 // (say B) is inlined into into a caller function (say A) in LTO prelink, 1712 // every call edge originated from the callee B will be transferred to 1713 // the caller A. If any transferred edge (say A->C) is indirect, the 1714 // original profiled indirect edge B->C, even if considered, would not 1715 // enforce a top-down order from the caller A to the potential indirect 1716 // call target C in LTO postlink since the inlined callee B is gone from 1717 // the static call graph. 1718 // 4. #3 can happen even for direct call targets, due to functions defined 1719 // in header files. A header function (say A), when included into source 1720 // files, is defined multiple times but only one definition survives due 1721 // to ODR. Therefore, the LTO prelink inlining done on those dropped 1722 // definitions can be useless based on a local file scope. More 1723 // importantly, the inlinee (say B), once fully inlined to a 1724 // to-be-dropped A, will have no profile to consume when its outlined 1725 // version is compiled. This can lead to a profile-less prelink 1726 // compilation for the outlined version of B which may be called from 1727 // external modules. while this isn't easy to fix, we rely on the 1728 // postlink AutoFDO pipeline to optimize B. Since the survived copy of 1729 // the A can be inlined in its local scope in prelink, it may not exist 1730 // in the merged IR in postlink, and we'll need the profiled call edges 1731 // to enforce a top-down order for the rest of the functions. 1732 // 1733 // Considering those cases, a profiled call graph completely independent of 1734 // the static call graph is constructed based on profile data, where 1735 // function objects are not even needed to handle case #3 and case 4. 1736 // 1737 // Note that static callgraph edges are completely ignored since they 1738 // can be conflicting with profiled edges for cyclic SCCs and may result in 1739 // an SCC order incompatible with profile-defined one. Using strictly 1740 // profile order ensures a maximum inlining experience. On the other hand, 1741 // static call edges are not so important when they don't correspond to a 1742 // context in the profile. 1743 1744 std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(*CG); 1745 scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get()); 1746 while (!CGI.isAtEnd()) { 1747 for (ProfiledCallGraphNode *Node : *CGI) { 1748 Function *F = SymbolMap.lookup(Node->Name); 1749 if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile")) 1750 FunctionOrderList.push_back(F); 1751 } 1752 ++CGI; 1753 } 1754 } else { 1755 scc_iterator<CallGraph *> CGI = scc_begin(CG); 1756 while (!CGI.isAtEnd()) { 1757 for (CallGraphNode *Node : *CGI) { 1758 auto *F = Node->getFunction(); 1759 if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile")) 1760 FunctionOrderList.push_back(F); 1761 } 1762 ++CGI; 1763 } 1764 } 1765 1766 LLVM_DEBUG({ 1767 dbgs() << "Function processing order:\n"; 1768 for (auto F : reverse(FunctionOrderList)) { 1769 dbgs() << F->getName() << "\n"; 1770 } 1771 }); 1772 1773 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end()); 1774 return FunctionOrderList; 1775 } 1776 1777 bool SampleProfileLoader::doInitialization(Module &M, 1778 FunctionAnalysisManager *FAM) { 1779 auto &Ctx = M.getContext(); 1780 1781 auto ReaderOrErr = SampleProfileReader::create( 1782 Filename, Ctx, FSDiscriminatorPass::Base, RemappingFilename); 1783 if (std::error_code EC = ReaderOrErr.getError()) { 1784 std::string Msg = "Could not open profile: " + EC.message(); 1785 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg)); 1786 return false; 1787 } 1788 Reader = std::move(ReaderOrErr.get()); 1789 Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink); 1790 // set module before reading the profile so reader may be able to only 1791 // read the function profiles which are used by the current module. 1792 Reader->setModule(&M); 1793 if (std::error_code EC = Reader->read()) { 1794 std::string Msg = "profile reading failed: " + EC.message(); 1795 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg)); 1796 return false; 1797 } 1798 1799 PSL = Reader->getProfileSymbolList(); 1800 1801 // While profile-sample-accurate is on, ignore symbol list. 1802 ProfAccForSymsInList = 1803 ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate; 1804 if (ProfAccForSymsInList) { 1805 NamesInProfile.clear(); 1806 if (auto NameTable = Reader->getNameTable()) 1807 NamesInProfile.insert(NameTable->begin(), NameTable->end()); 1808 CoverageTracker.setProfAccForSymsInList(true); 1809 } 1810 1811 if (FAM && !ProfileInlineReplayFile.empty()) { 1812 ExternalInlineAdvisor = std::make_unique<ReplayInlineAdvisor>( 1813 M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr, ProfileInlineReplayFile, 1814 /*EmitRemarks=*/false); 1815 if (!ExternalInlineAdvisor->areReplayRemarksLoaded()) 1816 ExternalInlineAdvisor.reset(); 1817 } 1818 1819 // Apply tweaks if context-sensitive profile is available. 1820 if (Reader->profileIsCS()) { 1821 ProfileIsCS = true; 1822 FunctionSamples::ProfileIsCS = true; 1823 1824 // Enable priority-base inliner and size inline by default for CSSPGO. 1825 if (!ProfileSizeInline.getNumOccurrences()) 1826 ProfileSizeInline = true; 1827 if (!CallsitePrioritizedInline.getNumOccurrences()) 1828 CallsitePrioritizedInline = true; 1829 1830 // Enable iterative-BFI by default for CSSPGO. 1831 if (!UseIterativeBFIInference.getNumOccurrences()) 1832 UseIterativeBFIInference = true; 1833 1834 // Tracker for profiles under different context 1835 ContextTracker = 1836 std::make_unique<SampleContextTracker>(Reader->getProfiles()); 1837 } 1838 1839 // Load pseudo probe descriptors for probe-based function samples. 1840 if (Reader->profileIsProbeBased()) { 1841 ProbeManager = std::make_unique<PseudoProbeManager>(M); 1842 if (!ProbeManager->moduleIsProbed(M)) { 1843 const char *Msg = 1844 "Pseudo-probe-based profile requires SampleProfileProbePass"; 1845 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg)); 1846 return false; 1847 } 1848 } 1849 1850 return true; 1851 } 1852 1853 ModulePass *llvm::createSampleProfileLoaderPass() { 1854 return new SampleProfileLoaderLegacyPass(); 1855 } 1856 1857 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) { 1858 return new SampleProfileLoaderLegacyPass(Name); 1859 } 1860 1861 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM, 1862 ProfileSummaryInfo *_PSI, CallGraph *CG) { 1863 GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap); 1864 1865 PSI = _PSI; 1866 if (M.getProfileSummary(/* IsCS */ false) == nullptr) { 1867 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()), 1868 ProfileSummary::PSK_Sample); 1869 PSI->refresh(); 1870 } 1871 // Compute the total number of samples collected in this profile. 1872 for (const auto &I : Reader->getProfiles()) 1873 TotalCollectedSamples += I.second.getTotalSamples(); 1874 1875 auto Remapper = Reader->getRemapper(); 1876 // Populate the symbol map. 1877 for (const auto &N_F : M.getValueSymbolTable()) { 1878 StringRef OrigName = N_F.getKey(); 1879 Function *F = dyn_cast<Function>(N_F.getValue()); 1880 if (F == nullptr || OrigName.empty()) 1881 continue; 1882 SymbolMap[OrigName] = F; 1883 StringRef NewName = FunctionSamples::getCanonicalFnName(*F); 1884 if (OrigName != NewName && !NewName.empty()) { 1885 auto r = SymbolMap.insert(std::make_pair(NewName, F)); 1886 // Failiing to insert means there is already an entry in SymbolMap, 1887 // thus there are multiple functions that are mapped to the same 1888 // stripped name. In this case of name conflicting, set the value 1889 // to nullptr to avoid confusion. 1890 if (!r.second) 1891 r.first->second = nullptr; 1892 OrigName = NewName; 1893 } 1894 // Insert the remapped names into SymbolMap. 1895 if (Remapper) { 1896 if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) { 1897 if (*MapName != OrigName && !MapName->empty()) 1898 SymbolMap.insert(std::make_pair(*MapName, F)); 1899 } 1900 } 1901 } 1902 assert(SymbolMap.count(StringRef()) == 0 && 1903 "No empty StringRef should be added in SymbolMap"); 1904 1905 bool retval = false; 1906 for (auto F : buildFunctionOrder(M, CG)) { 1907 assert(!F->isDeclaration()); 1908 clearFunctionData(); 1909 retval |= runOnFunction(*F, AM); 1910 } 1911 1912 // Account for cold calls not inlined.... 1913 if (!ProfileIsCS) 1914 for (const std::pair<Function *, NotInlinedProfileInfo> &pair : 1915 notInlinedCallInfo) 1916 updateProfileCallee(pair.first, pair.second.entryCount); 1917 1918 return retval; 1919 } 1920 1921 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) { 1922 ACT = &getAnalysis<AssumptionCacheTracker>(); 1923 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>(); 1924 TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>(); 1925 ProfileSummaryInfo *PSI = 1926 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 1927 return SampleLoader.runOnModule(M, nullptr, PSI, nullptr); 1928 } 1929 1930 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) { 1931 LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n"); 1932 DILocation2SampleMap.clear(); 1933 // By default the entry count is initialized to -1, which will be treated 1934 // conservatively by getEntryCount as the same as unknown (None). This is 1935 // to avoid newly added code to be treated as cold. If we have samples 1936 // this will be overwritten in emitAnnotations. 1937 uint64_t initialEntryCount = -1; 1938 1939 ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL; 1940 if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) { 1941 // initialize all the function entry counts to 0. It means all the 1942 // functions without profile will be regarded as cold. 1943 initialEntryCount = 0; 1944 // profile-sample-accurate is a user assertion which has a higher precedence 1945 // than symbol list. When profile-sample-accurate is on, ignore symbol list. 1946 ProfAccForSymsInList = false; 1947 } 1948 CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList); 1949 1950 // PSL -- profile symbol list include all the symbols in sampled binary. 1951 // If ProfileAccurateForSymsInList is enabled, PSL is used to treat 1952 // old functions without samples being cold, without having to worry 1953 // about new and hot functions being mistakenly treated as cold. 1954 if (ProfAccForSymsInList) { 1955 // Initialize the entry count to 0 for functions in the list. 1956 if (PSL->contains(F.getName())) 1957 initialEntryCount = 0; 1958 1959 // Function in the symbol list but without sample will be regarded as 1960 // cold. To minimize the potential negative performance impact it could 1961 // have, we want to be a little conservative here saying if a function 1962 // shows up in the profile, no matter as outline function, inline instance 1963 // or call targets, treat the function as not being cold. This will handle 1964 // the cases such as most callsites of a function are inlined in sampled 1965 // binary but not inlined in current build (because of source code drift, 1966 // imprecise debug information, or the callsites are all cold individually 1967 // but not cold accumulatively...), so the outline function showing up as 1968 // cold in sampled binary will actually not be cold after current build. 1969 StringRef CanonName = FunctionSamples::getCanonicalFnName(F); 1970 if (NamesInProfile.count(CanonName)) 1971 initialEntryCount = -1; 1972 } 1973 1974 // Initialize entry count when the function has no existing entry 1975 // count value. 1976 if (!F.getEntryCount().hasValue()) 1977 F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real)); 1978 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE; 1979 if (AM) { 1980 auto &FAM = 1981 AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent()) 1982 .getManager(); 1983 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1984 } else { 1985 OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F); 1986 ORE = OwnedORE.get(); 1987 } 1988 1989 if (ProfileIsCS) 1990 Samples = ContextTracker->getBaseSamplesFor(F); 1991 else 1992 Samples = Reader->getSamplesFor(F); 1993 1994 if (Samples && !Samples->empty()) 1995 return emitAnnotations(F); 1996 return false; 1997 } 1998 1999 PreservedAnalyses SampleProfileLoaderPass::run(Module &M, 2000 ModuleAnalysisManager &AM) { 2001 FunctionAnalysisManager &FAM = 2002 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2003 2004 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 2005 return FAM.getResult<AssumptionAnalysis>(F); 2006 }; 2007 auto GetTTI = [&](Function &F) -> TargetTransformInfo & { 2008 return FAM.getResult<TargetIRAnalysis>(F); 2009 }; 2010 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & { 2011 return FAM.getResult<TargetLibraryAnalysis>(F); 2012 }; 2013 2014 SampleProfileLoader SampleLoader( 2015 ProfileFileName.empty() ? SampleProfileFile : ProfileFileName, 2016 ProfileRemappingFileName.empty() ? SampleProfileRemappingFile 2017 : ProfileRemappingFileName, 2018 LTOPhase, GetAssumptionCache, GetTTI, GetTLI); 2019 2020 if (!SampleLoader.doInitialization(M, &FAM)) 2021 return PreservedAnalyses::all(); 2022 2023 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M); 2024 CallGraph &CG = AM.getResult<CallGraphAnalysis>(M); 2025 if (!SampleLoader.runOnModule(M, &AM, PSI, &CG)) 2026 return PreservedAnalyses::all(); 2027 2028 return PreservedAnalyses::none(); 2029 } 2030