1 //===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===// 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 pass implements whole program optimization of virtual calls in cases 10 // where we know (via !type metadata) that the list of callees is fixed. This 11 // includes the following: 12 // - Single implementation devirtualization: if a virtual call has a single 13 // possible callee, replace all calls with a direct call to that callee. 14 // - Virtual constant propagation: if the virtual function's return type is an 15 // integer <=64 bits and all possible callees are readnone, for each class and 16 // each list of constant arguments: evaluate the function, store the return 17 // value alongside the virtual table, and rewrite each virtual call as a load 18 // from the virtual table. 19 // - Uniform return value optimization: if the conditions for virtual constant 20 // propagation hold and each function returns the same constant value, replace 21 // each virtual call with that constant. 22 // - Unique return value optimization for i1 return values: if the conditions 23 // for virtual constant propagation hold and a single vtable's function 24 // returns 0, or a single vtable's function returns 1, replace each virtual 25 // call with a comparison of the vptr against that vtable's address. 26 // 27 // This pass is intended to be used during the regular and thin LTO pipelines: 28 // 29 // During regular LTO, the pass determines the best optimization for each 30 // virtual call and applies the resolutions directly to virtual calls that are 31 // eligible for virtual call optimization (i.e. calls that use either of the 32 // llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics). 33 // 34 // During hybrid Regular/ThinLTO, the pass operates in two phases: 35 // - Export phase: this is run during the thin link over a single merged module 36 // that contains all vtables with !type metadata that participate in the link. 37 // The pass computes a resolution for each virtual call and stores it in the 38 // type identifier summary. 39 // - Import phase: this is run during the thin backends over the individual 40 // modules. The pass applies the resolutions previously computed during the 41 // import phase to each eligible virtual call. 42 // 43 // During ThinLTO, the pass operates in two phases: 44 // - Export phase: this is run during the thin link over the index which 45 // contains a summary of all vtables with !type metadata that participate in 46 // the link. It computes a resolution for each virtual call and stores it in 47 // the type identifier summary. Only single implementation devirtualization 48 // is supported. 49 // - Import phase: (same as with hybrid case above). 50 // 51 //===----------------------------------------------------------------------===// 52 53 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 54 #include "llvm/ADT/ArrayRef.h" 55 #include "llvm/ADT/DenseMap.h" 56 #include "llvm/ADT/DenseMapInfo.h" 57 #include "llvm/ADT/DenseSet.h" 58 #include "llvm/ADT/MapVector.h" 59 #include "llvm/ADT/SmallVector.h" 60 #include "llvm/ADT/Statistic.h" 61 #include "llvm/Analysis/AssumptionCache.h" 62 #include "llvm/Analysis/BasicAliasAnalysis.h" 63 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 64 #include "llvm/Analysis/TypeMetadataUtils.h" 65 #include "llvm/Bitcode/BitcodeReader.h" 66 #include "llvm/Bitcode/BitcodeWriter.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugLoc.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Dominators.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GlobalAlias.h" 74 #include "llvm/IR/GlobalVariable.h" 75 #include "llvm/IR/IRBuilder.h" 76 #include "llvm/IR/InstrTypes.h" 77 #include "llvm/IR/Instruction.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/Intrinsics.h" 80 #include "llvm/IR/LLVMContext.h" 81 #include "llvm/IR/MDBuilder.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/ModuleSummaryIndexYAML.h" 85 #include "llvm/Support/Casting.h" 86 #include "llvm/Support/CommandLine.h" 87 #include "llvm/Support/Errc.h" 88 #include "llvm/Support/Error.h" 89 #include "llvm/Support/FileSystem.h" 90 #include "llvm/Support/GlobPattern.h" 91 #include "llvm/Support/MathExtras.h" 92 #include "llvm/TargetParser/Triple.h" 93 #include "llvm/Transforms/IPO.h" 94 #include "llvm/Transforms/IPO/FunctionAttrs.h" 95 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 96 #include "llvm/Transforms/Utils/CallPromotionUtils.h" 97 #include "llvm/Transforms/Utils/Evaluator.h" 98 #include <algorithm> 99 #include <cstddef> 100 #include <map> 101 #include <set> 102 #include <string> 103 104 using namespace llvm; 105 using namespace wholeprogramdevirt; 106 107 #define DEBUG_TYPE "wholeprogramdevirt" 108 109 STATISTIC(NumDevirtTargets, "Number of whole program devirtualization targets"); 110 STATISTIC(NumSingleImpl, "Number of single implementation devirtualizations"); 111 STATISTIC(NumBranchFunnel, "Number of branch funnels"); 112 STATISTIC(NumUniformRetVal, "Number of uniform return value optimizations"); 113 STATISTIC(NumUniqueRetVal, "Number of unique return value optimizations"); 114 STATISTIC(NumVirtConstProp1Bit, 115 "Number of 1 bit virtual constant propagations"); 116 STATISTIC(NumVirtConstProp, "Number of virtual constant propagations"); 117 118 static cl::opt<PassSummaryAction> ClSummaryAction( 119 "wholeprogramdevirt-summary-action", 120 cl::desc("What to do with the summary when running this pass"), 121 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), 122 clEnumValN(PassSummaryAction::Import, "import", 123 "Import typeid resolutions from summary and globals"), 124 clEnumValN(PassSummaryAction::Export, "export", 125 "Export typeid resolutions to summary and globals")), 126 cl::Hidden); 127 128 static cl::opt<std::string> ClReadSummary( 129 "wholeprogramdevirt-read-summary", 130 cl::desc( 131 "Read summary from given bitcode or YAML file before running pass"), 132 cl::Hidden); 133 134 static cl::opt<std::string> ClWriteSummary( 135 "wholeprogramdevirt-write-summary", 136 cl::desc("Write summary to given bitcode or YAML file after running pass. " 137 "Output file format is deduced from extension: *.bc means writing " 138 "bitcode, otherwise YAML"), 139 cl::Hidden); 140 141 static cl::opt<unsigned> 142 ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden, 143 cl::init(10), 144 cl::desc("Maximum number of call targets per " 145 "call site to enable branch funnels")); 146 147 static cl::opt<bool> 148 PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden, 149 cl::desc("Print index-based devirtualization messages")); 150 151 /// Provide a way to force enable whole program visibility in tests. 152 /// This is needed to support legacy tests that don't contain 153 /// !vcall_visibility metadata (the mere presense of type tests 154 /// previously implied hidden visibility). 155 static cl::opt<bool> 156 WholeProgramVisibility("whole-program-visibility", cl::Hidden, 157 cl::desc("Enable whole program visibility")); 158 159 /// Provide a way to force disable whole program for debugging or workarounds, 160 /// when enabled via the linker. 161 static cl::opt<bool> DisableWholeProgramVisibility( 162 "disable-whole-program-visibility", cl::Hidden, 163 cl::desc("Disable whole program visibility (overrides enabling options)")); 164 165 /// Provide way to prevent certain function from being devirtualized 166 static cl::list<std::string> 167 SkipFunctionNames("wholeprogramdevirt-skip", 168 cl::desc("Prevent function(s) from being devirtualized"), 169 cl::Hidden, cl::CommaSeparated); 170 171 /// Mechanism to add runtime checking of devirtualization decisions, optionally 172 /// trapping or falling back to indirect call on any that are not correct. 173 /// Trapping mode is useful for debugging undefined behavior leading to failures 174 /// with WPD. Fallback mode is useful for ensuring safety when whole program 175 /// visibility may be compromised. 176 enum WPDCheckMode { None, Trap, Fallback }; 177 static cl::opt<WPDCheckMode> DevirtCheckMode( 178 "wholeprogramdevirt-check", cl::Hidden, 179 cl::desc("Type of checking for incorrect devirtualizations"), 180 cl::values(clEnumValN(WPDCheckMode::None, "none", "No checking"), 181 clEnumValN(WPDCheckMode::Trap, "trap", "Trap when incorrect"), 182 clEnumValN(WPDCheckMode::Fallback, "fallback", 183 "Fallback to indirect when incorrect"))); 184 185 namespace { 186 struct PatternList { 187 std::vector<GlobPattern> Patterns; 188 template <class T> void init(const T &StringList) { 189 for (const auto &S : StringList) 190 if (Expected<GlobPattern> Pat = GlobPattern::create(S)) 191 Patterns.push_back(std::move(*Pat)); 192 } 193 bool match(StringRef S) { 194 for (const GlobPattern &P : Patterns) 195 if (P.match(S)) 196 return true; 197 return false; 198 } 199 }; 200 } // namespace 201 202 // Find the minimum offset that we may store a value of size Size bits at. If 203 // IsAfter is set, look for an offset before the object, otherwise look for an 204 // offset after the object. 205 uint64_t 206 wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets, 207 bool IsAfter, uint64_t Size) { 208 // Find a minimum offset taking into account only vtable sizes. 209 uint64_t MinByte = 0; 210 for (const VirtualCallTarget &Target : Targets) { 211 if (IsAfter) 212 MinByte = std::max(MinByte, Target.minAfterBytes()); 213 else 214 MinByte = std::max(MinByte, Target.minBeforeBytes()); 215 } 216 217 // Build a vector of arrays of bytes covering, for each target, a slice of the 218 // used region (see AccumBitVector::BytesUsed in 219 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively, 220 // this aligns the used regions to start at MinByte. 221 // 222 // In this example, A, B and C are vtables, # is a byte already allocated for 223 // a virtual function pointer, AAAA... (etc.) are the used regions for the 224 // vtables and Offset(X) is the value computed for the Offset variable below 225 // for X. 226 // 227 // Offset(A) 228 // | | 229 // |MinByte 230 // A: ################AAAAAAAA|AAAAAAAA 231 // B: ########BBBBBBBBBBBBBBBB|BBBB 232 // C: ########################|CCCCCCCCCCCCCCCC 233 // | Offset(B) | 234 // 235 // This code produces the slices of A, B and C that appear after the divider 236 // at MinByte. 237 std::vector<ArrayRef<uint8_t>> Used; 238 for (const VirtualCallTarget &Target : Targets) { 239 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed 240 : Target.TM->Bits->Before.BytesUsed; 241 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes() 242 : MinByte - Target.minBeforeBytes(); 243 244 // Disregard used regions that are smaller than Offset. These are 245 // effectively all-free regions that do not need to be checked. 246 if (VTUsed.size() > Offset) 247 Used.push_back(VTUsed.slice(Offset)); 248 } 249 250 if (Size == 1) { 251 // Find a free bit in each member of Used. 252 for (unsigned I = 0;; ++I) { 253 uint8_t BitsUsed = 0; 254 for (auto &&B : Used) 255 if (I < B.size()) 256 BitsUsed |= B[I]; 257 if (BitsUsed != 0xff) 258 return (MinByte + I) * 8 + llvm::countr_zero(uint8_t(~BitsUsed)); 259 } 260 } else { 261 // Find a free (Size/8) byte region in each member of Used. 262 // FIXME: see if alignment helps. 263 for (unsigned I = 0;; ++I) { 264 for (auto &&B : Used) { 265 unsigned Byte = 0; 266 while ((I + Byte) < B.size() && Byte < (Size / 8)) { 267 if (B[I + Byte]) 268 goto NextI; 269 ++Byte; 270 } 271 } 272 return (MinByte + I) * 8; 273 NextI:; 274 } 275 } 276 } 277 278 void wholeprogramdevirt::setBeforeReturnValues( 279 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore, 280 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { 281 if (BitWidth == 1) 282 OffsetByte = -(AllocBefore / 8 + 1); 283 else 284 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8); 285 OffsetBit = AllocBefore % 8; 286 287 for (VirtualCallTarget &Target : Targets) { 288 if (BitWidth == 1) 289 Target.setBeforeBit(AllocBefore); 290 else 291 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8); 292 } 293 } 294 295 void wholeprogramdevirt::setAfterReturnValues( 296 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter, 297 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { 298 if (BitWidth == 1) 299 OffsetByte = AllocAfter / 8; 300 else 301 OffsetByte = (AllocAfter + 7) / 8; 302 OffsetBit = AllocAfter % 8; 303 304 for (VirtualCallTarget &Target : Targets) { 305 if (BitWidth == 1) 306 Target.setAfterBit(AllocAfter); 307 else 308 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8); 309 } 310 } 311 312 VirtualCallTarget::VirtualCallTarget(GlobalValue *Fn, const TypeMemberInfo *TM) 313 : Fn(Fn), TM(TM), 314 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), 315 WasDevirt(false) {} 316 317 namespace { 318 319 // A slot in a set of virtual tables. The TypeID identifies the set of virtual 320 // tables, and the ByteOffset is the offset in bytes from the address point to 321 // the virtual function pointer. 322 struct VTableSlot { 323 Metadata *TypeID; 324 uint64_t ByteOffset; 325 }; 326 327 } // end anonymous namespace 328 329 namespace llvm { 330 331 template <> struct DenseMapInfo<VTableSlot> { 332 static VTableSlot getEmptyKey() { 333 return {DenseMapInfo<Metadata *>::getEmptyKey(), 334 DenseMapInfo<uint64_t>::getEmptyKey()}; 335 } 336 static VTableSlot getTombstoneKey() { 337 return {DenseMapInfo<Metadata *>::getTombstoneKey(), 338 DenseMapInfo<uint64_t>::getTombstoneKey()}; 339 } 340 static unsigned getHashValue(const VTableSlot &I) { 341 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^ 342 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); 343 } 344 static bool isEqual(const VTableSlot &LHS, 345 const VTableSlot &RHS) { 346 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; 347 } 348 }; 349 350 template <> struct DenseMapInfo<VTableSlotSummary> { 351 static VTableSlotSummary getEmptyKey() { 352 return {DenseMapInfo<StringRef>::getEmptyKey(), 353 DenseMapInfo<uint64_t>::getEmptyKey()}; 354 } 355 static VTableSlotSummary getTombstoneKey() { 356 return {DenseMapInfo<StringRef>::getTombstoneKey(), 357 DenseMapInfo<uint64_t>::getTombstoneKey()}; 358 } 359 static unsigned getHashValue(const VTableSlotSummary &I) { 360 return DenseMapInfo<StringRef>::getHashValue(I.TypeID) ^ 361 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); 362 } 363 static bool isEqual(const VTableSlotSummary &LHS, 364 const VTableSlotSummary &RHS) { 365 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; 366 } 367 }; 368 369 } // end namespace llvm 370 371 // Returns true if the function must be unreachable based on ValueInfo. 372 // 373 // In particular, identifies a function as unreachable in the following 374 // conditions 375 // 1) All summaries are live. 376 // 2) All function summaries indicate it's unreachable 377 // 3) There is no non-function with the same GUID (which is rare) 378 static bool mustBeUnreachableFunction(ValueInfo TheFnVI) { 379 if ((!TheFnVI) || TheFnVI.getSummaryList().empty()) { 380 // Returns false if ValueInfo is absent, or the summary list is empty 381 // (e.g., function declarations). 382 return false; 383 } 384 385 for (const auto &Summary : TheFnVI.getSummaryList()) { 386 // Conservatively returns false if any non-live functions are seen. 387 // In general either all summaries should be live or all should be dead. 388 if (!Summary->isLive()) 389 return false; 390 if (auto *FS = dyn_cast<FunctionSummary>(Summary->getBaseObject())) { 391 if (!FS->fflags().MustBeUnreachable) 392 return false; 393 } 394 // Be conservative if a non-function has the same GUID (which is rare). 395 else 396 return false; 397 } 398 // All function summaries are live and all of them agree that the function is 399 // unreachble. 400 return true; 401 } 402 403 namespace { 404 // A virtual call site. VTable is the loaded virtual table pointer, and CS is 405 // the indirect virtual call. 406 struct VirtualCallSite { 407 Value *VTable = nullptr; 408 CallBase &CB; 409 410 // If non-null, this field points to the associated unsafe use count stored in 411 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description 412 // of that field for details. 413 unsigned *NumUnsafeUses = nullptr; 414 415 void 416 emitRemark(const StringRef OptName, const StringRef TargetName, 417 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) { 418 Function *F = CB.getCaller(); 419 DebugLoc DLoc = CB.getDebugLoc(); 420 BasicBlock *Block = CB.getParent(); 421 422 using namespace ore; 423 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block) 424 << NV("Optimization", OptName) 425 << ": devirtualized a call to " 426 << NV("FunctionName", TargetName)); 427 } 428 429 void replaceAndErase( 430 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled, 431 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, 432 Value *New) { 433 if (RemarksEnabled) 434 emitRemark(OptName, TargetName, OREGetter); 435 CB.replaceAllUsesWith(New); 436 if (auto *II = dyn_cast<InvokeInst>(&CB)) { 437 BranchInst::Create(II->getNormalDest(), &CB); 438 II->getUnwindDest()->removePredecessor(II->getParent()); 439 } 440 CB.eraseFromParent(); 441 // This use is no longer unsafe. 442 if (NumUnsafeUses) 443 --*NumUnsafeUses; 444 } 445 }; 446 447 // Call site information collected for a specific VTableSlot and possibly a list 448 // of constant integer arguments. The grouping by arguments is handled by the 449 // VTableSlotInfo class. 450 struct CallSiteInfo { 451 /// The set of call sites for this slot. Used during regular LTO and the 452 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any 453 /// call sites that appear in the merged module itself); in each of these 454 /// cases we are directly operating on the call sites at the IR level. 455 std::vector<VirtualCallSite> CallSites; 456 457 /// Whether all call sites represented by this CallSiteInfo, including those 458 /// in summaries, have been devirtualized. This starts off as true because a 459 /// default constructed CallSiteInfo represents no call sites. 460 bool AllCallSitesDevirted = true; 461 462 // These fields are used during the export phase of ThinLTO and reflect 463 // information collected from function summaries. 464 465 /// Whether any function summary contains an llvm.assume(llvm.type.test) for 466 /// this slot. 467 bool SummaryHasTypeTestAssumeUsers = false; 468 469 /// CFI-specific: a vector containing the list of function summaries that use 470 /// the llvm.type.checked.load intrinsic and therefore will require 471 /// resolutions for llvm.type.test in order to implement CFI checks if 472 /// devirtualization was unsuccessful. If devirtualization was successful, the 473 /// pass will clear this vector by calling markDevirt(). If at the end of the 474 /// pass the vector is non-empty, we will need to add a use of llvm.type.test 475 /// to each of the function summaries in the vector. 476 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers; 477 std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers; 478 479 bool isExported() const { 480 return SummaryHasTypeTestAssumeUsers || 481 !SummaryTypeCheckedLoadUsers.empty(); 482 } 483 484 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) { 485 SummaryTypeCheckedLoadUsers.push_back(FS); 486 AllCallSitesDevirted = false; 487 } 488 489 void addSummaryTypeTestAssumeUser(FunctionSummary *FS) { 490 SummaryTypeTestAssumeUsers.push_back(FS); 491 SummaryHasTypeTestAssumeUsers = true; 492 AllCallSitesDevirted = false; 493 } 494 495 void markDevirt() { 496 AllCallSitesDevirted = true; 497 498 // As explained in the comment for SummaryTypeCheckedLoadUsers. 499 SummaryTypeCheckedLoadUsers.clear(); 500 } 501 }; 502 503 // Call site information collected for a specific VTableSlot. 504 struct VTableSlotInfo { 505 // The set of call sites which do not have all constant integer arguments 506 // (excluding "this"). 507 CallSiteInfo CSInfo; 508 509 // The set of call sites with all constant integer arguments (excluding 510 // "this"), grouped by argument list. 511 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo; 512 513 void addCallSite(Value *VTable, CallBase &CB, unsigned *NumUnsafeUses); 514 515 private: 516 CallSiteInfo &findCallSiteInfo(CallBase &CB); 517 }; 518 519 CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallBase &CB) { 520 std::vector<uint64_t> Args; 521 auto *CBType = dyn_cast<IntegerType>(CB.getType()); 522 if (!CBType || CBType->getBitWidth() > 64 || CB.arg_empty()) 523 return CSInfo; 524 for (auto &&Arg : drop_begin(CB.args())) { 525 auto *CI = dyn_cast<ConstantInt>(Arg); 526 if (!CI || CI->getBitWidth() > 64) 527 return CSInfo; 528 Args.push_back(CI->getZExtValue()); 529 } 530 return ConstCSInfo[Args]; 531 } 532 533 void VTableSlotInfo::addCallSite(Value *VTable, CallBase &CB, 534 unsigned *NumUnsafeUses) { 535 auto &CSI = findCallSiteInfo(CB); 536 CSI.AllCallSitesDevirted = false; 537 CSI.CallSites.push_back({VTable, CB, NumUnsafeUses}); 538 } 539 540 struct DevirtModule { 541 Module &M; 542 function_ref<AAResults &(Function &)> AARGetter; 543 function_ref<DominatorTree &(Function &)> LookupDomTree; 544 545 ModuleSummaryIndex *ExportSummary; 546 const ModuleSummaryIndex *ImportSummary; 547 548 IntegerType *Int8Ty; 549 PointerType *Int8PtrTy; 550 IntegerType *Int32Ty; 551 IntegerType *Int64Ty; 552 IntegerType *IntPtrTy; 553 /// Sizeless array type, used for imported vtables. This provides a signal 554 /// to analyzers that these imports may alias, as they do for example 555 /// when multiple unique return values occur in the same vtable. 556 ArrayType *Int8Arr0Ty; 557 558 bool RemarksEnabled; 559 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter; 560 561 MapVector<VTableSlot, VTableSlotInfo> CallSlots; 562 563 // Calls that have already been optimized. We may add a call to multiple 564 // VTableSlotInfos if vtable loads are coalesced and need to make sure not to 565 // optimize a call more than once. 566 SmallPtrSet<CallBase *, 8> OptimizedCalls; 567 568 // Store calls that had their ptrauth bundle removed. They are to be deleted 569 // at the end of the optimization. 570 SmallVector<CallBase *, 8> CallsWithPtrAuthBundleRemoved; 571 572 // This map keeps track of the number of "unsafe" uses of a loaded function 573 // pointer. The key is the associated llvm.type.test intrinsic call generated 574 // by this pass. An unsafe use is one that calls the loaded function pointer 575 // directly. Every time we eliminate an unsafe use (for example, by 576 // devirtualizing it or by applying virtual constant propagation), we 577 // decrement the value stored in this map. If a value reaches zero, we can 578 // eliminate the type check by RAUWing the associated llvm.type.test call with 579 // true. 580 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest; 581 PatternList FunctionsToSkip; 582 583 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter, 584 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, 585 function_ref<DominatorTree &(Function &)> LookupDomTree, 586 ModuleSummaryIndex *ExportSummary, 587 const ModuleSummaryIndex *ImportSummary) 588 : M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree), 589 ExportSummary(ExportSummary), ImportSummary(ImportSummary), 590 Int8Ty(Type::getInt8Ty(M.getContext())), 591 Int8PtrTy(PointerType::getUnqual(M.getContext())), 592 Int32Ty(Type::getInt32Ty(M.getContext())), 593 Int64Ty(Type::getInt64Ty(M.getContext())), 594 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)), 595 Int8Arr0Ty(ArrayType::get(Type::getInt8Ty(M.getContext()), 0)), 596 RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) { 597 assert(!(ExportSummary && ImportSummary)); 598 FunctionsToSkip.init(SkipFunctionNames); 599 } 600 601 bool areRemarksEnabled(); 602 603 void 604 scanTypeTestUsers(Function *TypeTestFunc, 605 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); 606 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc); 607 608 void buildTypeIdentifierMap( 609 std::vector<VTableBits> &Bits, 610 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); 611 612 bool 613 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot, 614 const std::set<TypeMemberInfo> &TypeMemberInfos, 615 uint64_t ByteOffset, 616 ModuleSummaryIndex *ExportSummary); 617 618 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn, 619 bool &IsExported); 620 bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary, 621 MutableArrayRef<VirtualCallTarget> TargetsForSlot, 622 VTableSlotInfo &SlotInfo, 623 WholeProgramDevirtResolution *Res); 624 625 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT, 626 bool &IsExported); 627 void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot, 628 VTableSlotInfo &SlotInfo, 629 WholeProgramDevirtResolution *Res, VTableSlot Slot); 630 631 bool tryEvaluateFunctionsWithArgs( 632 MutableArrayRef<VirtualCallTarget> TargetsForSlot, 633 ArrayRef<uint64_t> Args); 634 635 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, 636 uint64_t TheRetVal); 637 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, 638 CallSiteInfo &CSInfo, 639 WholeProgramDevirtResolution::ByArg *Res); 640 641 // Returns the global symbol name that is used to export information about the 642 // given vtable slot and list of arguments. 643 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args, 644 StringRef Name); 645 646 bool shouldExportConstantsAsAbsoluteSymbols(); 647 648 // This function is called during the export phase to create a symbol 649 // definition containing information about the given vtable slot and list of 650 // arguments. 651 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, 652 Constant *C); 653 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, 654 uint32_t Const, uint32_t &Storage); 655 656 // This function is called during the import phase to create a reference to 657 // the symbol definition created during the export phase. 658 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, 659 StringRef Name); 660 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, 661 StringRef Name, IntegerType *IntTy, 662 uint32_t Storage); 663 664 Constant *getMemberAddr(const TypeMemberInfo *M); 665 666 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne, 667 Constant *UniqueMemberAddr); 668 bool tryUniqueRetValOpt(unsigned BitWidth, 669 MutableArrayRef<VirtualCallTarget> TargetsForSlot, 670 CallSiteInfo &CSInfo, 671 WholeProgramDevirtResolution::ByArg *Res, 672 VTableSlot Slot, ArrayRef<uint64_t> Args); 673 674 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, 675 Constant *Byte, Constant *Bit); 676 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot, 677 VTableSlotInfo &SlotInfo, 678 WholeProgramDevirtResolution *Res, VTableSlot Slot); 679 680 void rebuildGlobal(VTableBits &B); 681 682 // Apply the summary resolution for Slot to all virtual calls in SlotInfo. 683 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo); 684 685 // If we were able to eliminate all unsafe uses for a type checked load, 686 // eliminate the associated type tests by replacing them with true. 687 void removeRedundantTypeTests(); 688 689 bool run(); 690 691 // Look up the corresponding ValueInfo entry of `TheFn` in `ExportSummary`. 692 // 693 // Caller guarantees that `ExportSummary` is not nullptr. 694 static ValueInfo lookUpFunctionValueInfo(Function *TheFn, 695 ModuleSummaryIndex *ExportSummary); 696 697 // Returns true if the function definition must be unreachable. 698 // 699 // Note if this helper function returns true, `F` is guaranteed 700 // to be unreachable; if it returns false, `F` might still 701 // be unreachable but not covered by this helper function. 702 // 703 // Implementation-wise, if function definition is present, IR is analyzed; if 704 // not, look up function flags from ExportSummary as a fallback. 705 static bool mustBeUnreachableFunction(Function *const F, 706 ModuleSummaryIndex *ExportSummary); 707 708 // Lower the module using the action and summary passed as command line 709 // arguments. For testing purposes only. 710 static bool 711 runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter, 712 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, 713 function_ref<DominatorTree &(Function &)> LookupDomTree); 714 }; 715 716 struct DevirtIndex { 717 ModuleSummaryIndex &ExportSummary; 718 // The set in which to record GUIDs exported from their module by 719 // devirtualization, used by client to ensure they are not internalized. 720 std::set<GlobalValue::GUID> &ExportedGUIDs; 721 // A map in which to record the information necessary to locate the WPD 722 // resolution for local targets in case they are exported by cross module 723 // importing. 724 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap; 725 726 MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots; 727 728 PatternList FunctionsToSkip; 729 730 DevirtIndex( 731 ModuleSummaryIndex &ExportSummary, 732 std::set<GlobalValue::GUID> &ExportedGUIDs, 733 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) 734 : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs), 735 LocalWPDTargetsMap(LocalWPDTargetsMap) { 736 FunctionsToSkip.init(SkipFunctionNames); 737 } 738 739 bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot, 740 const TypeIdCompatibleVtableInfo TIdInfo, 741 uint64_t ByteOffset); 742 743 bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot, 744 VTableSlotSummary &SlotSummary, 745 VTableSlotInfo &SlotInfo, 746 WholeProgramDevirtResolution *Res, 747 std::set<ValueInfo> &DevirtTargets); 748 749 void run(); 750 }; 751 } // end anonymous namespace 752 753 PreservedAnalyses WholeProgramDevirtPass::run(Module &M, 754 ModuleAnalysisManager &AM) { 755 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 756 auto AARGetter = [&](Function &F) -> AAResults & { 757 return FAM.getResult<AAManager>(F); 758 }; 759 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & { 760 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); 761 }; 762 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & { 763 return FAM.getResult<DominatorTreeAnalysis>(F); 764 }; 765 if (UseCommandLine) { 766 if (!DevirtModule::runForTesting(M, AARGetter, OREGetter, LookupDomTree)) 767 return PreservedAnalyses::all(); 768 return PreservedAnalyses::none(); 769 } 770 if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary, 771 ImportSummary) 772 .run()) 773 return PreservedAnalyses::all(); 774 return PreservedAnalyses::none(); 775 } 776 777 // Enable whole program visibility if enabled by client (e.g. linker) or 778 // internal option, and not force disabled. 779 bool llvm::hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO) { 780 return (WholeProgramVisibilityEnabledInLTO || WholeProgramVisibility) && 781 !DisableWholeProgramVisibility; 782 } 783 784 static bool 785 typeIDVisibleToRegularObj(StringRef TypeID, 786 function_ref<bool(StringRef)> IsVisibleToRegularObj) { 787 // TypeID for member function pointer type is an internal construct 788 // and won't exist in IsVisibleToRegularObj. The full TypeID 789 // will be present and participate in invalidation. 790 if (TypeID.ends_with(".virtual")) 791 return false; 792 793 // TypeID that doesn't start with Itanium mangling (_ZTS) will be 794 // non-externally visible types which cannot interact with 795 // external native files. See CodeGenModule::CreateMetadataIdentifierImpl. 796 if (!TypeID.consume_front("_ZTS")) 797 return false; 798 799 // TypeID is keyed off the type name symbol (_ZTS). However, the native 800 // object may not contain this symbol if it does not contain a key 801 // function for the base type and thus only contains a reference to the 802 // type info (_ZTI). To catch this case we query using the type info 803 // symbol corresponding to the TypeID. 804 std::string typeInfo = ("_ZTI" + TypeID).str(); 805 return IsVisibleToRegularObj(typeInfo); 806 } 807 808 static bool 809 skipUpdateDueToValidation(GlobalVariable &GV, 810 function_ref<bool(StringRef)> IsVisibleToRegularObj) { 811 SmallVector<MDNode *, 2> Types; 812 GV.getMetadata(LLVMContext::MD_type, Types); 813 814 for (auto Type : Types) 815 if (auto *TypeID = dyn_cast<MDString>(Type->getOperand(1).get())) 816 return typeIDVisibleToRegularObj(TypeID->getString(), 817 IsVisibleToRegularObj); 818 819 return false; 820 } 821 822 /// If whole program visibility asserted, then upgrade all public vcall 823 /// visibility metadata on vtable definitions to linkage unit visibility in 824 /// Module IR (for regular or hybrid LTO). 825 void llvm::updateVCallVisibilityInModule( 826 Module &M, bool WholeProgramVisibilityEnabledInLTO, 827 const DenseSet<GlobalValue::GUID> &DynamicExportSymbols, 828 bool ValidateAllVtablesHaveTypeInfos, 829 function_ref<bool(StringRef)> IsVisibleToRegularObj) { 830 if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) 831 return; 832 for (GlobalVariable &GV : M.globals()) { 833 // Add linkage unit visibility to any variable with type metadata, which are 834 // the vtable definitions. We won't have an existing vcall_visibility 835 // metadata on vtable definitions with public visibility. 836 if (GV.hasMetadata(LLVMContext::MD_type) && 837 GV.getVCallVisibility() == GlobalObject::VCallVisibilityPublic && 838 // Don't upgrade the visibility for symbols exported to the dynamic 839 // linker, as we have no information on their eventual use. 840 !DynamicExportSymbols.count(GV.getGUID()) && 841 // With validation enabled, we want to exclude symbols visible to 842 // regular objects. Local symbols will be in this group due to the 843 // current implementation but those with VCallVisibilityTranslationUnit 844 // will have already been marked in clang so are unaffected. 845 !(ValidateAllVtablesHaveTypeInfos && 846 skipUpdateDueToValidation(GV, IsVisibleToRegularObj))) 847 GV.setVCallVisibilityMetadata(GlobalObject::VCallVisibilityLinkageUnit); 848 } 849 } 850 851 void llvm::updatePublicTypeTestCalls(Module &M, 852 bool WholeProgramVisibilityEnabledInLTO) { 853 Function *PublicTypeTestFunc = 854 M.getFunction(Intrinsic::getName(Intrinsic::public_type_test)); 855 if (!PublicTypeTestFunc) 856 return; 857 if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) { 858 Function *TypeTestFunc = 859 Intrinsic::getDeclaration(&M, Intrinsic::type_test); 860 for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) { 861 auto *CI = cast<CallInst>(U.getUser()); 862 auto *NewCI = CallInst::Create( 863 TypeTestFunc, {CI->getArgOperand(0), CI->getArgOperand(1)}, 864 std::nullopt, "", CI); 865 CI->replaceAllUsesWith(NewCI); 866 CI->eraseFromParent(); 867 } 868 } else { 869 auto *True = ConstantInt::getTrue(M.getContext()); 870 for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) { 871 auto *CI = cast<CallInst>(U.getUser()); 872 CI->replaceAllUsesWith(True); 873 CI->eraseFromParent(); 874 } 875 } 876 } 877 878 /// Based on typeID string, get all associated vtable GUIDS that are 879 /// visible to regular objects. 880 void llvm::getVisibleToRegularObjVtableGUIDs( 881 ModuleSummaryIndex &Index, 882 DenseSet<GlobalValue::GUID> &VisibleToRegularObjSymbols, 883 function_ref<bool(StringRef)> IsVisibleToRegularObj) { 884 for (const auto &typeID : Index.typeIdCompatibleVtableMap()) { 885 if (typeIDVisibleToRegularObj(typeID.first, IsVisibleToRegularObj)) 886 for (const TypeIdOffsetVtableInfo &P : typeID.second) 887 VisibleToRegularObjSymbols.insert(P.VTableVI.getGUID()); 888 } 889 } 890 891 /// If whole program visibility asserted, then upgrade all public vcall 892 /// visibility metadata on vtable definition summaries to linkage unit 893 /// visibility in Module summary index (for ThinLTO). 894 void llvm::updateVCallVisibilityInIndex( 895 ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, 896 const DenseSet<GlobalValue::GUID> &DynamicExportSymbols, 897 const DenseSet<GlobalValue::GUID> &VisibleToRegularObjSymbols) { 898 if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) 899 return; 900 for (auto &P : Index) { 901 // Don't upgrade the visibility for symbols exported to the dynamic 902 // linker, as we have no information on their eventual use. 903 if (DynamicExportSymbols.count(P.first)) 904 continue; 905 for (auto &S : P.second.SummaryList) { 906 auto *GVar = dyn_cast<GlobalVarSummary>(S.get()); 907 if (!GVar || 908 GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic) 909 continue; 910 // With validation enabled, we want to exclude symbols visible to regular 911 // objects. Local symbols will be in this group due to the current 912 // implementation but those with VCallVisibilityTranslationUnit will have 913 // already been marked in clang so are unaffected. 914 if (VisibleToRegularObjSymbols.count(P.first)) 915 continue; 916 GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit); 917 } 918 } 919 } 920 921 void llvm::runWholeProgramDevirtOnIndex( 922 ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs, 923 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) { 924 DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run(); 925 } 926 927 void llvm::updateIndexWPDForExports( 928 ModuleSummaryIndex &Summary, 929 function_ref<bool(StringRef, ValueInfo)> isExported, 930 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) { 931 for (auto &T : LocalWPDTargetsMap) { 932 auto &VI = T.first; 933 // This was enforced earlier during trySingleImplDevirt. 934 assert(VI.getSummaryList().size() == 1 && 935 "Devirt of local target has more than one copy"); 936 auto &S = VI.getSummaryList()[0]; 937 if (!isExported(S->modulePath(), VI)) 938 continue; 939 940 // It's been exported by a cross module import. 941 for (auto &SlotSummary : T.second) { 942 auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID); 943 assert(TIdSum); 944 auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset); 945 assert(WPDRes != TIdSum->WPDRes.end()); 946 WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal( 947 WPDRes->second.SingleImplName, 948 Summary.getModuleHash(S->modulePath())); 949 } 950 } 951 } 952 953 static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary) { 954 // Check that summary index contains regular LTO module when performing 955 // export to prevent occasional use of index from pure ThinLTO compilation 956 // (-fno-split-lto-module). This kind of summary index is passed to 957 // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting. 958 const auto &ModPaths = Summary->modulePaths(); 959 if (ClSummaryAction != PassSummaryAction::Import && 960 !ModPaths.contains(ModuleSummaryIndex::getRegularLTOModuleName())) 961 return createStringError( 962 errc::invalid_argument, 963 "combined summary should contain Regular LTO module"); 964 return ErrorSuccess(); 965 } 966 967 bool DevirtModule::runForTesting( 968 Module &M, function_ref<AAResults &(Function &)> AARGetter, 969 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, 970 function_ref<DominatorTree &(Function &)> LookupDomTree) { 971 std::unique_ptr<ModuleSummaryIndex> Summary = 972 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 973 974 // Handle the command-line summary arguments. This code is for testing 975 // purposes only, so we handle errors directly. 976 if (!ClReadSummary.empty()) { 977 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary + 978 ": "); 979 auto ReadSummaryFile = 980 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); 981 if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = 982 getModuleSummaryIndex(*ReadSummaryFile)) { 983 Summary = std::move(*SummaryOrErr); 984 ExitOnErr(checkCombinedSummaryForTesting(Summary.get())); 985 } else { 986 // Try YAML if we've failed with bitcode. 987 consumeError(SummaryOrErr.takeError()); 988 yaml::Input In(ReadSummaryFile->getBuffer()); 989 In >> *Summary; 990 ExitOnErr(errorCodeToError(In.error())); 991 } 992 } 993 994 bool Changed = 995 DevirtModule(M, AARGetter, OREGetter, LookupDomTree, 996 ClSummaryAction == PassSummaryAction::Export ? Summary.get() 997 : nullptr, 998 ClSummaryAction == PassSummaryAction::Import ? Summary.get() 999 : nullptr) 1000 .run(); 1001 1002 if (!ClWriteSummary.empty()) { 1003 ExitOnError ExitOnErr( 1004 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": "); 1005 std::error_code EC; 1006 if (StringRef(ClWriteSummary).ends_with(".bc")) { 1007 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None); 1008 ExitOnErr(errorCodeToError(EC)); 1009 writeIndexToFile(*Summary, OS); 1010 } else { 1011 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_TextWithCRLF); 1012 ExitOnErr(errorCodeToError(EC)); 1013 yaml::Output Out(OS); 1014 Out << *Summary; 1015 } 1016 } 1017 1018 return Changed; 1019 } 1020 1021 void DevirtModule::buildTypeIdentifierMap( 1022 std::vector<VTableBits> &Bits, 1023 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { 1024 DenseMap<GlobalVariable *, VTableBits *> GVToBits; 1025 Bits.reserve(M.global_size()); 1026 SmallVector<MDNode *, 2> Types; 1027 for (GlobalVariable &GV : M.globals()) { 1028 Types.clear(); 1029 GV.getMetadata(LLVMContext::MD_type, Types); 1030 if (GV.isDeclaration() || Types.empty()) 1031 continue; 1032 1033 VTableBits *&BitsPtr = GVToBits[&GV]; 1034 if (!BitsPtr) { 1035 Bits.emplace_back(); 1036 Bits.back().GV = &GV; 1037 Bits.back().ObjectSize = 1038 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType()); 1039 BitsPtr = &Bits.back(); 1040 } 1041 1042 for (MDNode *Type : Types) { 1043 auto TypeID = Type->getOperand(1).get(); 1044 1045 uint64_t Offset = 1046 cast<ConstantInt>( 1047 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) 1048 ->getZExtValue(); 1049 1050 TypeIdMap[TypeID].insert({BitsPtr, Offset}); 1051 } 1052 } 1053 } 1054 1055 bool DevirtModule::tryFindVirtualCallTargets( 1056 std::vector<VirtualCallTarget> &TargetsForSlot, 1057 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset, 1058 ModuleSummaryIndex *ExportSummary) { 1059 for (const TypeMemberInfo &TM : TypeMemberInfos) { 1060 if (!TM.Bits->GV->isConstant()) 1061 return false; 1062 1063 // We cannot perform whole program devirtualization analysis on a vtable 1064 // with public LTO visibility. 1065 if (TM.Bits->GV->getVCallVisibility() == 1066 GlobalObject::VCallVisibilityPublic) 1067 return false; 1068 1069 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(), 1070 TM.Offset + ByteOffset, M, TM.Bits->GV); 1071 if (!Ptr) 1072 return false; 1073 1074 auto C = Ptr->stripPointerCasts(); 1075 // Make sure this is a function or alias to a function. 1076 auto Fn = dyn_cast<Function>(C); 1077 auto A = dyn_cast<GlobalAlias>(C); 1078 if (!Fn && A) 1079 Fn = dyn_cast<Function>(A->getAliasee()); 1080 1081 if (!Fn) 1082 return false; 1083 1084 if (FunctionsToSkip.match(Fn->getName())) 1085 return false; 1086 1087 // We can disregard __cxa_pure_virtual as a possible call target, as 1088 // calls to pure virtuals are UB. 1089 if (Fn->getName() == "__cxa_pure_virtual") 1090 continue; 1091 1092 // We can disregard unreachable functions as possible call targets, as 1093 // unreachable functions shouldn't be called. 1094 if (mustBeUnreachableFunction(Fn, ExportSummary)) 1095 continue; 1096 1097 // Save the symbol used in the vtable to use as the devirtualization 1098 // target. 1099 auto GV = dyn_cast<GlobalValue>(C); 1100 assert(GV); 1101 TargetsForSlot.push_back({GV, &TM}); 1102 } 1103 1104 // Give up if we couldn't find any targets. 1105 return !TargetsForSlot.empty(); 1106 } 1107 1108 bool DevirtIndex::tryFindVirtualCallTargets( 1109 std::vector<ValueInfo> &TargetsForSlot, 1110 const TypeIdCompatibleVtableInfo TIdInfo, uint64_t ByteOffset) { 1111 for (const TypeIdOffsetVtableInfo &P : TIdInfo) { 1112 // Find a representative copy of the vtable initializer. 1113 // We can have multiple available_externally, linkonce_odr and weak_odr 1114 // vtable initializers. We can also have multiple external vtable 1115 // initializers in the case of comdats, which we cannot check here. 1116 // The linker should give an error in this case. 1117 // 1118 // Also, handle the case of same-named local Vtables with the same path 1119 // and therefore the same GUID. This can happen if there isn't enough 1120 // distinguishing path when compiling the source file. In that case we 1121 // conservatively return false early. 1122 const GlobalVarSummary *VS = nullptr; 1123 bool LocalFound = false; 1124 for (const auto &S : P.VTableVI.getSummaryList()) { 1125 if (GlobalValue::isLocalLinkage(S->linkage())) { 1126 if (LocalFound) 1127 return false; 1128 LocalFound = true; 1129 } 1130 auto *CurVS = cast<GlobalVarSummary>(S->getBaseObject()); 1131 if (!CurVS->vTableFuncs().empty() || 1132 // Previously clang did not attach the necessary type metadata to 1133 // available_externally vtables, in which case there would not 1134 // be any vtable functions listed in the summary and we need 1135 // to treat this case conservatively (in case the bitcode is old). 1136 // However, we will also not have any vtable functions in the 1137 // case of a pure virtual base class. In that case we do want 1138 // to set VS to avoid treating it conservatively. 1139 !GlobalValue::isAvailableExternallyLinkage(S->linkage())) { 1140 VS = CurVS; 1141 // We cannot perform whole program devirtualization analysis on a vtable 1142 // with public LTO visibility. 1143 if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic) 1144 return false; 1145 } 1146 } 1147 // There will be no VS if all copies are available_externally having no 1148 // type metadata. In that case we can't safely perform WPD. 1149 if (!VS) 1150 return false; 1151 if (!VS->isLive()) 1152 continue; 1153 for (auto VTP : VS->vTableFuncs()) { 1154 if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset) 1155 continue; 1156 1157 if (mustBeUnreachableFunction(VTP.FuncVI)) 1158 continue; 1159 1160 TargetsForSlot.push_back(VTP.FuncVI); 1161 } 1162 } 1163 1164 // Give up if we couldn't find any targets. 1165 return !TargetsForSlot.empty(); 1166 } 1167 1168 void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo, 1169 Constant *TheFn, bool &IsExported) { 1170 // Don't devirtualize function if we're told to skip it 1171 // in -wholeprogramdevirt-skip. 1172 if (FunctionsToSkip.match(TheFn->stripPointerCasts()->getName())) 1173 return; 1174 auto Apply = [&](CallSiteInfo &CSInfo) { 1175 for (auto &&VCallSite : CSInfo.CallSites) { 1176 if (!OptimizedCalls.insert(&VCallSite.CB).second) 1177 continue; 1178 1179 if (RemarksEnabled) 1180 VCallSite.emitRemark("single-impl", 1181 TheFn->stripPointerCasts()->getName(), OREGetter); 1182 NumSingleImpl++; 1183 auto &CB = VCallSite.CB; 1184 assert(!CB.getCalledFunction() && "devirtualizing direct call?"); 1185 IRBuilder<> Builder(&CB); 1186 Value *Callee = 1187 Builder.CreateBitCast(TheFn, CB.getCalledOperand()->getType()); 1188 1189 // If trap checking is enabled, add support to compare the virtual 1190 // function pointer to the devirtualized target. In case of a mismatch, 1191 // perform a debug trap. 1192 if (DevirtCheckMode == WPDCheckMode::Trap) { 1193 auto *Cond = Builder.CreateICmpNE(CB.getCalledOperand(), Callee); 1194 Instruction *ThenTerm = 1195 SplitBlockAndInsertIfThen(Cond, &CB, /*Unreachable=*/false); 1196 Builder.SetInsertPoint(ThenTerm); 1197 Function *TrapFn = Intrinsic::getDeclaration(&M, Intrinsic::debugtrap); 1198 auto *CallTrap = Builder.CreateCall(TrapFn); 1199 CallTrap->setDebugLoc(CB.getDebugLoc()); 1200 } 1201 1202 // If fallback checking is enabled, add support to compare the virtual 1203 // function pointer to the devirtualized target. In case of a mismatch, 1204 // fall back to indirect call. 1205 if (DevirtCheckMode == WPDCheckMode::Fallback) { 1206 MDNode *Weights = 1207 MDBuilder(M.getContext()).createBranchWeights((1U << 20) - 1, 1); 1208 // Version the indirect call site. If the called value is equal to the 1209 // given callee, 'NewInst' will be executed, otherwise the original call 1210 // site will be executed. 1211 CallBase &NewInst = versionCallSite(CB, Callee, Weights); 1212 NewInst.setCalledOperand(Callee); 1213 // Since the new call site is direct, we must clear metadata that 1214 // is only appropriate for indirect calls. This includes !prof and 1215 // !callees metadata. 1216 NewInst.setMetadata(LLVMContext::MD_prof, nullptr); 1217 NewInst.setMetadata(LLVMContext::MD_callees, nullptr); 1218 // Additionally, we should remove them from the fallback indirect call, 1219 // so that we don't attempt to perform indirect call promotion later. 1220 CB.setMetadata(LLVMContext::MD_prof, nullptr); 1221 CB.setMetadata(LLVMContext::MD_callees, nullptr); 1222 } 1223 1224 // In either trapping or non-checking mode, devirtualize original call. 1225 else { 1226 // Devirtualize unconditionally. 1227 CB.setCalledOperand(Callee); 1228 // Since the call site is now direct, we must clear metadata that 1229 // is only appropriate for indirect calls. This includes !prof and 1230 // !callees metadata. 1231 CB.setMetadata(LLVMContext::MD_prof, nullptr); 1232 CB.setMetadata(LLVMContext::MD_callees, nullptr); 1233 if (CB.getCalledOperand() && 1234 CB.getOperandBundle(LLVMContext::OB_ptrauth)) { 1235 auto *NewCS = 1236 CallBase::removeOperandBundle(&CB, LLVMContext::OB_ptrauth, &CB); 1237 CB.replaceAllUsesWith(NewCS); 1238 // Schedule for deletion at the end of pass run. 1239 CallsWithPtrAuthBundleRemoved.push_back(&CB); 1240 } 1241 } 1242 1243 // This use is no longer unsafe. 1244 if (VCallSite.NumUnsafeUses) 1245 --*VCallSite.NumUnsafeUses; 1246 } 1247 if (CSInfo.isExported()) 1248 IsExported = true; 1249 CSInfo.markDevirt(); 1250 }; 1251 Apply(SlotInfo.CSInfo); 1252 for (auto &P : SlotInfo.ConstCSInfo) 1253 Apply(P.second); 1254 } 1255 1256 static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) { 1257 // We can't add calls if we haven't seen a definition 1258 if (Callee.getSummaryList().empty()) 1259 return false; 1260 1261 // Insert calls into the summary index so that the devirtualized targets 1262 // are eligible for import. 1263 // FIXME: Annotate type tests with hotness. For now, mark these as hot 1264 // to better ensure we have the opportunity to inline them. 1265 bool IsExported = false; 1266 auto &S = Callee.getSummaryList()[0]; 1267 CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* HasTailCall = */ false, 1268 /* RelBF = */ 0); 1269 auto AddCalls = [&](CallSiteInfo &CSInfo) { 1270 for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) { 1271 FS->addCall({Callee, CI}); 1272 IsExported |= S->modulePath() != FS->modulePath(); 1273 } 1274 for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) { 1275 FS->addCall({Callee, CI}); 1276 IsExported |= S->modulePath() != FS->modulePath(); 1277 } 1278 }; 1279 AddCalls(SlotInfo.CSInfo); 1280 for (auto &P : SlotInfo.ConstCSInfo) 1281 AddCalls(P.second); 1282 return IsExported; 1283 } 1284 1285 bool DevirtModule::trySingleImplDevirt( 1286 ModuleSummaryIndex *ExportSummary, 1287 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, 1288 WholeProgramDevirtResolution *Res) { 1289 // See if the program contains a single implementation of this virtual 1290 // function. 1291 auto *TheFn = TargetsForSlot[0].Fn; 1292 for (auto &&Target : TargetsForSlot) 1293 if (TheFn != Target.Fn) 1294 return false; 1295 1296 // If so, update each call site to call that implementation directly. 1297 if (RemarksEnabled || AreStatisticsEnabled()) 1298 TargetsForSlot[0].WasDevirt = true; 1299 1300 bool IsExported = false; 1301 applySingleImplDevirt(SlotInfo, TheFn, IsExported); 1302 if (!IsExported) 1303 return false; 1304 1305 // If the only implementation has local linkage, we must promote to external 1306 // to make it visible to thin LTO objects. We can only get here during the 1307 // ThinLTO export phase. 1308 if (TheFn->hasLocalLinkage()) { 1309 std::string NewName = (TheFn->getName() + ".llvm.merged").str(); 1310 1311 // Since we are renaming the function, any comdats with the same name must 1312 // also be renamed. This is required when targeting COFF, as the comdat name 1313 // must match one of the names of the symbols in the comdat. 1314 if (Comdat *C = TheFn->getComdat()) { 1315 if (C->getName() == TheFn->getName()) { 1316 Comdat *NewC = M.getOrInsertComdat(NewName); 1317 NewC->setSelectionKind(C->getSelectionKind()); 1318 for (GlobalObject &GO : M.global_objects()) 1319 if (GO.getComdat() == C) 1320 GO.setComdat(NewC); 1321 } 1322 } 1323 1324 TheFn->setLinkage(GlobalValue::ExternalLinkage); 1325 TheFn->setVisibility(GlobalValue::HiddenVisibility); 1326 TheFn->setName(NewName); 1327 } 1328 if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID())) 1329 // Any needed promotion of 'TheFn' has already been done during 1330 // LTO unit split, so we can ignore return value of AddCalls. 1331 AddCalls(SlotInfo, TheFnVI); 1332 1333 Res->TheKind = WholeProgramDevirtResolution::SingleImpl; 1334 Res->SingleImplName = std::string(TheFn->getName()); 1335 1336 return true; 1337 } 1338 1339 bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot, 1340 VTableSlotSummary &SlotSummary, 1341 VTableSlotInfo &SlotInfo, 1342 WholeProgramDevirtResolution *Res, 1343 std::set<ValueInfo> &DevirtTargets) { 1344 // See if the program contains a single implementation of this virtual 1345 // function. 1346 auto TheFn = TargetsForSlot[0]; 1347 for (auto &&Target : TargetsForSlot) 1348 if (TheFn != Target) 1349 return false; 1350 1351 // Don't devirtualize if we don't have target definition. 1352 auto Size = TheFn.getSummaryList().size(); 1353 if (!Size) 1354 return false; 1355 1356 // Don't devirtualize function if we're told to skip it 1357 // in -wholeprogramdevirt-skip. 1358 if (FunctionsToSkip.match(TheFn.name())) 1359 return false; 1360 1361 // If the summary list contains multiple summaries where at least one is 1362 // a local, give up, as we won't know which (possibly promoted) name to use. 1363 for (const auto &S : TheFn.getSummaryList()) 1364 if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1) 1365 return false; 1366 1367 // Collect functions devirtualized at least for one call site for stats. 1368 if (PrintSummaryDevirt || AreStatisticsEnabled()) 1369 DevirtTargets.insert(TheFn); 1370 1371 auto &S = TheFn.getSummaryList()[0]; 1372 bool IsExported = AddCalls(SlotInfo, TheFn); 1373 if (IsExported) 1374 ExportedGUIDs.insert(TheFn.getGUID()); 1375 1376 // Record in summary for use in devirtualization during the ThinLTO import 1377 // step. 1378 Res->TheKind = WholeProgramDevirtResolution::SingleImpl; 1379 if (GlobalValue::isLocalLinkage(S->linkage())) { 1380 if (IsExported) 1381 // If target is a local function and we are exporting it by 1382 // devirtualizing a call in another module, we need to record the 1383 // promoted name. 1384 Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal( 1385 TheFn.name(), ExportSummary.getModuleHash(S->modulePath())); 1386 else { 1387 LocalWPDTargetsMap[TheFn].push_back(SlotSummary); 1388 Res->SingleImplName = std::string(TheFn.name()); 1389 } 1390 } else 1391 Res->SingleImplName = std::string(TheFn.name()); 1392 1393 // Name will be empty if this thin link driven off of serialized combined 1394 // index (e.g. llvm-lto). However, WPD is not supported/invoked for the 1395 // legacy LTO API anyway. 1396 assert(!Res->SingleImplName.empty()); 1397 1398 return true; 1399 } 1400 1401 void DevirtModule::tryICallBranchFunnel( 1402 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, 1403 WholeProgramDevirtResolution *Res, VTableSlot Slot) { 1404 Triple T(M.getTargetTriple()); 1405 if (T.getArch() != Triple::x86_64) 1406 return; 1407 1408 if (TargetsForSlot.size() > ClThreshold) 1409 return; 1410 1411 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted; 1412 if (!HasNonDevirt) 1413 for (auto &P : SlotInfo.ConstCSInfo) 1414 if (!P.second.AllCallSitesDevirted) { 1415 HasNonDevirt = true; 1416 break; 1417 } 1418 1419 if (!HasNonDevirt) 1420 return; 1421 1422 FunctionType *FT = 1423 FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true); 1424 Function *JT; 1425 if (isa<MDString>(Slot.TypeID)) { 1426 JT = Function::Create(FT, Function::ExternalLinkage, 1427 M.getDataLayout().getProgramAddressSpace(), 1428 getGlobalName(Slot, {}, "branch_funnel"), &M); 1429 JT->setVisibility(GlobalValue::HiddenVisibility); 1430 } else { 1431 JT = Function::Create(FT, Function::InternalLinkage, 1432 M.getDataLayout().getProgramAddressSpace(), 1433 "branch_funnel", &M); 1434 } 1435 JT->addParamAttr(0, Attribute::Nest); 1436 1437 std::vector<Value *> JTArgs; 1438 JTArgs.push_back(JT->arg_begin()); 1439 for (auto &T : TargetsForSlot) { 1440 JTArgs.push_back(getMemberAddr(T.TM)); 1441 JTArgs.push_back(T.Fn); 1442 } 1443 1444 BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr); 1445 Function *Intr = 1446 Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {}); 1447 1448 auto *CI = CallInst::Create(Intr, JTArgs, "", BB); 1449 CI->setTailCallKind(CallInst::TCK_MustTail); 1450 ReturnInst::Create(M.getContext(), nullptr, BB); 1451 1452 bool IsExported = false; 1453 applyICallBranchFunnel(SlotInfo, JT, IsExported); 1454 if (IsExported) 1455 Res->TheKind = WholeProgramDevirtResolution::BranchFunnel; 1456 } 1457 1458 void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo, 1459 Constant *JT, bool &IsExported) { 1460 auto Apply = [&](CallSiteInfo &CSInfo) { 1461 if (CSInfo.isExported()) 1462 IsExported = true; 1463 if (CSInfo.AllCallSitesDevirted) 1464 return; 1465 1466 std::map<CallBase *, CallBase *> CallBases; 1467 for (auto &&VCallSite : CSInfo.CallSites) { 1468 CallBase &CB = VCallSite.CB; 1469 1470 if (CallBases.find(&CB) != CallBases.end()) { 1471 // When finding devirtualizable calls, it's possible to find the same 1472 // vtable passed to multiple llvm.type.test or llvm.type.checked.load 1473 // calls, which can cause duplicate call sites to be recorded in 1474 // [Const]CallSites. If we've already found one of these 1475 // call instances, just ignore it. It will be replaced later. 1476 continue; 1477 } 1478 1479 // Jump tables are only profitable if the retpoline mitigation is enabled. 1480 Attribute FSAttr = CB.getCaller()->getFnAttribute("target-features"); 1481 if (!FSAttr.isValid() || 1482 !FSAttr.getValueAsString().contains("+retpoline")) 1483 continue; 1484 1485 NumBranchFunnel++; 1486 if (RemarksEnabled) 1487 VCallSite.emitRemark("branch-funnel", 1488 JT->stripPointerCasts()->getName(), OREGetter); 1489 1490 // Pass the address of the vtable in the nest register, which is r10 on 1491 // x86_64. 1492 std::vector<Type *> NewArgs; 1493 NewArgs.push_back(Int8PtrTy); 1494 append_range(NewArgs, CB.getFunctionType()->params()); 1495 FunctionType *NewFT = 1496 FunctionType::get(CB.getFunctionType()->getReturnType(), NewArgs, 1497 CB.getFunctionType()->isVarArg()); 1498 PointerType *NewFTPtr = PointerType::getUnqual(NewFT); 1499 1500 IRBuilder<> IRB(&CB); 1501 std::vector<Value *> Args; 1502 Args.push_back(VCallSite.VTable); 1503 llvm::append_range(Args, CB.args()); 1504 1505 CallBase *NewCS = nullptr; 1506 if (isa<CallInst>(CB)) 1507 NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args); 1508 else 1509 NewCS = IRB.CreateInvoke(NewFT, IRB.CreateBitCast(JT, NewFTPtr), 1510 cast<InvokeInst>(CB).getNormalDest(), 1511 cast<InvokeInst>(CB).getUnwindDest(), Args); 1512 NewCS->setCallingConv(CB.getCallingConv()); 1513 1514 AttributeList Attrs = CB.getAttributes(); 1515 std::vector<AttributeSet> NewArgAttrs; 1516 NewArgAttrs.push_back(AttributeSet::get( 1517 M.getContext(), ArrayRef<Attribute>{Attribute::get( 1518 M.getContext(), Attribute::Nest)})); 1519 for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I) 1520 NewArgAttrs.push_back(Attrs.getParamAttrs(I)); 1521 NewCS->setAttributes( 1522 AttributeList::get(M.getContext(), Attrs.getFnAttrs(), 1523 Attrs.getRetAttrs(), NewArgAttrs)); 1524 1525 CallBases[&CB] = NewCS; 1526 1527 // This use is no longer unsafe. 1528 if (VCallSite.NumUnsafeUses) 1529 --*VCallSite.NumUnsafeUses; 1530 } 1531 // Don't mark as devirtualized because there may be callers compiled without 1532 // retpoline mitigation, which would mean that they are lowered to 1533 // llvm.type.test and therefore require an llvm.type.test resolution for the 1534 // type identifier. 1535 1536 for (auto &[Old, New] : CallBases) { 1537 Old->replaceAllUsesWith(New); 1538 Old->eraseFromParent(); 1539 } 1540 }; 1541 Apply(SlotInfo.CSInfo); 1542 for (auto &P : SlotInfo.ConstCSInfo) 1543 Apply(P.second); 1544 } 1545 1546 bool DevirtModule::tryEvaluateFunctionsWithArgs( 1547 MutableArrayRef<VirtualCallTarget> TargetsForSlot, 1548 ArrayRef<uint64_t> Args) { 1549 // Evaluate each function and store the result in each target's RetVal 1550 // field. 1551 for (VirtualCallTarget &Target : TargetsForSlot) { 1552 // TODO: Skip for now if the vtable symbol was an alias to a function, 1553 // need to evaluate whether it would be correct to analyze the aliasee 1554 // function for this optimization. 1555 auto Fn = dyn_cast<Function>(Target.Fn); 1556 if (!Fn) 1557 return false; 1558 1559 if (Fn->arg_size() != Args.size() + 1) 1560 return false; 1561 1562 Evaluator Eval(M.getDataLayout(), nullptr); 1563 SmallVector<Constant *, 2> EvalArgs; 1564 EvalArgs.push_back( 1565 Constant::getNullValue(Fn->getFunctionType()->getParamType(0))); 1566 for (unsigned I = 0; I != Args.size(); ++I) { 1567 auto *ArgTy = 1568 dyn_cast<IntegerType>(Fn->getFunctionType()->getParamType(I + 1)); 1569 if (!ArgTy) 1570 return false; 1571 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I])); 1572 } 1573 1574 Constant *RetVal; 1575 if (!Eval.EvaluateFunction(Fn, RetVal, EvalArgs) || 1576 !isa<ConstantInt>(RetVal)) 1577 return false; 1578 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue(); 1579 } 1580 return true; 1581 } 1582 1583 void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, 1584 uint64_t TheRetVal) { 1585 for (auto Call : CSInfo.CallSites) { 1586 if (!OptimizedCalls.insert(&Call.CB).second) 1587 continue; 1588 NumUniformRetVal++; 1589 Call.replaceAndErase( 1590 "uniform-ret-val", FnName, RemarksEnabled, OREGetter, 1591 ConstantInt::get(cast<IntegerType>(Call.CB.getType()), TheRetVal)); 1592 } 1593 CSInfo.markDevirt(); 1594 } 1595 1596 bool DevirtModule::tryUniformRetValOpt( 1597 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo, 1598 WholeProgramDevirtResolution::ByArg *Res) { 1599 // Uniform return value optimization. If all functions return the same 1600 // constant, replace all calls with that constant. 1601 uint64_t TheRetVal = TargetsForSlot[0].RetVal; 1602 for (const VirtualCallTarget &Target : TargetsForSlot) 1603 if (Target.RetVal != TheRetVal) 1604 return false; 1605 1606 if (CSInfo.isExported()) { 1607 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 1608 Res->Info = TheRetVal; 1609 } 1610 1611 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal); 1612 if (RemarksEnabled || AreStatisticsEnabled()) 1613 for (auto &&Target : TargetsForSlot) 1614 Target.WasDevirt = true; 1615 return true; 1616 } 1617 1618 std::string DevirtModule::getGlobalName(VTableSlot Slot, 1619 ArrayRef<uint64_t> Args, 1620 StringRef Name) { 1621 std::string FullName = "__typeid_"; 1622 raw_string_ostream OS(FullName); 1623 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset; 1624 for (uint64_t Arg : Args) 1625 OS << '_' << Arg; 1626 OS << '_' << Name; 1627 return OS.str(); 1628 } 1629 1630 bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() { 1631 Triple T(M.getTargetTriple()); 1632 return T.isX86() && T.getObjectFormat() == Triple::ELF; 1633 } 1634 1635 void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, 1636 StringRef Name, Constant *C) { 1637 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage, 1638 getGlobalName(Slot, Args, Name), C, &M); 1639 GA->setVisibility(GlobalValue::HiddenVisibility); 1640 } 1641 1642 void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, 1643 StringRef Name, uint32_t Const, 1644 uint32_t &Storage) { 1645 if (shouldExportConstantsAsAbsoluteSymbols()) { 1646 exportGlobal( 1647 Slot, Args, Name, 1648 ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy)); 1649 return; 1650 } 1651 1652 Storage = Const; 1653 } 1654 1655 Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, 1656 StringRef Name) { 1657 Constant *C = 1658 M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty); 1659 auto *GV = dyn_cast<GlobalVariable>(C); 1660 if (GV) 1661 GV->setVisibility(GlobalValue::HiddenVisibility); 1662 return C; 1663 } 1664 1665 Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, 1666 StringRef Name, IntegerType *IntTy, 1667 uint32_t Storage) { 1668 if (!shouldExportConstantsAsAbsoluteSymbols()) 1669 return ConstantInt::get(IntTy, Storage); 1670 1671 Constant *C = importGlobal(Slot, Args, Name); 1672 auto *GV = cast<GlobalVariable>(C->stripPointerCasts()); 1673 C = ConstantExpr::getPtrToInt(C, IntTy); 1674 1675 // We only need to set metadata if the global is newly created, in which 1676 // case it would not have hidden visibility. 1677 if (GV->hasMetadata(LLVMContext::MD_absolute_symbol)) 1678 return C; 1679 1680 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) { 1681 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min)); 1682 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max)); 1683 GV->setMetadata(LLVMContext::MD_absolute_symbol, 1684 MDNode::get(M.getContext(), {MinC, MaxC})); 1685 }; 1686 unsigned AbsWidth = IntTy->getBitWidth(); 1687 if (AbsWidth == IntPtrTy->getBitWidth()) 1688 SetAbsRange(~0ull, ~0ull); // Full set. 1689 else 1690 SetAbsRange(0, 1ull << AbsWidth); 1691 return C; 1692 } 1693 1694 void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, 1695 bool IsOne, 1696 Constant *UniqueMemberAddr) { 1697 for (auto &&Call : CSInfo.CallSites) { 1698 if (!OptimizedCalls.insert(&Call.CB).second) 1699 continue; 1700 IRBuilder<> B(&Call.CB); 1701 Value *Cmp = 1702 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, Call.VTable, 1703 B.CreateBitCast(UniqueMemberAddr, Call.VTable->getType())); 1704 Cmp = B.CreateZExt(Cmp, Call.CB.getType()); 1705 NumUniqueRetVal++; 1706 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter, 1707 Cmp); 1708 } 1709 CSInfo.markDevirt(); 1710 } 1711 1712 Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) { 1713 return ConstantExpr::getGetElementPtr(Int8Ty, M->Bits->GV, 1714 ConstantInt::get(Int64Ty, M->Offset)); 1715 } 1716 1717 bool DevirtModule::tryUniqueRetValOpt( 1718 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot, 1719 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res, 1720 VTableSlot Slot, ArrayRef<uint64_t> Args) { 1721 // IsOne controls whether we look for a 0 or a 1. 1722 auto tryUniqueRetValOptFor = [&](bool IsOne) { 1723 const TypeMemberInfo *UniqueMember = nullptr; 1724 for (const VirtualCallTarget &Target : TargetsForSlot) { 1725 if (Target.RetVal == (IsOne ? 1 : 0)) { 1726 if (UniqueMember) 1727 return false; 1728 UniqueMember = Target.TM; 1729 } 1730 } 1731 1732 // We should have found a unique member or bailed out by now. We already 1733 // checked for a uniform return value in tryUniformRetValOpt. 1734 assert(UniqueMember); 1735 1736 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember); 1737 if (CSInfo.isExported()) { 1738 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 1739 Res->Info = IsOne; 1740 1741 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr); 1742 } 1743 1744 // Replace each call with the comparison. 1745 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne, 1746 UniqueMemberAddr); 1747 1748 // Update devirtualization statistics for targets. 1749 if (RemarksEnabled || AreStatisticsEnabled()) 1750 for (auto &&Target : TargetsForSlot) 1751 Target.WasDevirt = true; 1752 1753 return true; 1754 }; 1755 1756 if (BitWidth == 1) { 1757 if (tryUniqueRetValOptFor(true)) 1758 return true; 1759 if (tryUniqueRetValOptFor(false)) 1760 return true; 1761 } 1762 return false; 1763 } 1764 1765 void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, 1766 Constant *Byte, Constant *Bit) { 1767 for (auto Call : CSInfo.CallSites) { 1768 if (!OptimizedCalls.insert(&Call.CB).second) 1769 continue; 1770 auto *RetType = cast<IntegerType>(Call.CB.getType()); 1771 IRBuilder<> B(&Call.CB); 1772 Value *Addr = B.CreatePtrAdd(Call.VTable, Byte); 1773 if (RetType->getBitWidth() == 1) { 1774 Value *Bits = B.CreateLoad(Int8Ty, Addr); 1775 Value *BitsAndBit = B.CreateAnd(Bits, Bit); 1776 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); 1777 NumVirtConstProp1Bit++; 1778 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled, 1779 OREGetter, IsBitSet); 1780 } else { 1781 Value *Val = B.CreateLoad(RetType, Addr); 1782 NumVirtConstProp++; 1783 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, 1784 OREGetter, Val); 1785 } 1786 } 1787 CSInfo.markDevirt(); 1788 } 1789 1790 bool DevirtModule::tryVirtualConstProp( 1791 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, 1792 WholeProgramDevirtResolution *Res, VTableSlot Slot) { 1793 // TODO: Skip for now if the vtable symbol was an alias to a function, 1794 // need to evaluate whether it would be correct to analyze the aliasee 1795 // function for this optimization. 1796 auto Fn = dyn_cast<Function>(TargetsForSlot[0].Fn); 1797 if (!Fn) 1798 return false; 1799 // This only works if the function returns an integer. 1800 auto RetType = dyn_cast<IntegerType>(Fn->getReturnType()); 1801 if (!RetType) 1802 return false; 1803 unsigned BitWidth = RetType->getBitWidth(); 1804 if (BitWidth > 64) 1805 return false; 1806 1807 // Make sure that each function is defined, does not access memory, takes at 1808 // least one argument, does not use its first argument (which we assume is 1809 // 'this'), and has the same return type. 1810 // 1811 // Note that we test whether this copy of the function is readnone, rather 1812 // than testing function attributes, which must hold for any copy of the 1813 // function, even a less optimized version substituted at link time. This is 1814 // sound because the virtual constant propagation optimizations effectively 1815 // inline all implementations of the virtual function into each call site, 1816 // rather than using function attributes to perform local optimization. 1817 for (VirtualCallTarget &Target : TargetsForSlot) { 1818 // TODO: Skip for now if the vtable symbol was an alias to a function, 1819 // need to evaluate whether it would be correct to analyze the aliasee 1820 // function for this optimization. 1821 auto Fn = dyn_cast<Function>(Target.Fn); 1822 if (!Fn) 1823 return false; 1824 1825 if (Fn->isDeclaration() || 1826 !computeFunctionBodyMemoryAccess(*Fn, AARGetter(*Fn)) 1827 .doesNotAccessMemory() || 1828 Fn->arg_empty() || !Fn->arg_begin()->use_empty() || 1829 Fn->getReturnType() != RetType) 1830 return false; 1831 } 1832 1833 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) { 1834 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first)) 1835 continue; 1836 1837 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr; 1838 if (Res) 1839 ResByArg = &Res->ResByArg[CSByConstantArg.first]; 1840 1841 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg)) 1842 continue; 1843 1844 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second, 1845 ResByArg, Slot, CSByConstantArg.first)) 1846 continue; 1847 1848 // Find an allocation offset in bits in all vtables associated with the 1849 // type. 1850 uint64_t AllocBefore = 1851 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); 1852 uint64_t AllocAfter = 1853 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); 1854 1855 // Calculate the total amount of padding needed to store a value at both 1856 // ends of the object. 1857 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; 1858 for (auto &&Target : TargetsForSlot) { 1859 TotalPaddingBefore += std::max<int64_t>( 1860 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); 1861 TotalPaddingAfter += std::max<int64_t>( 1862 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); 1863 } 1864 1865 // If the amount of padding is too large, give up. 1866 // FIXME: do something smarter here. 1867 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) 1868 continue; 1869 1870 // Calculate the offset to the value as a (possibly negative) byte offset 1871 // and (if applicable) a bit offset, and store the values in the targets. 1872 int64_t OffsetByte; 1873 uint64_t OffsetBit; 1874 if (TotalPaddingBefore <= TotalPaddingAfter) 1875 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, 1876 OffsetBit); 1877 else 1878 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, 1879 OffsetBit); 1880 1881 if (RemarksEnabled || AreStatisticsEnabled()) 1882 for (auto &&Target : TargetsForSlot) 1883 Target.WasDevirt = true; 1884 1885 1886 if (CSByConstantArg.second.isExported()) { 1887 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 1888 exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte, 1889 ResByArg->Byte); 1890 exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit, 1891 ResByArg->Bit); 1892 } 1893 1894 // Rewrite each call to a load from OffsetByte/OffsetBit. 1895 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte); 1896 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit); 1897 applyVirtualConstProp(CSByConstantArg.second, 1898 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst); 1899 } 1900 return true; 1901 } 1902 1903 void DevirtModule::rebuildGlobal(VTableBits &B) { 1904 if (B.Before.Bytes.empty() && B.After.Bytes.empty()) 1905 return; 1906 1907 // Align the before byte array to the global's minimum alignment so that we 1908 // don't break any alignment requirements on the global. 1909 Align Alignment = M.getDataLayout().getValueOrABITypeAlignment( 1910 B.GV->getAlign(), B.GV->getValueType()); 1911 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment)); 1912 1913 // Before was stored in reverse order; flip it now. 1914 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I) 1915 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]); 1916 1917 // Build an anonymous global containing the before bytes, followed by the 1918 // original initializer, followed by the after bytes. 1919 auto NewInit = ConstantStruct::getAnon( 1920 {ConstantDataArray::get(M.getContext(), B.Before.Bytes), 1921 B.GV->getInitializer(), 1922 ConstantDataArray::get(M.getContext(), B.After.Bytes)}); 1923 auto NewGV = 1924 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(), 1925 GlobalVariable::PrivateLinkage, NewInit, "", B.GV); 1926 NewGV->setSection(B.GV->getSection()); 1927 NewGV->setComdat(B.GV->getComdat()); 1928 NewGV->setAlignment(B.GV->getAlign()); 1929 1930 // Copy the original vtable's metadata to the anonymous global, adjusting 1931 // offsets as required. 1932 NewGV->copyMetadata(B.GV, B.Before.Bytes.size()); 1933 1934 // Build an alias named after the original global, pointing at the second 1935 // element (the original initializer). 1936 auto Alias = GlobalAlias::create( 1937 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", 1938 ConstantExpr::getGetElementPtr( 1939 NewInit->getType(), NewGV, 1940 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0), 1941 ConstantInt::get(Int32Ty, 1)}), 1942 &M); 1943 Alias->setVisibility(B.GV->getVisibility()); 1944 Alias->takeName(B.GV); 1945 1946 B.GV->replaceAllUsesWith(Alias); 1947 B.GV->eraseFromParent(); 1948 } 1949 1950 bool DevirtModule::areRemarksEnabled() { 1951 const auto &FL = M.getFunctionList(); 1952 for (const Function &Fn : FL) { 1953 if (Fn.empty()) 1954 continue; 1955 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &Fn.front()); 1956 return DI.isEnabled(); 1957 } 1958 return false; 1959 } 1960 1961 void DevirtModule::scanTypeTestUsers( 1962 Function *TypeTestFunc, 1963 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { 1964 // Find all virtual calls via a virtual table pointer %p under an assumption 1965 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p 1966 // points to a member of the type identifier %md. Group calls by (type ID, 1967 // offset) pair (effectively the identity of the virtual function) and store 1968 // to CallSlots. 1969 for (Use &U : llvm::make_early_inc_range(TypeTestFunc->uses())) { 1970 auto *CI = dyn_cast<CallInst>(U.getUser()); 1971 if (!CI) 1972 continue; 1973 1974 // Search for virtual calls based on %p and add them to DevirtCalls. 1975 SmallVector<DevirtCallSite, 1> DevirtCalls; 1976 SmallVector<CallInst *, 1> Assumes; 1977 auto &DT = LookupDomTree(*CI->getFunction()); 1978 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT); 1979 1980 Metadata *TypeId = 1981 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata(); 1982 // If we found any, add them to CallSlots. 1983 if (!Assumes.empty()) { 1984 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); 1985 for (DevirtCallSite Call : DevirtCalls) 1986 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, nullptr); 1987 } 1988 1989 auto RemoveTypeTestAssumes = [&]() { 1990 // We no longer need the assumes or the type test. 1991 for (auto *Assume : Assumes) 1992 Assume->eraseFromParent(); 1993 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we 1994 // may use the vtable argument later. 1995 if (CI->use_empty()) 1996 CI->eraseFromParent(); 1997 }; 1998 1999 // At this point we could remove all type test assume sequences, as they 2000 // were originally inserted for WPD. However, we can keep these in the 2001 // code stream for later analysis (e.g. to help drive more efficient ICP 2002 // sequences). They will eventually be removed by a second LowerTypeTests 2003 // invocation that cleans them up. In order to do this correctly, the first 2004 // LowerTypeTests invocation needs to know that they have "Unknown" type 2005 // test resolution, so that they aren't treated as Unsat and lowered to 2006 // False, which will break any uses on assumes. Below we remove any type 2007 // test assumes that will not be treated as Unknown by LTT. 2008 2009 // The type test assumes will be treated by LTT as Unsat if the type id is 2010 // not used on a global (in which case it has no entry in the TypeIdMap). 2011 if (!TypeIdMap.count(TypeId)) 2012 RemoveTypeTestAssumes(); 2013 2014 // For ThinLTO importing, we need to remove the type test assumes if this is 2015 // an MDString type id without a corresponding TypeIdSummary. Any 2016 // non-MDString type ids are ignored and treated as Unknown by LTT, so their 2017 // type test assumes can be kept. If the MDString type id is missing a 2018 // TypeIdSummary (e.g. because there was no use on a vcall, preventing the 2019 // exporting phase of WPD from analyzing it), then it would be treated as 2020 // Unsat by LTT and we need to remove its type test assumes here. If not 2021 // used on a vcall we don't need them for later optimization use in any 2022 // case. 2023 else if (ImportSummary && isa<MDString>(TypeId)) { 2024 const TypeIdSummary *TidSummary = 2025 ImportSummary->getTypeIdSummary(cast<MDString>(TypeId)->getString()); 2026 if (!TidSummary) 2027 RemoveTypeTestAssumes(); 2028 else 2029 // If one was created it should not be Unsat, because if we reached here 2030 // the type id was used on a global. 2031 assert(TidSummary->TTRes.TheKind != TypeTestResolution::Unsat); 2032 } 2033 } 2034 } 2035 2036 void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) { 2037 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test); 2038 2039 for (Use &U : llvm::make_early_inc_range(TypeCheckedLoadFunc->uses())) { 2040 auto *CI = dyn_cast<CallInst>(U.getUser()); 2041 if (!CI) 2042 continue; 2043 2044 Value *Ptr = CI->getArgOperand(0); 2045 Value *Offset = CI->getArgOperand(1); 2046 Value *TypeIdValue = CI->getArgOperand(2); 2047 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata(); 2048 2049 SmallVector<DevirtCallSite, 1> DevirtCalls; 2050 SmallVector<Instruction *, 1> LoadedPtrs; 2051 SmallVector<Instruction *, 1> Preds; 2052 bool HasNonCallUses = false; 2053 auto &DT = LookupDomTree(*CI->getFunction()); 2054 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, 2055 HasNonCallUses, CI, DT); 2056 2057 // Start by generating "pessimistic" code that explicitly loads the function 2058 // pointer from the vtable and performs the type check. If possible, we will 2059 // eliminate the load and the type check later. 2060 2061 // If possible, only generate the load at the point where it is used. 2062 // This helps avoid unnecessary spills. 2063 IRBuilder<> LoadB( 2064 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI); 2065 2066 Value *LoadedValue = nullptr; 2067 if (TypeCheckedLoadFunc->getIntrinsicID() == 2068 Intrinsic::type_checked_load_relative) { 2069 Value *GEP = LoadB.CreatePtrAdd(Ptr, Offset); 2070 LoadedValue = LoadB.CreateLoad(Int32Ty, GEP); 2071 LoadedValue = LoadB.CreateSExt(LoadedValue, IntPtrTy); 2072 GEP = LoadB.CreatePtrToInt(GEP, IntPtrTy); 2073 LoadedValue = LoadB.CreateAdd(GEP, LoadedValue); 2074 LoadedValue = LoadB.CreateIntToPtr(LoadedValue, Int8PtrTy); 2075 } else { 2076 Value *GEP = LoadB.CreatePtrAdd(Ptr, Offset); 2077 LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEP); 2078 } 2079 2080 for (Instruction *LoadedPtr : LoadedPtrs) { 2081 LoadedPtr->replaceAllUsesWith(LoadedValue); 2082 LoadedPtr->eraseFromParent(); 2083 } 2084 2085 // Likewise for the type test. 2086 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI); 2087 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue}); 2088 2089 for (Instruction *Pred : Preds) { 2090 Pred->replaceAllUsesWith(TypeTestCall); 2091 Pred->eraseFromParent(); 2092 } 2093 2094 // We have already erased any extractvalue instructions that refer to the 2095 // intrinsic call, but the intrinsic may have other non-extractvalue uses 2096 // (although this is unlikely). In that case, explicitly build a pair and 2097 // RAUW it. 2098 if (!CI->use_empty()) { 2099 Value *Pair = PoisonValue::get(CI->getType()); 2100 IRBuilder<> B(CI); 2101 Pair = B.CreateInsertValue(Pair, LoadedValue, {0}); 2102 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1}); 2103 CI->replaceAllUsesWith(Pair); 2104 } 2105 2106 // The number of unsafe uses is initially the number of uses. 2107 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall]; 2108 NumUnsafeUses = DevirtCalls.size(); 2109 2110 // If the function pointer has a non-call user, we cannot eliminate the type 2111 // check, as one of those users may eventually call the pointer. Increment 2112 // the unsafe use count to make sure it cannot reach zero. 2113 if (HasNonCallUses) 2114 ++NumUnsafeUses; 2115 for (DevirtCallSite Call : DevirtCalls) { 2116 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, 2117 &NumUnsafeUses); 2118 } 2119 2120 CI->eraseFromParent(); 2121 } 2122 } 2123 2124 void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) { 2125 auto *TypeId = dyn_cast<MDString>(Slot.TypeID); 2126 if (!TypeId) 2127 return; 2128 const TypeIdSummary *TidSummary = 2129 ImportSummary->getTypeIdSummary(TypeId->getString()); 2130 if (!TidSummary) 2131 return; 2132 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset); 2133 if (ResI == TidSummary->WPDRes.end()) 2134 return; 2135 const WholeProgramDevirtResolution &Res = ResI->second; 2136 2137 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) { 2138 assert(!Res.SingleImplName.empty()); 2139 // The type of the function in the declaration is irrelevant because every 2140 // call site will cast it to the correct type. 2141 Constant *SingleImpl = 2142 cast<Constant>(M.getOrInsertFunction(Res.SingleImplName, 2143 Type::getVoidTy(M.getContext())) 2144 .getCallee()); 2145 2146 // This is the import phase so we should not be exporting anything. 2147 bool IsExported = false; 2148 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported); 2149 assert(!IsExported); 2150 } 2151 2152 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) { 2153 auto I = Res.ResByArg.find(CSByConstantArg.first); 2154 if (I == Res.ResByArg.end()) 2155 continue; 2156 auto &ResByArg = I->second; 2157 // FIXME: We should figure out what to do about the "function name" argument 2158 // to the apply* functions, as the function names are unavailable during the 2159 // importing phase. For now we just pass the empty string. This does not 2160 // impact correctness because the function names are just used for remarks. 2161 switch (ResByArg.TheKind) { 2162 case WholeProgramDevirtResolution::ByArg::UniformRetVal: 2163 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info); 2164 break; 2165 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: { 2166 Constant *UniqueMemberAddr = 2167 importGlobal(Slot, CSByConstantArg.first, "unique_member"); 2168 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info, 2169 UniqueMemberAddr); 2170 break; 2171 } 2172 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: { 2173 Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte", 2174 Int32Ty, ResByArg.Byte); 2175 Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty, 2176 ResByArg.Bit); 2177 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit); 2178 break; 2179 } 2180 default: 2181 break; 2182 } 2183 } 2184 2185 if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) { 2186 // The type of the function is irrelevant, because it's bitcast at calls 2187 // anyhow. 2188 Constant *JT = cast<Constant>( 2189 M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"), 2190 Type::getVoidTy(M.getContext())) 2191 .getCallee()); 2192 bool IsExported = false; 2193 applyICallBranchFunnel(SlotInfo, JT, IsExported); 2194 assert(!IsExported); 2195 } 2196 } 2197 2198 void DevirtModule::removeRedundantTypeTests() { 2199 auto True = ConstantInt::getTrue(M.getContext()); 2200 for (auto &&U : NumUnsafeUsesForTypeTest) { 2201 if (U.second == 0) { 2202 U.first->replaceAllUsesWith(True); 2203 U.first->eraseFromParent(); 2204 } 2205 } 2206 } 2207 2208 ValueInfo 2209 DevirtModule::lookUpFunctionValueInfo(Function *TheFn, 2210 ModuleSummaryIndex *ExportSummary) { 2211 assert((ExportSummary != nullptr) && 2212 "Caller guarantees ExportSummary is not nullptr"); 2213 2214 const auto TheFnGUID = TheFn->getGUID(); 2215 const auto TheFnGUIDWithExportedName = GlobalValue::getGUID(TheFn->getName()); 2216 // Look up ValueInfo with the GUID in the current linkage. 2217 ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFnGUID); 2218 // If no entry is found and GUID is different from GUID computed using 2219 // exported name, look up ValueInfo with the exported name unconditionally. 2220 // This is a fallback. 2221 // 2222 // The reason to have a fallback: 2223 // 1. LTO could enable global value internalization via 2224 // `enable-lto-internalization`. 2225 // 2. The GUID in ExportedSummary is computed using exported name. 2226 if ((!TheFnVI) && (TheFnGUID != TheFnGUIDWithExportedName)) { 2227 TheFnVI = ExportSummary->getValueInfo(TheFnGUIDWithExportedName); 2228 } 2229 return TheFnVI; 2230 } 2231 2232 bool DevirtModule::mustBeUnreachableFunction( 2233 Function *const F, ModuleSummaryIndex *ExportSummary) { 2234 // First, learn unreachability by analyzing function IR. 2235 if (!F->isDeclaration()) { 2236 // A function must be unreachable if its entry block ends with an 2237 // 'unreachable'. 2238 return isa<UnreachableInst>(F->getEntryBlock().getTerminator()); 2239 } 2240 // Learn unreachability from ExportSummary if ExportSummary is present. 2241 return ExportSummary && 2242 ::mustBeUnreachableFunction( 2243 DevirtModule::lookUpFunctionValueInfo(F, ExportSummary)); 2244 } 2245 2246 bool DevirtModule::run() { 2247 // If only some of the modules were split, we cannot correctly perform 2248 // this transformation. We already checked for the presense of type tests 2249 // with partially split modules during the thin link, and would have emitted 2250 // an error if any were found, so here we can simply return. 2251 if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) || 2252 (ImportSummary && ImportSummary->partiallySplitLTOUnits())) 2253 return false; 2254 2255 Function *TypeTestFunc = 2256 M.getFunction(Intrinsic::getName(Intrinsic::type_test)); 2257 Function *TypeCheckedLoadFunc = 2258 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load)); 2259 Function *TypeCheckedLoadRelativeFunc = 2260 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load_relative)); 2261 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume)); 2262 2263 // Normally if there are no users of the devirtualization intrinsics in the 2264 // module, this pass has nothing to do. But if we are exporting, we also need 2265 // to handle any users that appear only in the function summaries. 2266 if (!ExportSummary && 2267 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc || 2268 AssumeFunc->use_empty()) && 2269 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()) && 2270 (!TypeCheckedLoadRelativeFunc || 2271 TypeCheckedLoadRelativeFunc->use_empty())) 2272 return false; 2273 2274 // Rebuild type metadata into a map for easy lookup. 2275 std::vector<VTableBits> Bits; 2276 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap; 2277 buildTypeIdentifierMap(Bits, TypeIdMap); 2278 2279 if (TypeTestFunc && AssumeFunc) 2280 scanTypeTestUsers(TypeTestFunc, TypeIdMap); 2281 2282 if (TypeCheckedLoadFunc) 2283 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc); 2284 2285 if (TypeCheckedLoadRelativeFunc) 2286 scanTypeCheckedLoadUsers(TypeCheckedLoadRelativeFunc); 2287 2288 if (ImportSummary) { 2289 for (auto &S : CallSlots) 2290 importResolution(S.first, S.second); 2291 2292 removeRedundantTypeTests(); 2293 2294 // We have lowered or deleted the type intrinsics, so we will no longer have 2295 // enough information to reason about the liveness of virtual function 2296 // pointers in GlobalDCE. 2297 for (GlobalVariable &GV : M.globals()) 2298 GV.eraseMetadata(LLVMContext::MD_vcall_visibility); 2299 2300 // The rest of the code is only necessary when exporting or during regular 2301 // LTO, so we are done. 2302 return true; 2303 } 2304 2305 if (TypeIdMap.empty()) 2306 return true; 2307 2308 // Collect information from summary about which calls to try to devirtualize. 2309 if (ExportSummary) { 2310 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID; 2311 for (auto &P : TypeIdMap) { 2312 if (auto *TypeId = dyn_cast<MDString>(P.first)) 2313 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back( 2314 TypeId); 2315 } 2316 2317 for (auto &P : *ExportSummary) { 2318 for (auto &S : P.second.SummaryList) { 2319 auto *FS = dyn_cast<FunctionSummary>(S.get()); 2320 if (!FS) 2321 continue; 2322 // FIXME: Only add live functions. 2323 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { 2324 for (Metadata *MD : MetadataByGUID[VF.GUID]) { 2325 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS); 2326 } 2327 } 2328 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { 2329 for (Metadata *MD : MetadataByGUID[VF.GUID]) { 2330 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS); 2331 } 2332 } 2333 for (const FunctionSummary::ConstVCall &VC : 2334 FS->type_test_assume_const_vcalls()) { 2335 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { 2336 CallSlots[{MD, VC.VFunc.Offset}] 2337 .ConstCSInfo[VC.Args] 2338 .addSummaryTypeTestAssumeUser(FS); 2339 } 2340 } 2341 for (const FunctionSummary::ConstVCall &VC : 2342 FS->type_checked_load_const_vcalls()) { 2343 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { 2344 CallSlots[{MD, VC.VFunc.Offset}] 2345 .ConstCSInfo[VC.Args] 2346 .addSummaryTypeCheckedLoadUser(FS); 2347 } 2348 } 2349 } 2350 } 2351 } 2352 2353 // For each (type, offset) pair: 2354 bool DidVirtualConstProp = false; 2355 std::map<std::string, GlobalValue *> DevirtTargets; 2356 for (auto &S : CallSlots) { 2357 // Search each of the members of the type identifier for the virtual 2358 // function implementation at offset S.first.ByteOffset, and add to 2359 // TargetsForSlot. 2360 std::vector<VirtualCallTarget> TargetsForSlot; 2361 WholeProgramDevirtResolution *Res = nullptr; 2362 const std::set<TypeMemberInfo> &TypeMemberInfos = TypeIdMap[S.first.TypeID]; 2363 if (ExportSummary && isa<MDString>(S.first.TypeID) && 2364 TypeMemberInfos.size()) 2365 // For any type id used on a global's type metadata, create the type id 2366 // summary resolution regardless of whether we can devirtualize, so that 2367 // lower type tests knows the type id is not Unsat. If it was not used on 2368 // a global's type metadata, the TypeIdMap entry set will be empty, and 2369 // we don't want to create an entry (with the default Unknown type 2370 // resolution), which can prevent detection of the Unsat. 2371 Res = &ExportSummary 2372 ->getOrInsertTypeIdSummary( 2373 cast<MDString>(S.first.TypeID)->getString()) 2374 .WPDRes[S.first.ByteOffset]; 2375 if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos, 2376 S.first.ByteOffset, ExportSummary)) { 2377 2378 if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) { 2379 DidVirtualConstProp |= 2380 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first); 2381 2382 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first); 2383 } 2384 2385 // Collect functions devirtualized at least for one call site for stats. 2386 if (RemarksEnabled || AreStatisticsEnabled()) 2387 for (const auto &T : TargetsForSlot) 2388 if (T.WasDevirt) 2389 DevirtTargets[std::string(T.Fn->getName())] = T.Fn; 2390 } 2391 2392 // CFI-specific: if we are exporting and any llvm.type.checked.load 2393 // intrinsics were *not* devirtualized, we need to add the resulting 2394 // llvm.type.test intrinsics to the function summaries so that the 2395 // LowerTypeTests pass will export them. 2396 if (ExportSummary && isa<MDString>(S.first.TypeID)) { 2397 auto GUID = 2398 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString()); 2399 for (auto *FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers) 2400 FS->addTypeTest(GUID); 2401 for (auto &CCS : S.second.ConstCSInfo) 2402 for (auto *FS : CCS.second.SummaryTypeCheckedLoadUsers) 2403 FS->addTypeTest(GUID); 2404 } 2405 } 2406 2407 if (RemarksEnabled) { 2408 // Generate remarks for each devirtualized function. 2409 for (const auto &DT : DevirtTargets) { 2410 GlobalValue *GV = DT.second; 2411 auto F = dyn_cast<Function>(GV); 2412 if (!F) { 2413 auto A = dyn_cast<GlobalAlias>(GV); 2414 assert(A && isa<Function>(A->getAliasee())); 2415 F = dyn_cast<Function>(A->getAliasee()); 2416 assert(F); 2417 } 2418 2419 using namespace ore; 2420 OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F) 2421 << "devirtualized " 2422 << NV("FunctionName", DT.first)); 2423 } 2424 } 2425 2426 NumDevirtTargets += DevirtTargets.size(); 2427 2428 removeRedundantTypeTests(); 2429 2430 // Rebuild each global we touched as part of virtual constant propagation to 2431 // include the before and after bytes. 2432 if (DidVirtualConstProp) 2433 for (VTableBits &B : Bits) 2434 rebuildGlobal(B); 2435 2436 // We have lowered or deleted the type intrinsics, so we will no longer have 2437 // enough information to reason about the liveness of virtual function 2438 // pointers in GlobalDCE. 2439 for (GlobalVariable &GV : M.globals()) 2440 GV.eraseMetadata(LLVMContext::MD_vcall_visibility); 2441 2442 for (auto *CI : CallsWithPtrAuthBundleRemoved) 2443 CI->eraseFromParent(); 2444 2445 return true; 2446 } 2447 2448 void DevirtIndex::run() { 2449 if (ExportSummary.typeIdCompatibleVtableMap().empty()) 2450 return; 2451 2452 DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID; 2453 for (const auto &P : ExportSummary.typeIdCompatibleVtableMap()) { 2454 NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first); 2455 // Create the type id summary resolution regardlness of whether we can 2456 // devirtualize, so that lower type tests knows the type id is used on 2457 // a global and not Unsat. We do this here rather than in the loop over the 2458 // CallSlots, since that handling will only see type tests that directly 2459 // feed assumes, and we would miss any that aren't currently handled by WPD 2460 // (such as type tests that feed assumes via phis). 2461 ExportSummary.getOrInsertTypeIdSummary(P.first); 2462 } 2463 2464 // Collect information from summary about which calls to try to devirtualize. 2465 for (auto &P : ExportSummary) { 2466 for (auto &S : P.second.SummaryList) { 2467 auto *FS = dyn_cast<FunctionSummary>(S.get()); 2468 if (!FS) 2469 continue; 2470 // FIXME: Only add live functions. 2471 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { 2472 for (StringRef Name : NameByGUID[VF.GUID]) { 2473 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS); 2474 } 2475 } 2476 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { 2477 for (StringRef Name : NameByGUID[VF.GUID]) { 2478 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS); 2479 } 2480 } 2481 for (const FunctionSummary::ConstVCall &VC : 2482 FS->type_test_assume_const_vcalls()) { 2483 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) { 2484 CallSlots[{Name, VC.VFunc.Offset}] 2485 .ConstCSInfo[VC.Args] 2486 .addSummaryTypeTestAssumeUser(FS); 2487 } 2488 } 2489 for (const FunctionSummary::ConstVCall &VC : 2490 FS->type_checked_load_const_vcalls()) { 2491 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) { 2492 CallSlots[{Name, VC.VFunc.Offset}] 2493 .ConstCSInfo[VC.Args] 2494 .addSummaryTypeCheckedLoadUser(FS); 2495 } 2496 } 2497 } 2498 } 2499 2500 std::set<ValueInfo> DevirtTargets; 2501 // For each (type, offset) pair: 2502 for (auto &S : CallSlots) { 2503 // Search each of the members of the type identifier for the virtual 2504 // function implementation at offset S.first.ByteOffset, and add to 2505 // TargetsForSlot. 2506 std::vector<ValueInfo> TargetsForSlot; 2507 auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID); 2508 assert(TidSummary); 2509 // The type id summary would have been created while building the NameByGUID 2510 // map earlier. 2511 WholeProgramDevirtResolution *Res = 2512 &ExportSummary.getTypeIdSummary(S.first.TypeID) 2513 ->WPDRes[S.first.ByteOffset]; 2514 if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary, 2515 S.first.ByteOffset)) { 2516 2517 if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res, 2518 DevirtTargets)) 2519 continue; 2520 } 2521 } 2522 2523 // Optionally have the thin link print message for each devirtualized 2524 // function. 2525 if (PrintSummaryDevirt) 2526 for (const auto &DT : DevirtTargets) 2527 errs() << "Devirtualized call to " << DT << "\n"; 2528 2529 NumDevirtTargets += DevirtTargets.size(); 2530 } 2531