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