1 //===- IndirectCallPromotion.cpp - Optimizations based on value profiling -===// 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 transformation that promotes indirect calls to 10 // conditional direct calls when the indirect-call value profile metadata is 11 // available. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/Analysis/IndirectCallPromotionAnalysis.h" 20 #include "llvm/Analysis/IndirectCallVisitor.h" 21 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 22 #include "llvm/Analysis/ProfileSummaryInfo.h" 23 #include "llvm/Analysis/TypeMetadataUtils.h" 24 #include "llvm/IR/DiagnosticInfo.h" 25 #include "llvm/IR/Dominators.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/InstrTypes.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/MDBuilder.h" 31 #include "llvm/IR/PassManager.h" 32 #include "llvm/IR/ProfDataUtils.h" 33 #include "llvm/IR/Value.h" 34 #include "llvm/ProfileData/InstrProf.h" 35 #include "llvm/Support/Casting.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/Error.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include "llvm/Transforms/Instrumentation.h" 41 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h" 42 #include "llvm/Transforms/Utils/CallPromotionUtils.h" 43 #include <cassert> 44 #include <cstdint> 45 #include <memory> 46 #include <set> 47 #include <string> 48 #include <utility> 49 #include <vector> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "pgo-icall-prom" 54 55 STATISTIC(NumOfPGOICallPromotion, "Number of indirect call promotions."); 56 STATISTIC(NumOfPGOICallsites, "Number of indirect call candidate sites."); 57 58 extern cl::opt<unsigned> MaxNumVTableAnnotations; 59 60 namespace llvm { 61 extern cl::opt<bool> EnableVTableProfileUse; 62 } 63 64 // Command line option to disable indirect-call promotion with the default as 65 // false. This is for debug purpose. 66 static cl::opt<bool> DisableICP("disable-icp", cl::init(false), cl::Hidden, 67 cl::desc("Disable indirect call promotion")); 68 69 // Set the cutoff value for the promotion. If the value is other than 0, we 70 // stop the transformation once the total number of promotions equals the cutoff 71 // value. 72 // For debug use only. 73 static cl::opt<unsigned> 74 ICPCutOff("icp-cutoff", cl::init(0), cl::Hidden, 75 cl::desc("Max number of promotions for this compilation")); 76 77 // If ICPCSSkip is non zero, the first ICPCSSkip callsites will be skipped. 78 // For debug use only. 79 static cl::opt<unsigned> 80 ICPCSSkip("icp-csskip", cl::init(0), cl::Hidden, 81 cl::desc("Skip Callsite up to this number for this compilation")); 82 83 // Set if the pass is called in LTO optimization. The difference for LTO mode 84 // is the pass won't prefix the source module name to the internal linkage 85 // symbols. 86 static cl::opt<bool> ICPLTOMode("icp-lto", cl::init(false), cl::Hidden, 87 cl::desc("Run indirect-call promotion in LTO " 88 "mode")); 89 90 // Set if the pass is called in SamplePGO mode. The difference for SamplePGO 91 // mode is it will add prof metadatato the created direct call. 92 static cl::opt<bool> 93 ICPSamplePGOMode("icp-samplepgo", cl::init(false), cl::Hidden, 94 cl::desc("Run indirect-call promotion in SamplePGO mode")); 95 96 // If the option is set to true, only call instructions will be considered for 97 // transformation -- invoke instructions will be ignored. 98 static cl::opt<bool> 99 ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden, 100 cl::desc("Run indirect-call promotion for call instructions " 101 "only")); 102 103 // If the option is set to true, only invoke instructions will be considered for 104 // transformation -- call instructions will be ignored. 105 static cl::opt<bool> ICPInvokeOnly("icp-invoke-only", cl::init(false), 106 cl::Hidden, 107 cl::desc("Run indirect-call promotion for " 108 "invoke instruction only")); 109 110 // Dump the function level IR if the transformation happened in this 111 // function. For debug use only. 112 static cl::opt<bool> 113 ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden, 114 cl::desc("Dump IR after transformation happens")); 115 116 // Indirect call promotion pass will fall back to function-based comparison if 117 // vtable-count / function-count is smaller than this threshold. 118 static cl::opt<float> ICPVTablePercentageThreshold( 119 "icp-vtable-percentage-threshold", cl::init(0.99), cl::Hidden, 120 cl::desc("The percentage threshold of vtable-count / function-count for " 121 "cost-benefit analysis.")); 122 123 // Although comparing vtables can save a vtable load, we may need to compare 124 // vtable pointer with multiple vtable address points due to class inheritance. 125 // Comparing with multiple vtables inserts additional instructions on hot code 126 // path, and doing so for an earlier candidate delays the comparisons for later 127 // candidates. For the last candidate, only the fallback path is affected. 128 // We allow multiple vtable comparison for the last function candidate and use 129 // the option below to cap the number of vtables. 130 static cl::opt<int> ICPMaxNumVTableLastCandidate( 131 "icp-max-num-vtable-last-candidate", cl::init(1), cl::Hidden, 132 cl::desc("The maximum number of vtable for the last candidate.")); 133 134 namespace { 135 136 // The key is a vtable global variable, and the value is a map. 137 // In the inner map, the key represents address point offsets and the value is a 138 // constant for this address point. 139 using VTableAddressPointOffsetValMap = 140 SmallDenseMap<const GlobalVariable *, std::unordered_map<int, Constant *>>; 141 142 // A struct to collect type information for a virtual call site. 143 struct VirtualCallSiteInfo { 144 // The offset from the address point to virtual function in the vtable. 145 uint64_t FunctionOffset; 146 // The instruction that computes the address point of vtable. 147 Instruction *VPtr; 148 // The compatible type used in LLVM type intrinsics. 149 StringRef CompatibleTypeStr; 150 }; 151 152 // The key is a virtual call, and value is its type information. 153 using VirtualCallSiteTypeInfoMap = 154 SmallDenseMap<const CallBase *, VirtualCallSiteInfo>; 155 156 // The key is vtable GUID, and value is its value profile count. 157 using VTableGUIDCountsMap = SmallDenseMap<uint64_t, uint64_t, 16>; 158 159 // Return the address point offset of the given compatible type. 160 // 161 // Type metadata of a vtable specifies the types that can contain a pointer to 162 // this vtable, for example, `Base*` can be a pointer to an derived type 163 // but not vice versa. See also https://llvm.org/docs/TypeMetadata.html 164 static std::optional<uint64_t> 165 getAddressPointOffset(const GlobalVariable &VTableVar, 166 StringRef CompatibleType) { 167 SmallVector<MDNode *> Types; 168 VTableVar.getMetadata(LLVMContext::MD_type, Types); 169 170 for (MDNode *Type : Types) 171 if (auto *TypeId = dyn_cast<MDString>(Type->getOperand(1).get()); 172 TypeId && TypeId->getString() == CompatibleType) 173 return cast<ConstantInt>( 174 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) 175 ->getZExtValue(); 176 177 return std::nullopt; 178 } 179 180 // Return a constant representing the vtable's address point specified by the 181 // offset. 182 static Constant *getVTableAddressPointOffset(GlobalVariable *VTable, 183 uint32_t AddressPointOffset) { 184 Module &M = *VTable->getParent(); 185 LLVMContext &Context = M.getContext(); 186 assert(AddressPointOffset < 187 M.getDataLayout().getTypeAllocSize(VTable->getValueType()) && 188 "Out-of-bound access"); 189 190 return ConstantExpr::getInBoundsGetElementPtr( 191 Type::getInt8Ty(Context), VTable, 192 llvm::ConstantInt::get(Type::getInt32Ty(Context), AddressPointOffset)); 193 } 194 195 // Return the basic block in which Use `U` is used via its `UserInst`. 196 static BasicBlock *getUserBasicBlock(Use &U, Instruction *UserInst) { 197 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 198 return PN->getIncomingBlock(U); 199 200 return UserInst->getParent(); 201 } 202 203 // `DestBB` is a suitable basic block to sink `Inst` into when `Inst` have users 204 // and all users are in `DestBB`. The caller guarantees that `Inst->getParent()` 205 // is the sole predecessor of `DestBB` and `DestBB` is dominated by 206 // `Inst->getParent()`. 207 static bool isDestBBSuitableForSink(Instruction *Inst, BasicBlock *DestBB) { 208 // 'BB' is used only by assert. 209 [[maybe_unused]] BasicBlock *BB = Inst->getParent(); 210 211 assert(BB != DestBB && BB->getTerminator()->getNumSuccessors() == 2 && 212 DestBB->getUniquePredecessor() == BB && 213 "Guaranteed by ICP transformation"); 214 215 BasicBlock *UserBB = nullptr; 216 for (Use &Use : Inst->uses()) { 217 User *User = Use.getUser(); 218 // Do checked cast since IR verifier guarantees that the user of an 219 // instruction must be an instruction. See `Verifier::visitInstruction`. 220 Instruction *UserInst = cast<Instruction>(User); 221 // We can sink debug or pseudo instructions together with Inst. 222 if (UserInst->isDebugOrPseudoInst()) 223 continue; 224 UserBB = getUserBasicBlock(Use, UserInst); 225 // Do not sink if Inst is used in a basic block that is not DestBB. 226 // TODO: Sink to the common dominator of all user blocks. 227 if (UserBB != DestBB) 228 return false; 229 } 230 return UserBB != nullptr; 231 } 232 233 // For the virtual call dispatch sequence, try to sink vtable load instructions 234 // to the cold indirect call fallback. 235 // FIXME: Move the sink eligibility check below to a utility function in 236 // Transforms/Utils/ directory. 237 static bool tryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 238 if (!isDestBBSuitableForSink(I, DestBlock)) 239 return false; 240 241 // Do not move control-flow-involving, volatile loads, vaarg, alloca 242 // instructions, etc. 243 if (isa<PHINode>(I) || I->isEHPad() || I->mayThrow() || !I->willReturn() || 244 isa<AllocaInst>(I)) 245 return false; 246 247 // Do not sink convergent call instructions. 248 if (const auto *C = dyn_cast<CallBase>(I)) 249 if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent()) 250 return false; 251 252 // Do not move an instruction that may write to memory. 253 if (I->mayWriteToMemory()) 254 return false; 255 256 // We can only sink load instructions if there is nothing between the load and 257 // the end of block that could change the value. 258 if (I->mayReadFromMemory()) { 259 // We already know that SrcBlock is the unique predecessor of DestBlock. 260 for (BasicBlock::iterator Scan = std::next(I->getIterator()), 261 E = I->getParent()->end(); 262 Scan != E; ++Scan) { 263 // Note analysis analysis can tell whether two pointers can point to the 264 // same object in memory or not thereby find further opportunities to 265 // sink. 266 if (Scan->mayWriteToMemory()) 267 return false; 268 } 269 } 270 271 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt(); 272 I->moveBefore(*DestBlock, InsertPos); 273 274 // TODO: Sink debug intrinsic users of I to 'DestBlock'. 275 // 'InstCombinerImpl::tryToSinkInstructionDbgValues' and 276 // 'InstCombinerImpl::tryToSinkInstructionDbgVariableRecords' already have 277 // the core logic to do this. 278 return true; 279 } 280 281 // Try to sink instructions after VPtr to the indirect call fallback. 282 // Return the number of sunk IR instructions. 283 static int tryToSinkInstructions(BasicBlock *OriginalBB, 284 BasicBlock *IndirectCallBB) { 285 int SinkCount = 0; 286 // Do not sink across a critical edge for simplicity. 287 if (IndirectCallBB->getUniquePredecessor() != OriginalBB) 288 return SinkCount; 289 // Sink all eligible instructions in OriginalBB in reverse order. 290 for (Instruction &I : 291 llvm::make_early_inc_range(llvm::drop_begin(llvm::reverse(*OriginalBB)))) 292 if (tryToSinkInstruction(&I, IndirectCallBB)) 293 SinkCount++; 294 295 return SinkCount; 296 } 297 298 // Promote indirect calls to conditional direct calls, keeping track of 299 // thresholds. 300 class IndirectCallPromoter { 301 private: 302 Function &F; 303 Module &M; 304 305 ProfileSummaryInfo *PSI = nullptr; 306 307 // Symtab that maps indirect call profile values to function names and 308 // defines. 309 InstrProfSymtab *const Symtab; 310 311 const bool SamplePGO; 312 313 // A map from a virtual call to its type information. 314 const VirtualCallSiteTypeInfoMap &VirtualCSInfo; 315 316 VTableAddressPointOffsetValMap &VTableAddressPointOffsetVal; 317 318 OptimizationRemarkEmitter &ORE; 319 320 // A struct that records the direct target and it's call count. 321 struct PromotionCandidate { 322 Function *const TargetFunction; 323 const uint64_t Count; 324 325 // The following fields only exists for promotion candidates with vtable 326 // information. 327 // 328 // Due to class inheritance, one virtual call candidate can come from 329 // multiple vtables. `VTableGUIDAndCounts` tracks the vtable GUIDs and 330 // counts for 'TargetFunction'. `AddressPoints` stores the vtable address 331 // points for comparison. 332 VTableGUIDCountsMap VTableGUIDAndCounts; 333 SmallVector<Constant *> AddressPoints; 334 335 PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {} 336 }; 337 338 // Check if the indirect-call call site should be promoted. Return the number 339 // of promotions. Inst is the candidate indirect call, ValueDataRef 340 // contains the array of value profile data for profiled targets, 341 // TotalCount is the total profiled count of call executions, and 342 // NumCandidates is the number of candidate entries in ValueDataRef. 343 std::vector<PromotionCandidate> getPromotionCandidatesForCallSite( 344 const CallBase &CB, ArrayRef<InstrProfValueData> ValueDataRef, 345 uint64_t TotalCount, uint32_t NumCandidates); 346 347 // Promote a list of targets for one indirect-call callsite by comparing 348 // indirect callee with functions. Return true if there are IR 349 // transformations and false otherwise. 350 bool tryToPromoteWithFuncCmp(CallBase &CB, Instruction *VPtr, 351 ArrayRef<PromotionCandidate> Candidates, 352 uint64_t TotalCount, 353 ArrayRef<InstrProfValueData> ICallProfDataRef, 354 uint32_t NumCandidates, 355 VTableGUIDCountsMap &VTableGUIDCounts); 356 357 // Promote a list of targets for one indirect call by comparing vtables with 358 // functions. Return true if there are IR transformations and false 359 // otherwise. 360 bool tryToPromoteWithVTableCmp( 361 CallBase &CB, Instruction *VPtr, 362 const std::vector<PromotionCandidate> &Candidates, 363 uint64_t TotalFuncCount, uint32_t NumCandidates, 364 MutableArrayRef<InstrProfValueData> ICallProfDataRef, 365 VTableGUIDCountsMap &VTableGUIDCounts); 366 367 // Return true if it's profitable to compare vtables for the callsite. 368 bool isProfitableToCompareVTables( 369 const CallBase &CB, const std::vector<PromotionCandidate> &Candidates, 370 uint64_t TotalCount); 371 372 // Given an indirect callsite and the list of function candidates, compute 373 // the following vtable information in output parameters and return vtable 374 // pointer if type profiles exist. 375 // - Populate `VTableGUIDCounts` with <vtable-guid, count> using !prof 376 // metadata attached on the vtable pointer. 377 // - For each function candidate, finds out the vtables from which it gets 378 // called and stores the <vtable-guid, count> in promotion candidate. 379 Instruction *computeVTableInfos(const CallBase *CB, 380 VTableGUIDCountsMap &VTableGUIDCounts, 381 std::vector<PromotionCandidate> &Candidates); 382 383 Constant *getOrCreateVTableAddressPointVar(GlobalVariable *GV, 384 uint64_t AddressPointOffset); 385 386 void updateFuncValueProfiles(CallBase &CB, ArrayRef<InstrProfValueData> VDs, 387 uint64_t Sum, uint32_t MaxMDCount); 388 389 void updateVPtrValueProfiles(Instruction *VPtr, 390 VTableGUIDCountsMap &VTableGUIDCounts); 391 392 public: 393 IndirectCallPromoter( 394 Function &Func, Module &M, ProfileSummaryInfo *PSI, 395 InstrProfSymtab *Symtab, bool SamplePGO, 396 const VirtualCallSiteTypeInfoMap &VirtualCSInfo, 397 VTableAddressPointOffsetValMap &VTableAddressPointOffsetVal, 398 OptimizationRemarkEmitter &ORE) 399 : F(Func), M(M), PSI(PSI), Symtab(Symtab), SamplePGO(SamplePGO), 400 VirtualCSInfo(VirtualCSInfo), 401 VTableAddressPointOffsetVal(VTableAddressPointOffsetVal), ORE(ORE) {} 402 IndirectCallPromoter(const IndirectCallPromoter &) = delete; 403 IndirectCallPromoter &operator=(const IndirectCallPromoter &) = delete; 404 405 bool processFunction(ProfileSummaryInfo *PSI); 406 }; 407 408 } // end anonymous namespace 409 410 // Indirect-call promotion heuristic. The direct targets are sorted based on 411 // the count. Stop at the first target that is not promoted. 412 std::vector<IndirectCallPromoter::PromotionCandidate> 413 IndirectCallPromoter::getPromotionCandidatesForCallSite( 414 const CallBase &CB, ArrayRef<InstrProfValueData> ValueDataRef, 415 uint64_t TotalCount, uint32_t NumCandidates) { 416 std::vector<PromotionCandidate> Ret; 417 418 LLVM_DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << CB 419 << " Num_targets: " << ValueDataRef.size() 420 << " Num_candidates: " << NumCandidates << "\n"); 421 NumOfPGOICallsites++; 422 if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) { 423 LLVM_DEBUG(dbgs() << " Skip: User options.\n"); 424 return Ret; 425 } 426 427 for (uint32_t I = 0; I < NumCandidates; I++) { 428 uint64_t Count = ValueDataRef[I].Count; 429 assert(Count <= TotalCount); 430 (void)TotalCount; 431 uint64_t Target = ValueDataRef[I].Value; 432 LLVM_DEBUG(dbgs() << " Candidate " << I << " Count=" << Count 433 << " Target_func: " << Target << "\n"); 434 435 if (ICPInvokeOnly && isa<CallInst>(CB)) { 436 LLVM_DEBUG(dbgs() << " Not promote: User options.\n"); 437 ORE.emit([&]() { 438 return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB) 439 << " Not promote: User options"; 440 }); 441 break; 442 } 443 if (ICPCallOnly && isa<InvokeInst>(CB)) { 444 LLVM_DEBUG(dbgs() << " Not promote: User option.\n"); 445 ORE.emit([&]() { 446 return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB) 447 << " Not promote: User options"; 448 }); 449 break; 450 } 451 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) { 452 LLVM_DEBUG(dbgs() << " Not promote: Cutoff reached.\n"); 453 ORE.emit([&]() { 454 return OptimizationRemarkMissed(DEBUG_TYPE, "CutOffReached", &CB) 455 << " Not promote: Cutoff reached"; 456 }); 457 break; 458 } 459 460 // Don't promote if the symbol is not defined in the module. This avoids 461 // creating a reference to a symbol that doesn't exist in the module 462 // This can happen when we compile with a sample profile collected from 463 // one binary but used for another, which may have profiled targets that 464 // aren't used in the new binary. We might have a declaration initially in 465 // the case where the symbol is globally dead in the binary and removed by 466 // ThinLTO. 467 Function *TargetFunction = Symtab->getFunction(Target); 468 if (TargetFunction == nullptr || TargetFunction->isDeclaration()) { 469 LLVM_DEBUG(dbgs() << " Not promote: Cannot find the target\n"); 470 ORE.emit([&]() { 471 return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToFindTarget", &CB) 472 << "Cannot promote indirect call: target with md5sum " 473 << ore::NV("target md5sum", Target) << " not found"; 474 }); 475 break; 476 } 477 478 const char *Reason = nullptr; 479 if (!isLegalToPromote(CB, TargetFunction, &Reason)) { 480 using namespace ore; 481 482 ORE.emit([&]() { 483 return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToPromote", &CB) 484 << "Cannot promote indirect call to " 485 << NV("TargetFunction", TargetFunction) << " with count of " 486 << NV("Count", Count) << ": " << Reason; 487 }); 488 break; 489 } 490 491 Ret.push_back(PromotionCandidate(TargetFunction, Count)); 492 TotalCount -= Count; 493 } 494 return Ret; 495 } 496 497 Constant *IndirectCallPromoter::getOrCreateVTableAddressPointVar( 498 GlobalVariable *GV, uint64_t AddressPointOffset) { 499 auto [Iter, Inserted] = 500 VTableAddressPointOffsetVal[GV].try_emplace(AddressPointOffset, nullptr); 501 if (Inserted) 502 Iter->second = getVTableAddressPointOffset(GV, AddressPointOffset); 503 return Iter->second; 504 } 505 506 Instruction *IndirectCallPromoter::computeVTableInfos( 507 const CallBase *CB, VTableGUIDCountsMap &GUIDCountsMap, 508 std::vector<PromotionCandidate> &Candidates) { 509 if (!EnableVTableProfileUse) 510 return nullptr; 511 512 // Take the following code sequence as an example, here is how the code works 513 // @vtable1 = {[n x ptr] [... ptr @func1]} 514 // @vtable2 = {[m x ptr] [... ptr @func2]} 515 // 516 // %vptr = load ptr, ptr %d, !prof !0 517 // %0 = tail call i1 @llvm.type.test(ptr %vptr, metadata !"vtable1") 518 // tail call void @llvm.assume(i1 %0) 519 // %vfn = getelementptr inbounds ptr, ptr %vptr, i64 1 520 // %1 = load ptr, ptr %vfn 521 // call void %1(ptr %d), !prof !1 522 // 523 // !0 = !{!"VP", i32 2, i64 100, i64 123, i64 50, i64 456, i64 50} 524 // !1 = !{!"VP", i32 0, i64 100, i64 789, i64 50, i64 579, i64 50} 525 // 526 // Step 1. Find out the %vptr instruction for indirect call and use its !prof 527 // to populate `GUIDCountsMap`. 528 // Step 2. For each vtable-guid, look up its definition from symtab. LTO can 529 // make vtable definitions visible across modules. 530 // Step 3. Compute the byte offset of the virtual call, by adding vtable 531 // address point offset and function's offset relative to vtable address 532 // point. For each function candidate, this step tells us the vtable from 533 // which it comes from, and the vtable address point to compare %vptr with. 534 535 // Only virtual calls have virtual call site info. 536 auto Iter = VirtualCSInfo.find(CB); 537 if (Iter == VirtualCSInfo.end()) 538 return nullptr; 539 540 LLVM_DEBUG(dbgs() << "\nComputing vtable infos for callsite #" 541 << NumOfPGOICallsites << "\n"); 542 543 const auto &VirtualCallInfo = Iter->second; 544 Instruction *VPtr = VirtualCallInfo.VPtr; 545 546 SmallDenseMap<Function *, int, 4> CalleeIndexMap; 547 for (size_t I = 0; I < Candidates.size(); I++) 548 CalleeIndexMap[Candidates[I].TargetFunction] = I; 549 550 uint32_t ActualNumValueData = 0; 551 uint64_t TotalVTableCount = 0; 552 auto VTableValueDataArray = getValueProfDataFromInst( 553 *VirtualCallInfo.VPtr, IPVK_VTableTarget, MaxNumVTableAnnotations, 554 ActualNumValueData, TotalVTableCount); 555 if (VTableValueDataArray.get() == nullptr) 556 return VPtr; 557 558 // Compute the functions and counts from by each vtable. 559 for (size_t j = 0; j < ActualNumValueData; j++) { 560 uint64_t VTableVal = VTableValueDataArray[j].Value; 561 GUIDCountsMap[VTableVal] = VTableValueDataArray[j].Count; 562 GlobalVariable *VTableVar = Symtab->getGlobalVariable(VTableVal); 563 if (!VTableVar) { 564 LLVM_DEBUG(dbgs() << " Cannot find vtable definition for " << VTableVal 565 << "; maybe the vtable isn't imported\n"); 566 continue; 567 } 568 569 std::optional<uint64_t> MaybeAddressPointOffset = 570 getAddressPointOffset(*VTableVar, VirtualCallInfo.CompatibleTypeStr); 571 if (!MaybeAddressPointOffset) 572 continue; 573 574 const uint64_t AddressPointOffset = *MaybeAddressPointOffset; 575 576 Function *Callee = nullptr; 577 std::tie(Callee, std::ignore) = getFunctionAtVTableOffset( 578 VTableVar, AddressPointOffset + VirtualCallInfo.FunctionOffset, M); 579 if (!Callee) 580 continue; 581 auto CalleeIndexIter = CalleeIndexMap.find(Callee); 582 if (CalleeIndexIter == CalleeIndexMap.end()) 583 continue; 584 585 auto &Candidate = Candidates[CalleeIndexIter->second]; 586 // There shouldn't be duplicate GUIDs in one !prof metadata (except 587 // duplicated zeros), so assign counters directly won't cause overwrite or 588 // counter loss. 589 Candidate.VTableGUIDAndCounts[VTableVal] = VTableValueDataArray[j].Count; 590 Candidate.AddressPoints.push_back( 591 getOrCreateVTableAddressPointVar(VTableVar, AddressPointOffset)); 592 } 593 594 return VPtr; 595 } 596 597 // Creates 'branch_weights' prof metadata using TrueWeight and FalseWeight. 598 // Scales uint64_t counters down to uint32_t if necessary to prevent overflow. 599 static MDNode *createBranchWeights(LLVMContext &Context, uint64_t TrueWeight, 600 uint64_t FalseWeight) { 601 MDBuilder MDB(Context); 602 uint64_t Scale = calculateCountScale(std::max(TrueWeight, FalseWeight)); 603 return MDB.createBranchWeights(scaleBranchCount(TrueWeight, Scale), 604 scaleBranchCount(FalseWeight, Scale)); 605 } 606 607 CallBase &llvm::pgo::promoteIndirectCall(CallBase &CB, Function *DirectCallee, 608 uint64_t Count, uint64_t TotalCount, 609 bool AttachProfToDirectCall, 610 OptimizationRemarkEmitter *ORE) { 611 CallBase &NewInst = promoteCallWithIfThenElse( 612 CB, DirectCallee, 613 createBranchWeights(CB.getContext(), Count, TotalCount - Count)); 614 615 if (AttachProfToDirectCall) 616 setBranchWeights(NewInst, {static_cast<uint32_t>(Count)}, 617 /*IsExpected=*/false); 618 619 using namespace ore; 620 621 if (ORE) 622 ORE->emit([&]() { 623 return OptimizationRemark(DEBUG_TYPE, "Promoted", &CB) 624 << "Promote indirect call to " << NV("DirectCallee", DirectCallee) 625 << " with count " << NV("Count", Count) << " out of " 626 << NV("TotalCount", TotalCount); 627 }); 628 return NewInst; 629 } 630 631 // Promote indirect-call to conditional direct-call for one callsite. 632 bool IndirectCallPromoter::tryToPromoteWithFuncCmp( 633 CallBase &CB, Instruction *VPtr, ArrayRef<PromotionCandidate> Candidates, 634 uint64_t TotalCount, ArrayRef<InstrProfValueData> ICallProfDataRef, 635 uint32_t NumCandidates, VTableGUIDCountsMap &VTableGUIDCounts) { 636 uint32_t NumPromoted = 0; 637 638 for (const auto &C : Candidates) { 639 uint64_t FuncCount = C.Count; 640 pgo::promoteIndirectCall(CB, C.TargetFunction, FuncCount, TotalCount, 641 SamplePGO, &ORE); 642 assert(TotalCount >= FuncCount); 643 TotalCount -= FuncCount; 644 NumOfPGOICallPromotion++; 645 NumPromoted++; 646 647 if (!EnableVTableProfileUse || C.VTableGUIDAndCounts.empty()) 648 continue; 649 650 // After a virtual call candidate gets promoted, update the vtable's counts 651 // proportionally. Each vtable-guid in `C.VTableGUIDAndCounts` represents 652 // a vtable from which the virtual call is loaded. Compute the sum and use 653 // 128-bit APInt to improve accuracy. 654 uint64_t SumVTableCount = 0; 655 for (const auto &[GUID, VTableCount] : C.VTableGUIDAndCounts) 656 SumVTableCount += VTableCount; 657 658 for (const auto &[GUID, VTableCount] : C.VTableGUIDAndCounts) { 659 APInt APFuncCount((unsigned)128, FuncCount, false /*signed*/); 660 APFuncCount *= VTableCount; 661 VTableGUIDCounts[GUID] -= APFuncCount.udiv(SumVTableCount).getZExtValue(); 662 } 663 } 664 if (NumPromoted == 0) 665 return false; 666 667 assert(NumPromoted <= ICallProfDataRef.size() && 668 "Number of promoted functions should not be greater than the number " 669 "of values in profile metadata"); 670 671 // Update value profiles on the indirect call. 672 updateFuncValueProfiles(CB, ICallProfDataRef.slice(NumPromoted), TotalCount, 673 NumCandidates); 674 updateVPtrValueProfiles(VPtr, VTableGUIDCounts); 675 return true; 676 } 677 678 void IndirectCallPromoter::updateFuncValueProfiles( 679 CallBase &CB, ArrayRef<InstrProfValueData> CallVDs, uint64_t TotalCount, 680 uint32_t MaxMDCount) { 681 // First clear the existing !prof. 682 CB.setMetadata(LLVMContext::MD_prof, nullptr); 683 // Annotate the remaining value profiles if counter is not zero. 684 if (TotalCount != 0) 685 annotateValueSite(M, CB, CallVDs, TotalCount, IPVK_IndirectCallTarget, 686 MaxMDCount); 687 } 688 689 void IndirectCallPromoter::updateVPtrValueProfiles( 690 Instruction *VPtr, VTableGUIDCountsMap &VTableGUIDCounts) { 691 if (!EnableVTableProfileUse || VPtr == nullptr || 692 !VPtr->getMetadata(LLVMContext::MD_prof)) 693 return; 694 VPtr->setMetadata(LLVMContext::MD_prof, nullptr); 695 std::vector<InstrProfValueData> VTableValueProfiles; 696 uint64_t TotalVTableCount = 0; 697 for (auto [GUID, Count] : VTableGUIDCounts) { 698 if (Count == 0) 699 continue; 700 701 VTableValueProfiles.push_back({GUID, Count}); 702 TotalVTableCount += Count; 703 } 704 llvm::sort(VTableValueProfiles, 705 [](const InstrProfValueData &LHS, const InstrProfValueData &RHS) { 706 return LHS.Count > RHS.Count; 707 }); 708 709 annotateValueSite(M, *VPtr, VTableValueProfiles, TotalVTableCount, 710 IPVK_VTableTarget, VTableValueProfiles.size()); 711 } 712 713 bool IndirectCallPromoter::tryToPromoteWithVTableCmp( 714 CallBase &CB, Instruction *VPtr, 715 const std::vector<PromotionCandidate> &Candidates, uint64_t TotalFuncCount, 716 uint32_t NumCandidates, 717 MutableArrayRef<InstrProfValueData> ICallProfDataRef, 718 VTableGUIDCountsMap &VTableGUIDCounts) { 719 SmallVector<uint64_t, 4> PromotedFuncCount; 720 721 for (const auto &Candidate : Candidates) { 722 for (auto &[GUID, Count] : Candidate.VTableGUIDAndCounts) 723 VTableGUIDCounts[GUID] -= Count; 724 725 // 'OriginalBB' is the basic block of indirect call. After each candidate 726 // is promoted, a new basic block is created for the indirect fallback basic 727 // block and indirect call `CB` is moved into this new BB. 728 BasicBlock *OriginalBB = CB.getParent(); 729 promoteCallWithVTableCmp( 730 CB, VPtr, Candidate.TargetFunction, Candidate.AddressPoints, 731 createBranchWeights(CB.getContext(), Candidate.Count, 732 TotalFuncCount - Candidate.Count)); 733 734 int SinkCount = tryToSinkInstructions(OriginalBB, CB.getParent()); 735 736 ORE.emit([&]() { 737 OptimizationRemark Remark(DEBUG_TYPE, "Promoted", &CB); 738 739 const auto &VTableGUIDAndCounts = Candidate.VTableGUIDAndCounts; 740 Remark << "Promote indirect call to " 741 << ore::NV("DirectCallee", Candidate.TargetFunction) 742 << " with count " << ore::NV("Count", Candidate.Count) 743 << " out of " << ore::NV("TotalCount", TotalFuncCount) << ", sink " 744 << ore::NV("SinkCount", SinkCount) 745 << " instruction(s) and compare " 746 << ore::NV("VTable", VTableGUIDAndCounts.size()) 747 << " vtable(s): {"; 748 749 // Sort GUIDs so remark message is deterministic. 750 std::set<uint64_t> GUIDSet; 751 for (auto [GUID, Count] : VTableGUIDAndCounts) 752 GUIDSet.insert(GUID); 753 for (auto Iter = GUIDSet.begin(); Iter != GUIDSet.end(); Iter++) { 754 if (Iter != GUIDSet.begin()) 755 Remark << ", "; 756 Remark << ore::NV("VTable", Symtab->getGlobalVariable(*Iter)); 757 } 758 759 Remark << "}"; 760 761 return Remark; 762 }); 763 764 PromotedFuncCount.push_back(Candidate.Count); 765 766 assert(TotalFuncCount >= Candidate.Count && 767 "Within one prof metadata, total count is the sum of counts from " 768 "individual <target, count> pairs"); 769 // Use std::min since 'TotalFuncCount' is the saturated sum of individual 770 // counts, see 771 // https://github.com/llvm/llvm-project/blob/abedb3b8356d5d56f1c575c4f7682fba2cb19787/llvm/lib/ProfileData/InstrProf.cpp#L1281-L1288 772 TotalFuncCount -= std::min(TotalFuncCount, Candidate.Count); 773 NumOfPGOICallPromotion++; 774 } 775 776 if (PromotedFuncCount.empty()) 777 return false; 778 779 // Update value profiles for 'CB' and 'VPtr', assuming that each 'CB' has a 780 // a distinct 'VPtr'. 781 // FIXME: When Clang `-fstrict-vtable-pointers` is enabled, a vtable might be 782 // used to load multiple virtual functions. The vtable profiles needs to be 783 // updated properly in that case (e.g, for each indirect call annotate both 784 // type profiles and function profiles in one !prof). 785 for (size_t I = 0; I < PromotedFuncCount.size(); I++) 786 ICallProfDataRef[I].Count -= 787 std::max(PromotedFuncCount[I], ICallProfDataRef[I].Count); 788 // Sort value profiles by count in descending order. 789 llvm::stable_sort(ICallProfDataRef, [](const InstrProfValueData &LHS, 790 const InstrProfValueData &RHS) { 791 return LHS.Count > RHS.Count; 792 }); 793 // Drop the <target-value, count> pair if count is zero. 794 ArrayRef<InstrProfValueData> VDs( 795 ICallProfDataRef.begin(), 796 llvm::upper_bound(ICallProfDataRef, 0U, 797 [](uint64_t Count, const InstrProfValueData &ProfData) { 798 return ProfData.Count <= Count; 799 })); 800 updateFuncValueProfiles(CB, VDs, TotalFuncCount, NumCandidates); 801 updateVPtrValueProfiles(VPtr, VTableGUIDCounts); 802 return true; 803 } 804 805 // Traverse all the indirect-call callsite and get the value profile 806 // annotation to perform indirect-call promotion. 807 bool IndirectCallPromoter::processFunction(ProfileSummaryInfo *PSI) { 808 bool Changed = false; 809 ICallPromotionAnalysis ICallAnalysis; 810 for (auto *CB : findIndirectCalls(F)) { 811 uint32_t NumCandidates; 812 uint64_t TotalCount; 813 auto ICallProfDataRef = ICallAnalysis.getPromotionCandidatesForInstruction( 814 CB, TotalCount, NumCandidates); 815 if (!NumCandidates || 816 (PSI && PSI->hasProfileSummary() && !PSI->isHotCount(TotalCount))) 817 continue; 818 819 auto PromotionCandidates = getPromotionCandidatesForCallSite( 820 *CB, ICallProfDataRef, TotalCount, NumCandidates); 821 822 VTableGUIDCountsMap VTableGUIDCounts; 823 Instruction *VPtr = 824 computeVTableInfos(CB, VTableGUIDCounts, PromotionCandidates); 825 826 if (isProfitableToCompareVTables(*CB, PromotionCandidates, TotalCount)) 827 Changed |= tryToPromoteWithVTableCmp(*CB, VPtr, PromotionCandidates, 828 TotalCount, NumCandidates, 829 ICallProfDataRef, VTableGUIDCounts); 830 else 831 Changed |= tryToPromoteWithFuncCmp(*CB, VPtr, PromotionCandidates, 832 TotalCount, ICallProfDataRef, 833 NumCandidates, VTableGUIDCounts); 834 } 835 return Changed; 836 } 837 838 // TODO: Return false if the function addressing and vtable load instructions 839 // cannot sink to indirect fallback. 840 bool IndirectCallPromoter::isProfitableToCompareVTables( 841 const CallBase &CB, const std::vector<PromotionCandidate> &Candidates, 842 uint64_t TotalCount) { 843 if (!EnableVTableProfileUse || Candidates.empty()) 844 return false; 845 LLVM_DEBUG(dbgs() << "\nEvaluating vtable profitability for callsite #" 846 << NumOfPGOICallsites << CB << "\n"); 847 uint64_t RemainingVTableCount = TotalCount; 848 const size_t CandidateSize = Candidates.size(); 849 for (size_t I = 0; I < CandidateSize; I++) { 850 auto &Candidate = Candidates[I]; 851 auto &VTableGUIDAndCounts = Candidate.VTableGUIDAndCounts; 852 853 LLVM_DEBUG(dbgs() << " Candidate " << I << " FunctionCount: " 854 << Candidate.Count << ", VTableCounts:"); 855 // Add [[maybe_unused]] since <GUID, Count> are only used by LLVM_DEBUG. 856 for ([[maybe_unused]] auto &[GUID, Count] : VTableGUIDAndCounts) 857 LLVM_DEBUG(dbgs() << " {" << Symtab->getGlobalVariable(GUID)->getName() 858 << ", " << Count << "}"); 859 LLVM_DEBUG(dbgs() << "\n"); 860 861 uint64_t CandidateVTableCount = 0; 862 for (auto &[GUID, Count] : VTableGUIDAndCounts) 863 CandidateVTableCount += Count; 864 865 if (CandidateVTableCount < Candidate.Count * ICPVTablePercentageThreshold) { 866 LLVM_DEBUG( 867 dbgs() << " function count " << Candidate.Count 868 << " and its vtable sum count " << CandidateVTableCount 869 << " have discrepancies. Bail out vtable comparison.\n"); 870 return false; 871 } 872 873 RemainingVTableCount -= Candidate.Count; 874 875 // 'MaxNumVTable' limits the number of vtables to make vtable comparison 876 // profitable. Comparing multiple vtables for one function candidate will 877 // insert additional instructions on the hot path, and allowing more than 878 // one vtable for non last candidates may or may not elongate the dependency 879 // chain for the subsequent candidates. Set its value to 1 for non-last 880 // candidate and allow option to override it for the last candidate. 881 int MaxNumVTable = 1; 882 if (I == CandidateSize - 1) 883 MaxNumVTable = ICPMaxNumVTableLastCandidate; 884 885 if ((int)Candidate.AddressPoints.size() > MaxNumVTable) { 886 LLVM_DEBUG(dbgs() << " allow at most " << MaxNumVTable << " and got " 887 << Candidate.AddressPoints.size() 888 << " vtables. Bail out for vtable comparison.\n"); 889 return false; 890 } 891 } 892 893 // If the indirect fallback is not cold, don't compare vtables. 894 if (PSI && PSI->hasProfileSummary() && 895 !PSI->isColdCount(RemainingVTableCount)) { 896 LLVM_DEBUG(dbgs() << " Indirect fallback basic block is not cold. Bail " 897 "out for vtable comparison.\n"); 898 return false; 899 } 900 901 return true; 902 } 903 904 // For virtual calls in the module, collect per-callsite information which will 905 // be used to associate an ICP candidate with a vtable and a specific function 906 // in the vtable. With type intrinsics (llvm.type.test), we can find virtual 907 // calls in a compile-time efficient manner (by iterating its users) and more 908 // importantly use the compatible type later to figure out the function byte 909 // offset relative to the start of vtables. 910 static void 911 computeVirtualCallSiteTypeInfoMap(Module &M, ModuleAnalysisManager &MAM, 912 VirtualCallSiteTypeInfoMap &VirtualCSInfo) { 913 // Right now only llvm.type.test is used to find out virtual call sites. 914 // With ThinLTO and whole-program-devirtualization, llvm.type.test and 915 // llvm.public.type.test are emitted, and llvm.public.type.test is either 916 // refined to llvm.type.test or dropped before indirect-call-promotion pass. 917 // 918 // FIXME: For fullLTO with VFE, `llvm.type.checked.load intrinsic` is emitted. 919 // Find out virtual calls by looking at users of llvm.type.checked.load in 920 // that case. 921 Function *TypeTestFunc = 922 M.getFunction(Intrinsic::getName(Intrinsic::type_test)); 923 if (!TypeTestFunc || TypeTestFunc->use_empty()) 924 return; 925 926 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 927 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & { 928 return FAM.getResult<DominatorTreeAnalysis>(F); 929 }; 930 // Iterate all type.test calls to find all indirect calls. 931 for (Use &U : llvm::make_early_inc_range(TypeTestFunc->uses())) { 932 auto *CI = dyn_cast<CallInst>(U.getUser()); 933 if (!CI) 934 continue; 935 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1)); 936 if (!TypeMDVal) 937 continue; 938 auto *CompatibleTypeId = dyn_cast<MDString>(TypeMDVal->getMetadata()); 939 if (!CompatibleTypeId) 940 continue; 941 942 // Find out all devirtualizable call sites given a llvm.type.test 943 // intrinsic call. 944 SmallVector<DevirtCallSite, 1> DevirtCalls; 945 SmallVector<CallInst *, 1> Assumes; 946 auto &DT = LookupDomTree(*CI->getFunction()); 947 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT); 948 949 for (auto &DevirtCall : DevirtCalls) { 950 CallBase &CB = DevirtCall.CB; 951 // Given an indirect call, try find the instruction which loads a 952 // pointer to virtual table. 953 Instruction *VTablePtr = 954 PGOIndirectCallVisitor::tryGetVTableInstruction(&CB); 955 if (!VTablePtr) 956 continue; 957 VirtualCSInfo[&CB] = {DevirtCall.Offset, VTablePtr, 958 CompatibleTypeId->getString()}; 959 } 960 } 961 } 962 963 // A wrapper function that does the actual work. 964 static bool promoteIndirectCalls(Module &M, ProfileSummaryInfo *PSI, bool InLTO, 965 bool SamplePGO, ModuleAnalysisManager &MAM) { 966 if (DisableICP) 967 return false; 968 InstrProfSymtab Symtab; 969 if (Error E = Symtab.create(M, InLTO)) { 970 std::string SymtabFailure = toString(std::move(E)); 971 M.getContext().emitError("Failed to create symtab: " + SymtabFailure); 972 return false; 973 } 974 bool Changed = false; 975 VirtualCallSiteTypeInfoMap VirtualCSInfo; 976 977 if (EnableVTableProfileUse) 978 computeVirtualCallSiteTypeInfoMap(M, MAM, VirtualCSInfo); 979 980 // VTableAddressPointOffsetVal stores the vtable address points. The vtable 981 // address point of a given <vtable, address point offset> is static (doesn't 982 // change after being computed once). 983 // IndirectCallPromoter::getOrCreateVTableAddressPointVar creates the map 984 // entry the first time a <vtable, offset> pair is seen, as 985 // promoteIndirectCalls processes an IR module and calls IndirectCallPromoter 986 // repeatedly on each function. 987 VTableAddressPointOffsetValMap VTableAddressPointOffsetVal; 988 989 for (auto &F : M) { 990 if (F.isDeclaration() || F.hasOptNone()) 991 continue; 992 993 auto &FAM = 994 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 995 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 996 997 IndirectCallPromoter CallPromoter(F, M, PSI, &Symtab, SamplePGO, 998 VirtualCSInfo, 999 VTableAddressPointOffsetVal, ORE); 1000 bool FuncChanged = CallPromoter.processFunction(PSI); 1001 if (ICPDUMPAFTER && FuncChanged) { 1002 LLVM_DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs())); 1003 LLVM_DEBUG(dbgs() << "\n"); 1004 } 1005 Changed |= FuncChanged; 1006 if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) { 1007 LLVM_DEBUG(dbgs() << " Stop: Cutoff reached.\n"); 1008 break; 1009 } 1010 } 1011 return Changed; 1012 } 1013 1014 PreservedAnalyses PGOIndirectCallPromotion::run(Module &M, 1015 ModuleAnalysisManager &MAM) { 1016 ProfileSummaryInfo *PSI = &MAM.getResult<ProfileSummaryAnalysis>(M); 1017 1018 if (!promoteIndirectCalls(M, PSI, InLTO | ICPLTOMode, 1019 SamplePGO | ICPSamplePGOMode, MAM)) 1020 return PreservedAnalyses::all(); 1021 1022 return PreservedAnalyses::none(); 1023 } 1024