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