1df49d1bbSPeter Collingbourne //===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===// 2df49d1bbSPeter Collingbourne // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6df49d1bbSPeter Collingbourne // 7df49d1bbSPeter Collingbourne //===----------------------------------------------------------------------===// 8df49d1bbSPeter Collingbourne // 9df49d1bbSPeter Collingbourne // This pass implements whole program optimization of virtual calls in cases 107efd7506SPeter Collingbourne // where we know (via !type metadata) that the list of callees is fixed. This 11df49d1bbSPeter Collingbourne // includes the following: 12df49d1bbSPeter Collingbourne // - Single implementation devirtualization: if a virtual call has a single 13df49d1bbSPeter Collingbourne // possible callee, replace all calls with a direct call to that callee. 14df49d1bbSPeter Collingbourne // - Virtual constant propagation: if the virtual function's return type is an 15df49d1bbSPeter Collingbourne // integer <=64 bits and all possible callees are readnone, for each class and 16df49d1bbSPeter Collingbourne // each list of constant arguments: evaluate the function, store the return 17df49d1bbSPeter Collingbourne // value alongside the virtual table, and rewrite each virtual call as a load 18df49d1bbSPeter Collingbourne // from the virtual table. 19df49d1bbSPeter Collingbourne // - Uniform return value optimization: if the conditions for virtual constant 20df49d1bbSPeter Collingbourne // propagation hold and each function returns the same constant value, replace 21df49d1bbSPeter Collingbourne // each virtual call with that constant. 22df49d1bbSPeter Collingbourne // - Unique return value optimization for i1 return values: if the conditions 23df49d1bbSPeter Collingbourne // for virtual constant propagation hold and a single vtable's function 24df49d1bbSPeter Collingbourne // returns 0, or a single vtable's function returns 1, replace each virtual 25df49d1bbSPeter Collingbourne // call with a comparison of the vptr against that vtable's address. 26df49d1bbSPeter Collingbourne // 27d2df54e6STeresa Johnson // This pass is intended to be used during the regular and thin LTO pipelines: 28d2df54e6STeresa Johnson // 29b406baaeSPeter Collingbourne // During regular LTO, the pass determines the best optimization for each 30b406baaeSPeter Collingbourne // virtual call and applies the resolutions directly to virtual calls that are 31b406baaeSPeter Collingbourne // eligible for virtual call optimization (i.e. calls that use either of the 32d2df54e6STeresa Johnson // llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics). 33d2df54e6STeresa Johnson // 34d2df54e6STeresa Johnson // During hybrid Regular/ThinLTO, the pass operates in two phases: 35b406baaeSPeter Collingbourne // - Export phase: this is run during the thin link over a single merged module 36b406baaeSPeter Collingbourne // that contains all vtables with !type metadata that participate in the link. 37b406baaeSPeter Collingbourne // The pass computes a resolution for each virtual call and stores it in the 38b406baaeSPeter Collingbourne // type identifier summary. 39b406baaeSPeter Collingbourne // - Import phase: this is run during the thin backends over the individual 40b406baaeSPeter Collingbourne // modules. The pass applies the resolutions previously computed during the 41b406baaeSPeter Collingbourne // import phase to each eligible virtual call. 42b406baaeSPeter Collingbourne // 43d2df54e6STeresa Johnson // During ThinLTO, the pass operates in two phases: 44d2df54e6STeresa Johnson // - Export phase: this is run during the thin link over the index which 45d2df54e6STeresa Johnson // contains a summary of all vtables with !type metadata that participate in 46d2df54e6STeresa Johnson // the link. It computes a resolution for each virtual call and stores it in 47d2df54e6STeresa Johnson // the type identifier summary. Only single implementation devirtualization 48d2df54e6STeresa Johnson // is supported. 49d2df54e6STeresa Johnson // - Import phase: (same as with hybrid case above). 50d2df54e6STeresa Johnson // 51df49d1bbSPeter Collingbourne //===----------------------------------------------------------------------===// 52df49d1bbSPeter Collingbourne 53df49d1bbSPeter Collingbourne #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 54b550cb17SMehdi Amini #include "llvm/ADT/ArrayRef.h" 55cdc71612SEugene Zelenko #include "llvm/ADT/DenseMap.h" 56cdc71612SEugene Zelenko #include "llvm/ADT/DenseMapInfo.h" 57df49d1bbSPeter Collingbourne #include "llvm/ADT/DenseSet.h" 58df49d1bbSPeter Collingbourne #include "llvm/ADT/MapVector.h" 59cdc71612SEugene Zelenko #include "llvm/ADT/SmallVector.h" 6006fd973cSSimon Pilgrim #include "llvm/ADT/Triple.h" 616bda14b3SChandler Carruth #include "llvm/ADT/iterator_range.h" 622ce38b3fSdfukalov #include "llvm/Analysis/AssumptionCache.h" 6337317f12SPeter Collingbourne #include "llvm/Analysis/BasicAliasAnalysis.h" 640965da20SAdam Nemet #include "llvm/Analysis/OptimizationRemarkEmitter.h" 657efd7506SPeter Collingbourne #include "llvm/Analysis/TypeMetadataUtils.h" 668973fae1SEvgeny Leviant #include "llvm/Bitcode/BitcodeReader.h" 678973fae1SEvgeny Leviant #include "llvm/Bitcode/BitcodeWriter.h" 68df49d1bbSPeter Collingbourne #include "llvm/IR/Constants.h" 69df49d1bbSPeter Collingbourne #include "llvm/IR/DataLayout.h" 70cdc71612SEugene Zelenko #include "llvm/IR/DebugLoc.h" 71cdc71612SEugene Zelenko #include "llvm/IR/DerivedTypes.h" 72f24136f1STeresa Johnson #include "llvm/IR/Dominators.h" 73cdc71612SEugene Zelenko #include "llvm/IR/Function.h" 74cdc71612SEugene Zelenko #include "llvm/IR/GlobalAlias.h" 75cdc71612SEugene Zelenko #include "llvm/IR/GlobalVariable.h" 76df49d1bbSPeter Collingbourne #include "llvm/IR/IRBuilder.h" 77cdc71612SEugene Zelenko #include "llvm/IR/InstrTypes.h" 78cdc71612SEugene Zelenko #include "llvm/IR/Instruction.h" 79df49d1bbSPeter Collingbourne #include "llvm/IR/Instructions.h" 80df49d1bbSPeter Collingbourne #include "llvm/IR/Intrinsics.h" 81cdc71612SEugene Zelenko #include "llvm/IR/LLVMContext.h" 82cdc71612SEugene Zelenko #include "llvm/IR/Metadata.h" 83df49d1bbSPeter Collingbourne #include "llvm/IR/Module.h" 842b33f653SPeter Collingbourne #include "llvm/IR/ModuleSummaryIndexYAML.h" 8505da2fe5SReid Kleckner #include "llvm/InitializePasses.h" 86df49d1bbSPeter Collingbourne #include "llvm/Pass.h" 87cdc71612SEugene Zelenko #include "llvm/PassRegistry.h" 88cdc71612SEugene Zelenko #include "llvm/Support/Casting.h" 894c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h" 908973fae1SEvgeny Leviant #include "llvm/Support/Errc.h" 912b33f653SPeter Collingbourne #include "llvm/Support/Error.h" 922b33f653SPeter Collingbourne #include "llvm/Support/FileSystem.h" 936d2032e2Sevgeny #include "llvm/Support/GlobPattern.h" 94cdc71612SEugene Zelenko #include "llvm/Support/MathExtras.h" 95b550cb17SMehdi Amini #include "llvm/Transforms/IPO.h" 9637317f12SPeter Collingbourne #include "llvm/Transforms/IPO/FunctionAttrs.h" 97d55d46f4STeresa Johnson #include "llvm/Transforms/Utils/BasicBlockUtils.h" 98df49d1bbSPeter Collingbourne #include "llvm/Transforms/Utils/Evaluator.h" 99cdc71612SEugene Zelenko #include <algorithm> 100cdc71612SEugene Zelenko #include <cstddef> 101cdc71612SEugene Zelenko #include <map> 102df49d1bbSPeter Collingbourne #include <set> 103cdc71612SEugene Zelenko #include <string> 104df49d1bbSPeter Collingbourne 105df49d1bbSPeter Collingbourne using namespace llvm; 106df49d1bbSPeter Collingbourne using namespace wholeprogramdevirt; 107df49d1bbSPeter Collingbourne 108df49d1bbSPeter Collingbourne #define DEBUG_TYPE "wholeprogramdevirt" 109df49d1bbSPeter Collingbourne 1102b33f653SPeter Collingbourne static cl::opt<PassSummaryAction> ClSummaryAction( 1112b33f653SPeter Collingbourne "wholeprogramdevirt-summary-action", 1122b33f653SPeter Collingbourne cl::desc("What to do with the summary when running this pass"), 1132b33f653SPeter Collingbourne cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), 1142b33f653SPeter Collingbourne clEnumValN(PassSummaryAction::Import, "import", 1152b33f653SPeter Collingbourne "Import typeid resolutions from summary and globals"), 1162b33f653SPeter Collingbourne clEnumValN(PassSummaryAction::Export, "export", 1172b33f653SPeter Collingbourne "Export typeid resolutions to summary and globals")), 1182b33f653SPeter Collingbourne cl::Hidden); 1192b33f653SPeter Collingbourne 1202b33f653SPeter Collingbourne static cl::opt<std::string> ClReadSummary( 1212b33f653SPeter Collingbourne "wholeprogramdevirt-read-summary", 1228973fae1SEvgeny Leviant cl::desc( 1238973fae1SEvgeny Leviant "Read summary from given bitcode or YAML file before running pass"), 1242b33f653SPeter Collingbourne cl::Hidden); 1252b33f653SPeter Collingbourne 1262b33f653SPeter Collingbourne static cl::opt<std::string> ClWriteSummary( 1272b33f653SPeter Collingbourne "wholeprogramdevirt-write-summary", 1288973fae1SEvgeny Leviant cl::desc("Write summary to given bitcode or YAML file after running pass. " 1298973fae1SEvgeny Leviant "Output file format is deduced from extension: *.bc means writing " 1308973fae1SEvgeny Leviant "bitcode, otherwise YAML"), 1312b33f653SPeter Collingbourne cl::Hidden); 1322b33f653SPeter Collingbourne 1339cb59b92SVitaly Buka static cl::opt<unsigned> 1349cb59b92SVitaly Buka ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden, 1359cb59b92SVitaly Buka cl::init(10), cl::ZeroOrMore, 13666f53d71SVitaly Buka cl::desc("Maximum number of call targets per " 13766f53d71SVitaly Buka "call site to enable branch funnels")); 13866f53d71SVitaly Buka 139d2df54e6STeresa Johnson static cl::opt<bool> 140d2df54e6STeresa Johnson PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden, 141d2df54e6STeresa Johnson cl::init(false), cl::ZeroOrMore, 142d2df54e6STeresa Johnson cl::desc("Print index-based devirtualization messages")); 143d2df54e6STeresa Johnson 1442f63d549STeresa Johnson /// Provide a way to force enable whole program visibility in tests. 1452f63d549STeresa Johnson /// This is needed to support legacy tests that don't contain 1462f63d549STeresa Johnson /// !vcall_visibility metadata (the mere presense of type tests 1472f63d549STeresa Johnson /// previously implied hidden visibility). 148d8aba75aSFangrui Song static cl::opt<bool> 1492f63d549STeresa Johnson WholeProgramVisibility("whole-program-visibility", cl::init(false), 1502f63d549STeresa Johnson cl::Hidden, cl::ZeroOrMore, 1512f63d549STeresa Johnson cl::desc("Enable whole program visibility")); 1522f63d549STeresa Johnson 1532f63d549STeresa Johnson /// Provide a way to force disable whole program for debugging or workarounds, 1542f63d549STeresa Johnson /// when enabled via the linker. 155d8aba75aSFangrui Song static cl::opt<bool> DisableWholeProgramVisibility( 1562f63d549STeresa Johnson "disable-whole-program-visibility", cl::init(false), cl::Hidden, 1572f63d549STeresa Johnson cl::ZeroOrMore, 1582f63d549STeresa Johnson cl::desc("Disable whole program visibility (overrides enabling options)")); 1592f63d549STeresa Johnson 1606d2032e2Sevgeny /// Provide way to prevent certain function from being devirtualized 161d8aba75aSFangrui Song static cl::list<std::string> 1626d2032e2Sevgeny SkipFunctionNames("wholeprogramdevirt-skip", 1636d2032e2Sevgeny cl::desc("Prevent function(s) from being devirtualized"), 1646d2032e2Sevgeny cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated); 1656d2032e2Sevgeny 166d55d46f4STeresa Johnson /// Mechanism to add runtime checking of devirtualization decisions, trapping on 167d55d46f4STeresa Johnson /// any that are not correct. Useful for debugging undefined behavior leading to 168d55d46f4STeresa Johnson /// failures with WPD. 169d8aba75aSFangrui Song static cl::opt<bool> 170d55d46f4STeresa Johnson CheckDevirt("wholeprogramdevirt-check", cl::init(false), cl::Hidden, 171d55d46f4STeresa Johnson cl::ZeroOrMore, 172d55d46f4STeresa Johnson cl::desc("Add code to trap on incorrect devirtualizations")); 173d55d46f4STeresa Johnson 1746d2032e2Sevgeny namespace { 1756d2032e2Sevgeny struct PatternList { 1766d2032e2Sevgeny std::vector<GlobPattern> Patterns; 1776d2032e2Sevgeny template <class T> void init(const T &StringList) { 1786d2032e2Sevgeny for (const auto &S : StringList) 1796d2032e2Sevgeny if (Expected<GlobPattern> Pat = GlobPattern::create(S)) 1806d2032e2Sevgeny Patterns.push_back(std::move(*Pat)); 1816d2032e2Sevgeny } 1826d2032e2Sevgeny bool match(StringRef S) { 1836d2032e2Sevgeny for (const GlobPattern &P : Patterns) 1846d2032e2Sevgeny if (P.match(S)) 1856d2032e2Sevgeny return true; 1866d2032e2Sevgeny return false; 1876d2032e2Sevgeny } 1886d2032e2Sevgeny }; 1896d2032e2Sevgeny } // namespace 1906d2032e2Sevgeny 191df49d1bbSPeter Collingbourne // Find the minimum offset that we may store a value of size Size bits at. If 192df49d1bbSPeter Collingbourne // IsAfter is set, look for an offset before the object, otherwise look for an 193df49d1bbSPeter Collingbourne // offset after the object. 194df49d1bbSPeter Collingbourne uint64_t 195df49d1bbSPeter Collingbourne wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets, 196df49d1bbSPeter Collingbourne bool IsAfter, uint64_t Size) { 197df49d1bbSPeter Collingbourne // Find a minimum offset taking into account only vtable sizes. 198df49d1bbSPeter Collingbourne uint64_t MinByte = 0; 199df49d1bbSPeter Collingbourne for (const VirtualCallTarget &Target : Targets) { 200df49d1bbSPeter Collingbourne if (IsAfter) 201df49d1bbSPeter Collingbourne MinByte = std::max(MinByte, Target.minAfterBytes()); 202df49d1bbSPeter Collingbourne else 203df49d1bbSPeter Collingbourne MinByte = std::max(MinByte, Target.minBeforeBytes()); 204df49d1bbSPeter Collingbourne } 205df49d1bbSPeter Collingbourne 206df49d1bbSPeter Collingbourne // Build a vector of arrays of bytes covering, for each target, a slice of the 207df49d1bbSPeter Collingbourne // used region (see AccumBitVector::BytesUsed in 208df49d1bbSPeter Collingbourne // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively, 209df49d1bbSPeter Collingbourne // this aligns the used regions to start at MinByte. 210df49d1bbSPeter Collingbourne // 211df49d1bbSPeter Collingbourne // In this example, A, B and C are vtables, # is a byte already allocated for 212df49d1bbSPeter Collingbourne // a virtual function pointer, AAAA... (etc.) are the used regions for the 213df49d1bbSPeter Collingbourne // vtables and Offset(X) is the value computed for the Offset variable below 214df49d1bbSPeter Collingbourne // for X. 215df49d1bbSPeter Collingbourne // 216df49d1bbSPeter Collingbourne // Offset(A) 217df49d1bbSPeter Collingbourne // | | 218df49d1bbSPeter Collingbourne // |MinByte 219df49d1bbSPeter Collingbourne // A: ################AAAAAAAA|AAAAAAAA 220df49d1bbSPeter Collingbourne // B: ########BBBBBBBBBBBBBBBB|BBBB 221df49d1bbSPeter Collingbourne // C: ########################|CCCCCCCCCCCCCCCC 222df49d1bbSPeter Collingbourne // | Offset(B) | 223df49d1bbSPeter Collingbourne // 224df49d1bbSPeter Collingbourne // This code produces the slices of A, B and C that appear after the divider 225df49d1bbSPeter Collingbourne // at MinByte. 226df49d1bbSPeter Collingbourne std::vector<ArrayRef<uint8_t>> Used; 227df49d1bbSPeter Collingbourne for (const VirtualCallTarget &Target : Targets) { 2287efd7506SPeter Collingbourne ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed 2297efd7506SPeter Collingbourne : Target.TM->Bits->Before.BytesUsed; 230df49d1bbSPeter Collingbourne uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes() 231df49d1bbSPeter Collingbourne : MinByte - Target.minBeforeBytes(); 232df49d1bbSPeter Collingbourne 233df49d1bbSPeter Collingbourne // Disregard used regions that are smaller than Offset. These are 234df49d1bbSPeter Collingbourne // effectively all-free regions that do not need to be checked. 235df49d1bbSPeter Collingbourne if (VTUsed.size() > Offset) 236df49d1bbSPeter Collingbourne Used.push_back(VTUsed.slice(Offset)); 237df49d1bbSPeter Collingbourne } 238df49d1bbSPeter Collingbourne 239df49d1bbSPeter Collingbourne if (Size == 1) { 240df49d1bbSPeter Collingbourne // Find a free bit in each member of Used. 241df49d1bbSPeter Collingbourne for (unsigned I = 0;; ++I) { 242df49d1bbSPeter Collingbourne uint8_t BitsUsed = 0; 243df49d1bbSPeter Collingbourne for (auto &&B : Used) 244df49d1bbSPeter Collingbourne if (I < B.size()) 245df49d1bbSPeter Collingbourne BitsUsed |= B[I]; 246df49d1bbSPeter Collingbourne if (BitsUsed != 0xff) 247df49d1bbSPeter Collingbourne return (MinByte + I) * 8 + 248df49d1bbSPeter Collingbourne countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined); 249df49d1bbSPeter Collingbourne } 250df49d1bbSPeter Collingbourne } else { 251df49d1bbSPeter Collingbourne // Find a free (Size/8) byte region in each member of Used. 252df49d1bbSPeter Collingbourne // FIXME: see if alignment helps. 253df49d1bbSPeter Collingbourne for (unsigned I = 0;; ++I) { 254df49d1bbSPeter Collingbourne for (auto &&B : Used) { 255df49d1bbSPeter Collingbourne unsigned Byte = 0; 256df49d1bbSPeter Collingbourne while ((I + Byte) < B.size() && Byte < (Size / 8)) { 257df49d1bbSPeter Collingbourne if (B[I + Byte]) 258df49d1bbSPeter Collingbourne goto NextI; 259df49d1bbSPeter Collingbourne ++Byte; 260df49d1bbSPeter Collingbourne } 261df49d1bbSPeter Collingbourne } 262df49d1bbSPeter Collingbourne return (MinByte + I) * 8; 263df49d1bbSPeter Collingbourne NextI:; 264df49d1bbSPeter Collingbourne } 265df49d1bbSPeter Collingbourne } 266df49d1bbSPeter Collingbourne } 267df49d1bbSPeter Collingbourne 268df49d1bbSPeter Collingbourne void wholeprogramdevirt::setBeforeReturnValues( 269df49d1bbSPeter Collingbourne MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore, 270df49d1bbSPeter Collingbourne unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { 271df49d1bbSPeter Collingbourne if (BitWidth == 1) 272df49d1bbSPeter Collingbourne OffsetByte = -(AllocBefore / 8 + 1); 273df49d1bbSPeter Collingbourne else 274df49d1bbSPeter Collingbourne OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8); 275df49d1bbSPeter Collingbourne OffsetBit = AllocBefore % 8; 276df49d1bbSPeter Collingbourne 277df49d1bbSPeter Collingbourne for (VirtualCallTarget &Target : Targets) { 278df49d1bbSPeter Collingbourne if (BitWidth == 1) 279df49d1bbSPeter Collingbourne Target.setBeforeBit(AllocBefore); 280df49d1bbSPeter Collingbourne else 281df49d1bbSPeter Collingbourne Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8); 282df49d1bbSPeter Collingbourne } 283df49d1bbSPeter Collingbourne } 284df49d1bbSPeter Collingbourne 285df49d1bbSPeter Collingbourne void wholeprogramdevirt::setAfterReturnValues( 286df49d1bbSPeter Collingbourne MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter, 287df49d1bbSPeter Collingbourne unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { 288df49d1bbSPeter Collingbourne if (BitWidth == 1) 289df49d1bbSPeter Collingbourne OffsetByte = AllocAfter / 8; 290df49d1bbSPeter Collingbourne else 291df49d1bbSPeter Collingbourne OffsetByte = (AllocAfter + 7) / 8; 292df49d1bbSPeter Collingbourne OffsetBit = AllocAfter % 8; 293df49d1bbSPeter Collingbourne 294df49d1bbSPeter Collingbourne for (VirtualCallTarget &Target : Targets) { 295df49d1bbSPeter Collingbourne if (BitWidth == 1) 296df49d1bbSPeter Collingbourne Target.setAfterBit(AllocAfter); 297df49d1bbSPeter Collingbourne else 298df49d1bbSPeter Collingbourne Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8); 299df49d1bbSPeter Collingbourne } 300df49d1bbSPeter Collingbourne } 301df49d1bbSPeter Collingbourne 3027efd7506SPeter Collingbourne VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM) 3037efd7506SPeter Collingbourne : Fn(Fn), TM(TM), 30489439a79SIvan Krasin IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {} 305df49d1bbSPeter Collingbourne 306df49d1bbSPeter Collingbourne namespace { 307df49d1bbSPeter Collingbourne 3087efd7506SPeter Collingbourne // A slot in a set of virtual tables. The TypeID identifies the set of virtual 309df49d1bbSPeter Collingbourne // tables, and the ByteOffset is the offset in bytes from the address point to 310df49d1bbSPeter Collingbourne // the virtual function pointer. 311df49d1bbSPeter Collingbourne struct VTableSlot { 3127efd7506SPeter Collingbourne Metadata *TypeID; 313df49d1bbSPeter Collingbourne uint64_t ByteOffset; 314df49d1bbSPeter Collingbourne }; 315df49d1bbSPeter Collingbourne 316cdc71612SEugene Zelenko } // end anonymous namespace 317df49d1bbSPeter Collingbourne 3189b656527SPeter Collingbourne namespace llvm { 3199b656527SPeter Collingbourne 320df49d1bbSPeter Collingbourne template <> struct DenseMapInfo<VTableSlot> { 321df49d1bbSPeter Collingbourne static VTableSlot getEmptyKey() { 322df49d1bbSPeter Collingbourne return {DenseMapInfo<Metadata *>::getEmptyKey(), 323df49d1bbSPeter Collingbourne DenseMapInfo<uint64_t>::getEmptyKey()}; 324df49d1bbSPeter Collingbourne } 325df49d1bbSPeter Collingbourne static VTableSlot getTombstoneKey() { 326df49d1bbSPeter Collingbourne return {DenseMapInfo<Metadata *>::getTombstoneKey(), 327df49d1bbSPeter Collingbourne DenseMapInfo<uint64_t>::getTombstoneKey()}; 328df49d1bbSPeter Collingbourne } 329df49d1bbSPeter Collingbourne static unsigned getHashValue(const VTableSlot &I) { 3307efd7506SPeter Collingbourne return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^ 331df49d1bbSPeter Collingbourne DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); 332df49d1bbSPeter Collingbourne } 333df49d1bbSPeter Collingbourne static bool isEqual(const VTableSlot &LHS, 334df49d1bbSPeter Collingbourne const VTableSlot &RHS) { 3357efd7506SPeter Collingbourne return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; 336df49d1bbSPeter Collingbourne } 337df49d1bbSPeter Collingbourne }; 338df49d1bbSPeter Collingbourne 339d2df54e6STeresa Johnson template <> struct DenseMapInfo<VTableSlotSummary> { 340d2df54e6STeresa Johnson static VTableSlotSummary getEmptyKey() { 341d2df54e6STeresa Johnson return {DenseMapInfo<StringRef>::getEmptyKey(), 342d2df54e6STeresa Johnson DenseMapInfo<uint64_t>::getEmptyKey()}; 343d2df54e6STeresa Johnson } 344d2df54e6STeresa Johnson static VTableSlotSummary getTombstoneKey() { 345d2df54e6STeresa Johnson return {DenseMapInfo<StringRef>::getTombstoneKey(), 346d2df54e6STeresa Johnson DenseMapInfo<uint64_t>::getTombstoneKey()}; 347d2df54e6STeresa Johnson } 348d2df54e6STeresa Johnson static unsigned getHashValue(const VTableSlotSummary &I) { 349d2df54e6STeresa Johnson return DenseMapInfo<StringRef>::getHashValue(I.TypeID) ^ 350d2df54e6STeresa Johnson DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); 351d2df54e6STeresa Johnson } 352d2df54e6STeresa Johnson static bool isEqual(const VTableSlotSummary &LHS, 353d2df54e6STeresa Johnson const VTableSlotSummary &RHS) { 354d2df54e6STeresa Johnson return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; 355d2df54e6STeresa Johnson } 356d2df54e6STeresa Johnson }; 357d2df54e6STeresa Johnson 358cdc71612SEugene Zelenko } // end namespace llvm 3599b656527SPeter Collingbourne 360df49d1bbSPeter Collingbourne namespace { 361df49d1bbSPeter Collingbourne 362df49d1bbSPeter Collingbourne // A virtual call site. VTable is the loaded virtual table pointer, and CS is 363df49d1bbSPeter Collingbourne // the indirect virtual call. 364df49d1bbSPeter Collingbourne struct VirtualCallSite { 365cea6f4d5SMircea Trofin Value *VTable = nullptr; 366cea6f4d5SMircea Trofin CallBase &CB; 367df49d1bbSPeter Collingbourne 3680312f614SPeter Collingbourne // If non-null, this field points to the associated unsafe use count stored in 3690312f614SPeter Collingbourne // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description 3700312f614SPeter Collingbourne // of that field for details. 371cea6f4d5SMircea Trofin unsigned *NumUnsafeUses = nullptr; 3720312f614SPeter Collingbourne 373e963c89dSSam Elliott void 374e963c89dSSam Elliott emitRemark(const StringRef OptName, const StringRef TargetName, 375e963c89dSSam Elliott function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) { 376cea6f4d5SMircea Trofin Function *F = CB.getCaller(); 377cea6f4d5SMircea Trofin DebugLoc DLoc = CB.getDebugLoc(); 378cea6f4d5SMircea Trofin BasicBlock *Block = CB.getParent(); 379e963c89dSSam Elliott 380e963c89dSSam Elliott using namespace ore; 3819110cb45SPeter Collingbourne OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block) 3829110cb45SPeter Collingbourne << NV("Optimization", OptName) 3839110cb45SPeter Collingbourne << ": devirtualized a call to " 384e963c89dSSam Elliott << NV("FunctionName", TargetName)); 385e963c89dSSam Elliott } 386e963c89dSSam Elliott 387e963c89dSSam Elliott void replaceAndErase( 388e963c89dSSam Elliott const StringRef OptName, const StringRef TargetName, bool RemarksEnabled, 389e963c89dSSam Elliott function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, 390e963c89dSSam Elliott Value *New) { 391f3403fd2SIvan Krasin if (RemarksEnabled) 392e963c89dSSam Elliott emitRemark(OptName, TargetName, OREGetter); 393cea6f4d5SMircea Trofin CB.replaceAllUsesWith(New); 394cea6f4d5SMircea Trofin if (auto *II = dyn_cast<InvokeInst>(&CB)) { 395cea6f4d5SMircea Trofin BranchInst::Create(II->getNormalDest(), &CB); 396df49d1bbSPeter Collingbourne II->getUnwindDest()->removePredecessor(II->getParent()); 397df49d1bbSPeter Collingbourne } 398cea6f4d5SMircea Trofin CB.eraseFromParent(); 3990312f614SPeter Collingbourne // This use is no longer unsafe. 4000312f614SPeter Collingbourne if (NumUnsafeUses) 4010312f614SPeter Collingbourne --*NumUnsafeUses; 402df49d1bbSPeter Collingbourne } 403df49d1bbSPeter Collingbourne }; 404df49d1bbSPeter Collingbourne 40550cbd7ccSPeter Collingbourne // Call site information collected for a specific VTableSlot and possibly a list 40650cbd7ccSPeter Collingbourne // of constant integer arguments. The grouping by arguments is handled by the 40750cbd7ccSPeter Collingbourne // VTableSlotInfo class. 40850cbd7ccSPeter Collingbourne struct CallSiteInfo { 409b406baaeSPeter Collingbourne /// The set of call sites for this slot. Used during regular LTO and the 410b406baaeSPeter Collingbourne /// import phase of ThinLTO (as well as the export phase of ThinLTO for any 411b406baaeSPeter Collingbourne /// call sites that appear in the merged module itself); in each of these 412b406baaeSPeter Collingbourne /// cases we are directly operating on the call sites at the IR level. 41350cbd7ccSPeter Collingbourne std::vector<VirtualCallSite> CallSites; 414b406baaeSPeter Collingbourne 4152974856aSPeter Collingbourne /// Whether all call sites represented by this CallSiteInfo, including those 4162974856aSPeter Collingbourne /// in summaries, have been devirtualized. This starts off as true because a 4172974856aSPeter Collingbourne /// default constructed CallSiteInfo represents no call sites. 4182974856aSPeter Collingbourne bool AllCallSitesDevirted = true; 4192974856aSPeter Collingbourne 420b406baaeSPeter Collingbourne // These fields are used during the export phase of ThinLTO and reflect 421b406baaeSPeter Collingbourne // information collected from function summaries. 422b406baaeSPeter Collingbourne 4232325bb34SPeter Collingbourne /// Whether any function summary contains an llvm.assume(llvm.type.test) for 4242325bb34SPeter Collingbourne /// this slot. 4252974856aSPeter Collingbourne bool SummaryHasTypeTestAssumeUsers = false; 4262325bb34SPeter Collingbourne 427b406baaeSPeter Collingbourne /// CFI-specific: a vector containing the list of function summaries that use 428b406baaeSPeter Collingbourne /// the llvm.type.checked.load intrinsic and therefore will require 429b406baaeSPeter Collingbourne /// resolutions for llvm.type.test in order to implement CFI checks if 430b406baaeSPeter Collingbourne /// devirtualization was unsuccessful. If devirtualization was successful, the 43159675ba0SPeter Collingbourne /// pass will clear this vector by calling markDevirt(). If at the end of the 43259675ba0SPeter Collingbourne /// pass the vector is non-empty, we will need to add a use of llvm.type.test 43359675ba0SPeter Collingbourne /// to each of the function summaries in the vector. 434b406baaeSPeter Collingbourne std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers; 435d2df54e6STeresa Johnson std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers; 4362325bb34SPeter Collingbourne 4372325bb34SPeter Collingbourne bool isExported() const { 4382325bb34SPeter Collingbourne return SummaryHasTypeTestAssumeUsers || 4392325bb34SPeter Collingbourne !SummaryTypeCheckedLoadUsers.empty(); 4402325bb34SPeter Collingbourne } 44159675ba0SPeter Collingbourne 4422974856aSPeter Collingbourne void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) { 4432974856aSPeter Collingbourne SummaryTypeCheckedLoadUsers.push_back(FS); 4442974856aSPeter Collingbourne AllCallSitesDevirted = false; 4452974856aSPeter Collingbourne } 4462974856aSPeter Collingbourne 447d2df54e6STeresa Johnson void addSummaryTypeTestAssumeUser(FunctionSummary *FS) { 448d2df54e6STeresa Johnson SummaryTypeTestAssumeUsers.push_back(FS); 449943afb57SEugene Leviant SummaryHasTypeTestAssumeUsers = true; 450943afb57SEugene Leviant AllCallSitesDevirted = false; 451d2df54e6STeresa Johnson } 452d2df54e6STeresa Johnson 4532974856aSPeter Collingbourne void markDevirt() { 4542974856aSPeter Collingbourne AllCallSitesDevirted = true; 4552974856aSPeter Collingbourne 4562974856aSPeter Collingbourne // As explained in the comment for SummaryTypeCheckedLoadUsers. 4572974856aSPeter Collingbourne SummaryTypeCheckedLoadUsers.clear(); 4582974856aSPeter Collingbourne } 45950cbd7ccSPeter Collingbourne }; 46050cbd7ccSPeter Collingbourne 46150cbd7ccSPeter Collingbourne // Call site information collected for a specific VTableSlot. 46250cbd7ccSPeter Collingbourne struct VTableSlotInfo { 46350cbd7ccSPeter Collingbourne // The set of call sites which do not have all constant integer arguments 46450cbd7ccSPeter Collingbourne // (excluding "this"). 46550cbd7ccSPeter Collingbourne CallSiteInfo CSInfo; 46650cbd7ccSPeter Collingbourne 46750cbd7ccSPeter Collingbourne // The set of call sites with all constant integer arguments (excluding 46850cbd7ccSPeter Collingbourne // "this"), grouped by argument list. 46950cbd7ccSPeter Collingbourne std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo; 47050cbd7ccSPeter Collingbourne 471cea6f4d5SMircea Trofin void addCallSite(Value *VTable, CallBase &CB, unsigned *NumUnsafeUses); 47250cbd7ccSPeter Collingbourne 47350cbd7ccSPeter Collingbourne private: 474cea6f4d5SMircea Trofin CallSiteInfo &findCallSiteInfo(CallBase &CB); 47550cbd7ccSPeter Collingbourne }; 47650cbd7ccSPeter Collingbourne 477cea6f4d5SMircea Trofin CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallBase &CB) { 47850cbd7ccSPeter Collingbourne std::vector<uint64_t> Args; 479cea6f4d5SMircea Trofin auto *CBType = dyn_cast<IntegerType>(CB.getType()); 480cea6f4d5SMircea Trofin if (!CBType || CBType->getBitWidth() > 64 || CB.arg_empty()) 48150cbd7ccSPeter Collingbourne return CSInfo; 48223b0ab2aSKazu Hirata for (auto &&Arg : drop_begin(CB.args())) { 48350cbd7ccSPeter Collingbourne auto *CI = dyn_cast<ConstantInt>(Arg); 48450cbd7ccSPeter Collingbourne if (!CI || CI->getBitWidth() > 64) 48550cbd7ccSPeter Collingbourne return CSInfo; 48650cbd7ccSPeter Collingbourne Args.push_back(CI->getZExtValue()); 48750cbd7ccSPeter Collingbourne } 48850cbd7ccSPeter Collingbourne return ConstCSInfo[Args]; 48950cbd7ccSPeter Collingbourne } 49050cbd7ccSPeter Collingbourne 491cea6f4d5SMircea Trofin void VTableSlotInfo::addCallSite(Value *VTable, CallBase &CB, 49250cbd7ccSPeter Collingbourne unsigned *NumUnsafeUses) { 493cea6f4d5SMircea Trofin auto &CSI = findCallSiteInfo(CB); 4942974856aSPeter Collingbourne CSI.AllCallSitesDevirted = false; 495cea6f4d5SMircea Trofin CSI.CallSites.push_back({VTable, CB, NumUnsafeUses}); 49650cbd7ccSPeter Collingbourne } 49750cbd7ccSPeter Collingbourne 498df49d1bbSPeter Collingbourne struct DevirtModule { 499df49d1bbSPeter Collingbourne Module &M; 50037317f12SPeter Collingbourne function_ref<AAResults &(Function &)> AARGetter; 501f24136f1STeresa Johnson function_ref<DominatorTree &(Function &)> LookupDomTree; 5022b33f653SPeter Collingbourne 503f7691d8bSPeter Collingbourne ModuleSummaryIndex *ExportSummary; 504f7691d8bSPeter Collingbourne const ModuleSummaryIndex *ImportSummary; 5052b33f653SPeter Collingbourne 506df49d1bbSPeter Collingbourne IntegerType *Int8Ty; 507df49d1bbSPeter Collingbourne PointerType *Int8PtrTy; 508df49d1bbSPeter Collingbourne IntegerType *Int32Ty; 50950cbd7ccSPeter Collingbourne IntegerType *Int64Ty; 51014dcf02fSPeter Collingbourne IntegerType *IntPtrTy; 511cc5c5888SBob Haarman /// Sizeless array type, used for imported vtables. This provides a signal 512cc5c5888SBob Haarman /// to analyzers that these imports may alias, as they do for example 513cc5c5888SBob Haarman /// when multiple unique return values occur in the same vtable. 514cc5c5888SBob Haarman ArrayType *Int8Arr0Ty; 515df49d1bbSPeter Collingbourne 516f3403fd2SIvan Krasin bool RemarksEnabled; 517e963c89dSSam Elliott function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter; 518f3403fd2SIvan Krasin 51950cbd7ccSPeter Collingbourne MapVector<VTableSlot, VTableSlotInfo> CallSlots; 520df49d1bbSPeter Collingbourne 5217110510eSArthur Eubanks // Calls that have already been optimized. We may add a call to multiple 5227110510eSArthur Eubanks // VTableSlotInfos if vtable loads are coalesced and need to make sure not to 5237110510eSArthur Eubanks // optimize a call more than once. 5247110510eSArthur Eubanks SmallPtrSet<CallBase *, 8> OptimizedCalls; 5257110510eSArthur Eubanks 5260312f614SPeter Collingbourne // This map keeps track of the number of "unsafe" uses of a loaded function 5270312f614SPeter Collingbourne // pointer. The key is the associated llvm.type.test intrinsic call generated 5280312f614SPeter Collingbourne // by this pass. An unsafe use is one that calls the loaded function pointer 5290312f614SPeter Collingbourne // directly. Every time we eliminate an unsafe use (for example, by 5300312f614SPeter Collingbourne // devirtualizing it or by applying virtual constant propagation), we 5310312f614SPeter Collingbourne // decrement the value stored in this map. If a value reaches zero, we can 5320312f614SPeter Collingbourne // eliminate the type check by RAUWing the associated llvm.type.test call with 5330312f614SPeter Collingbourne // true. 5340312f614SPeter Collingbourne std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest; 5356d2032e2Sevgeny PatternList FunctionsToSkip; 5360312f614SPeter Collingbourne 53737317f12SPeter Collingbourne DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter, 538e963c89dSSam Elliott function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, 539f24136f1STeresa Johnson function_ref<DominatorTree &(Function &)> LookupDomTree, 540f7691d8bSPeter Collingbourne ModuleSummaryIndex *ExportSummary, 541f7691d8bSPeter Collingbourne const ModuleSummaryIndex *ImportSummary) 542f24136f1STeresa Johnson : M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree), 543f24136f1STeresa Johnson ExportSummary(ExportSummary), ImportSummary(ImportSummary), 544f24136f1STeresa Johnson Int8Ty(Type::getInt8Ty(M.getContext())), 545df49d1bbSPeter Collingbourne Int8PtrTy(Type::getInt8PtrTy(M.getContext())), 546f3403fd2SIvan Krasin Int32Ty(Type::getInt32Ty(M.getContext())), 54750cbd7ccSPeter Collingbourne Int64Ty(Type::getInt64Ty(M.getContext())), 54814dcf02fSPeter Collingbourne IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)), 549cc5c5888SBob Haarman Int8Arr0Ty(ArrayType::get(Type::getInt8Ty(M.getContext()), 0)), 550e963c89dSSam Elliott RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) { 551f7691d8bSPeter Collingbourne assert(!(ExportSummary && ImportSummary)); 5526d2032e2Sevgeny FunctionsToSkip.init(SkipFunctionNames); 553f7691d8bSPeter Collingbourne } 554f3403fd2SIvan Krasin 555f3403fd2SIvan Krasin bool areRemarksEnabled(); 556df49d1bbSPeter Collingbourne 5576014c46cSTeresa Johnson void 5586014c46cSTeresa Johnson scanTypeTestUsers(Function *TypeTestFunc, 5596014c46cSTeresa Johnson DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); 5600312f614SPeter Collingbourne void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc); 5610312f614SPeter Collingbourne 5627efd7506SPeter Collingbourne void buildTypeIdentifierMap( 5637efd7506SPeter Collingbourne std::vector<VTableBits> &Bits, 5647efd7506SPeter Collingbourne DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); 5657efd7506SPeter Collingbourne bool 5667efd7506SPeter Collingbourne tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot, 5677efd7506SPeter Collingbourne const std::set<TypeMemberInfo> &TypeMemberInfos, 568df49d1bbSPeter Collingbourne uint64_t ByteOffset); 56950cbd7ccSPeter Collingbourne 5702325bb34SPeter Collingbourne void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn, 5712325bb34SPeter Collingbourne bool &IsExported); 572943afb57SEugene Leviant bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary, 573943afb57SEugene Leviant MutableArrayRef<VirtualCallTarget> TargetsForSlot, 5742325bb34SPeter Collingbourne VTableSlotInfo &SlotInfo, 5752325bb34SPeter Collingbourne WholeProgramDevirtResolution *Res); 57650cbd7ccSPeter Collingbourne 5772974856aSPeter Collingbourne void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT, 5782974856aSPeter Collingbourne bool &IsExported); 5792974856aSPeter Collingbourne void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot, 5802974856aSPeter Collingbourne VTableSlotInfo &SlotInfo, 5812974856aSPeter Collingbourne WholeProgramDevirtResolution *Res, VTableSlot Slot); 5822974856aSPeter Collingbourne 583df49d1bbSPeter Collingbourne bool tryEvaluateFunctionsWithArgs( 584df49d1bbSPeter Collingbourne MutableArrayRef<VirtualCallTarget> TargetsForSlot, 58550cbd7ccSPeter Collingbourne ArrayRef<uint64_t> Args); 58650cbd7ccSPeter Collingbourne 58750cbd7ccSPeter Collingbourne void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, 58850cbd7ccSPeter Collingbourne uint64_t TheRetVal); 58950cbd7ccSPeter Collingbourne bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, 59077a8d563SPeter Collingbourne CallSiteInfo &CSInfo, 59177a8d563SPeter Collingbourne WholeProgramDevirtResolution::ByArg *Res); 59250cbd7ccSPeter Collingbourne 59359675ba0SPeter Collingbourne // Returns the global symbol name that is used to export information about the 59459675ba0SPeter Collingbourne // given vtable slot and list of arguments. 59559675ba0SPeter Collingbourne std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args, 59659675ba0SPeter Collingbourne StringRef Name); 59759675ba0SPeter Collingbourne 598b15a35e6SPeter Collingbourne bool shouldExportConstantsAsAbsoluteSymbols(); 599b15a35e6SPeter Collingbourne 60059675ba0SPeter Collingbourne // This function is called during the export phase to create a symbol 60159675ba0SPeter Collingbourne // definition containing information about the given vtable slot and list of 60259675ba0SPeter Collingbourne // arguments. 60359675ba0SPeter Collingbourne void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, 60459675ba0SPeter Collingbourne Constant *C); 605b15a35e6SPeter Collingbourne void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, 606b15a35e6SPeter Collingbourne uint32_t Const, uint32_t &Storage); 60759675ba0SPeter Collingbourne 60859675ba0SPeter Collingbourne // This function is called during the import phase to create a reference to 60959675ba0SPeter Collingbourne // the symbol definition created during the export phase. 61059675ba0SPeter Collingbourne Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, 611b15a35e6SPeter Collingbourne StringRef Name); 612b15a35e6SPeter Collingbourne Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, 613b15a35e6SPeter Collingbourne StringRef Name, IntegerType *IntTy, 614b15a35e6SPeter Collingbourne uint32_t Storage); 61559675ba0SPeter Collingbourne 6162974856aSPeter Collingbourne Constant *getMemberAddr(const TypeMemberInfo *M); 6172974856aSPeter Collingbourne 61850cbd7ccSPeter Collingbourne void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne, 61950cbd7ccSPeter Collingbourne Constant *UniqueMemberAddr); 620df49d1bbSPeter Collingbourne bool tryUniqueRetValOpt(unsigned BitWidth, 621f3403fd2SIvan Krasin MutableArrayRef<VirtualCallTarget> TargetsForSlot, 62259675ba0SPeter Collingbourne CallSiteInfo &CSInfo, 62359675ba0SPeter Collingbourne WholeProgramDevirtResolution::ByArg *Res, 62459675ba0SPeter Collingbourne VTableSlot Slot, ArrayRef<uint64_t> Args); 62550cbd7ccSPeter Collingbourne 62650cbd7ccSPeter Collingbourne void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, 62750cbd7ccSPeter Collingbourne Constant *Byte, Constant *Bit); 628df49d1bbSPeter Collingbourne bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot, 62977a8d563SPeter Collingbourne VTableSlotInfo &SlotInfo, 63059675ba0SPeter Collingbourne WholeProgramDevirtResolution *Res, VTableSlot Slot); 631df49d1bbSPeter Collingbourne 632df49d1bbSPeter Collingbourne void rebuildGlobal(VTableBits &B); 633df49d1bbSPeter Collingbourne 6346d284fabSPeter Collingbourne // Apply the summary resolution for Slot to all virtual calls in SlotInfo. 6356d284fabSPeter Collingbourne void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo); 6366d284fabSPeter Collingbourne 6376d284fabSPeter Collingbourne // If we were able to eliminate all unsafe uses for a type checked load, 6386d284fabSPeter Collingbourne // eliminate the associated type tests by replacing them with true. 6396d284fabSPeter Collingbourne void removeRedundantTypeTests(); 6406d284fabSPeter Collingbourne 641df49d1bbSPeter Collingbourne bool run(); 6422b33f653SPeter Collingbourne 6432b33f653SPeter Collingbourne // Lower the module using the action and summary passed as command line 6442b33f653SPeter Collingbourne // arguments. For testing purposes only. 645f24136f1STeresa Johnson static bool 646f24136f1STeresa Johnson runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter, 647f24136f1STeresa Johnson function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, 648f24136f1STeresa Johnson function_ref<DominatorTree &(Function &)> LookupDomTree); 649df49d1bbSPeter Collingbourne }; 650df49d1bbSPeter Collingbourne 651d2df54e6STeresa Johnson struct DevirtIndex { 652d2df54e6STeresa Johnson ModuleSummaryIndex &ExportSummary; 653d2df54e6STeresa Johnson // The set in which to record GUIDs exported from their module by 654d2df54e6STeresa Johnson // devirtualization, used by client to ensure they are not internalized. 655d2df54e6STeresa Johnson std::set<GlobalValue::GUID> &ExportedGUIDs; 656d2df54e6STeresa Johnson // A map in which to record the information necessary to locate the WPD 657d2df54e6STeresa Johnson // resolution for local targets in case they are exported by cross module 658d2df54e6STeresa Johnson // importing. 659d2df54e6STeresa Johnson std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap; 660d2df54e6STeresa Johnson 661d2df54e6STeresa Johnson MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots; 662d2df54e6STeresa Johnson 6636d2032e2Sevgeny PatternList FunctionsToSkip; 6646d2032e2Sevgeny 665d2df54e6STeresa Johnson DevirtIndex( 666d2df54e6STeresa Johnson ModuleSummaryIndex &ExportSummary, 667d2df54e6STeresa Johnson std::set<GlobalValue::GUID> &ExportedGUIDs, 668d2df54e6STeresa Johnson std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) 669d2df54e6STeresa Johnson : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs), 6706d2032e2Sevgeny LocalWPDTargetsMap(LocalWPDTargetsMap) { 6716d2032e2Sevgeny FunctionsToSkip.init(SkipFunctionNames); 6726d2032e2Sevgeny } 673d2df54e6STeresa Johnson 674d2df54e6STeresa Johnson bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot, 675d2df54e6STeresa Johnson const TypeIdCompatibleVtableInfo TIdInfo, 676d2df54e6STeresa Johnson uint64_t ByteOffset); 677d2df54e6STeresa Johnson 678d2df54e6STeresa Johnson bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot, 679d2df54e6STeresa Johnson VTableSlotSummary &SlotSummary, 680d2df54e6STeresa Johnson VTableSlotInfo &SlotInfo, 681d2df54e6STeresa Johnson WholeProgramDevirtResolution *Res, 682d2df54e6STeresa Johnson std::set<ValueInfo> &DevirtTargets); 683d2df54e6STeresa Johnson 684d2df54e6STeresa Johnson void run(); 685d2df54e6STeresa Johnson }; 686d2df54e6STeresa Johnson 687df49d1bbSPeter Collingbourne struct WholeProgramDevirt : public ModulePass { 688df49d1bbSPeter Collingbourne static char ID; 689cdc71612SEugene Zelenko 6902b33f653SPeter Collingbourne bool UseCommandLine = false; 6912b33f653SPeter Collingbourne 69239c0829aSSimon Pilgrim ModuleSummaryIndex *ExportSummary = nullptr; 69339c0829aSSimon Pilgrim const ModuleSummaryIndex *ImportSummary = nullptr; 6942b33f653SPeter Collingbourne 6952b33f653SPeter Collingbourne WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) { 6962b33f653SPeter Collingbourne initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); 6972b33f653SPeter Collingbourne } 6982b33f653SPeter Collingbourne 699f7691d8bSPeter Collingbourne WholeProgramDevirt(ModuleSummaryIndex *ExportSummary, 700f7691d8bSPeter Collingbourne const ModuleSummaryIndex *ImportSummary) 701f7691d8bSPeter Collingbourne : ModulePass(ID), ExportSummary(ExportSummary), 702f7691d8bSPeter Collingbourne ImportSummary(ImportSummary) { 703df49d1bbSPeter Collingbourne initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); 704df49d1bbSPeter Collingbourne } 705cdc71612SEugene Zelenko 706cdc71612SEugene Zelenko bool runOnModule(Module &M) override { 707aa641a51SAndrew Kaylor if (skipModule(M)) 708aa641a51SAndrew Kaylor return false; 709e963c89dSSam Elliott 7109110cb45SPeter Collingbourne // In the new pass manager, we can request the optimization 7119110cb45SPeter Collingbourne // remark emitter pass on a per-function-basis, which the 7129110cb45SPeter Collingbourne // OREGetter will do for us. 7139110cb45SPeter Collingbourne // In the old pass manager, this is harder, so we just build 7149110cb45SPeter Collingbourne // an optimization remark emitter on the fly, when we need it. 7159110cb45SPeter Collingbourne std::unique_ptr<OptimizationRemarkEmitter> ORE; 7169110cb45SPeter Collingbourne auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & { 7170eaee545SJonas Devlieghere ORE = std::make_unique<OptimizationRemarkEmitter>(F); 7189110cb45SPeter Collingbourne return *ORE; 7199110cb45SPeter Collingbourne }; 720e963c89dSSam Elliott 721f24136f1STeresa Johnson auto LookupDomTree = [this](Function &F) -> DominatorTree & { 722f24136f1STeresa Johnson return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 723f24136f1STeresa Johnson }; 724e963c89dSSam Elliott 725f24136f1STeresa Johnson if (UseCommandLine) 726f24136f1STeresa Johnson return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter, 727f24136f1STeresa Johnson LookupDomTree); 728f24136f1STeresa Johnson 729f24136f1STeresa Johnson return DevirtModule(M, LegacyAARGetter(*this), OREGetter, LookupDomTree, 730f24136f1STeresa Johnson ExportSummary, ImportSummary) 731f7691d8bSPeter Collingbourne .run(); 73237317f12SPeter Collingbourne } 73337317f12SPeter Collingbourne 73437317f12SPeter Collingbourne void getAnalysisUsage(AnalysisUsage &AU) const override { 73537317f12SPeter Collingbourne AU.addRequired<AssumptionCacheTracker>(); 73637317f12SPeter Collingbourne AU.addRequired<TargetLibraryInfoWrapperPass>(); 737f24136f1STeresa Johnson AU.addRequired<DominatorTreeWrapperPass>(); 738aa641a51SAndrew Kaylor } 739df49d1bbSPeter Collingbourne }; 740df49d1bbSPeter Collingbourne 741cdc71612SEugene Zelenko } // end anonymous namespace 742df49d1bbSPeter Collingbourne 74337317f12SPeter Collingbourne INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt", 74437317f12SPeter Collingbourne "Whole program devirtualization", false, false) 74537317f12SPeter Collingbourne INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 74637317f12SPeter Collingbourne INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 747f24136f1STeresa Johnson INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 74837317f12SPeter Collingbourne INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt", 749df49d1bbSPeter Collingbourne "Whole program devirtualization", false, false) 750df49d1bbSPeter Collingbourne char WholeProgramDevirt::ID = 0; 751df49d1bbSPeter Collingbourne 752f7691d8bSPeter Collingbourne ModulePass * 753f7691d8bSPeter Collingbourne llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary, 754f7691d8bSPeter Collingbourne const ModuleSummaryIndex *ImportSummary) { 755f7691d8bSPeter Collingbourne return new WholeProgramDevirt(ExportSummary, ImportSummary); 756df49d1bbSPeter Collingbourne } 757df49d1bbSPeter Collingbourne 758164a2aa6SChandler Carruth PreservedAnalyses WholeProgramDevirtPass::run(Module &M, 75937317f12SPeter Collingbourne ModuleAnalysisManager &AM) { 76037317f12SPeter Collingbourne auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 76137317f12SPeter Collingbourne auto AARGetter = [&](Function &F) -> AAResults & { 76237317f12SPeter Collingbourne return FAM.getResult<AAManager>(F); 76337317f12SPeter Collingbourne }; 764e963c89dSSam Elliott auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & { 765e963c89dSSam Elliott return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); 766e963c89dSSam Elliott }; 767f24136f1STeresa Johnson auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & { 768f24136f1STeresa Johnson return FAM.getResult<DominatorTreeAnalysis>(F); 769f24136f1STeresa Johnson }; 770460dda07SArthur Eubanks if (UseCommandLine) { 771460dda07SArthur Eubanks if (DevirtModule::runForTesting(M, AARGetter, OREGetter, LookupDomTree)) 772460dda07SArthur Eubanks return PreservedAnalyses::all(); 773460dda07SArthur Eubanks return PreservedAnalyses::none(); 774460dda07SArthur Eubanks } 775f24136f1STeresa Johnson if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary, 776f24136f1STeresa Johnson ImportSummary) 77728023dbeSTeresa Johnson .run()) 778d737dd2eSDavide Italiano return PreservedAnalyses::all(); 779d737dd2eSDavide Italiano return PreservedAnalyses::none(); 780d737dd2eSDavide Italiano } 781d737dd2eSDavide Italiano 7822f63d549STeresa Johnson // Enable whole program visibility if enabled by client (e.g. linker) or 7832f63d549STeresa Johnson // internal option, and not force disabled. 7842f63d549STeresa Johnson static bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO) { 7852f63d549STeresa Johnson return (WholeProgramVisibilityEnabledInLTO || WholeProgramVisibility) && 7862f63d549STeresa Johnson !DisableWholeProgramVisibility; 7872f63d549STeresa Johnson } 7882f63d549STeresa Johnson 789d2df54e6STeresa Johnson namespace llvm { 7902f63d549STeresa Johnson 7912f63d549STeresa Johnson /// If whole program visibility asserted, then upgrade all public vcall 7922f63d549STeresa Johnson /// visibility metadata on vtable definitions to linkage unit visibility in 7932f63d549STeresa Johnson /// Module IR (for regular or hybrid LTO). 7941487747eSTeresa Johnson void updateVCallVisibilityInModule( 7951487747eSTeresa Johnson Module &M, bool WholeProgramVisibilityEnabledInLTO, 7961487747eSTeresa Johnson const DenseSet<GlobalValue::GUID> &DynamicExportSymbols) { 7972f63d549STeresa Johnson if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) 7982f63d549STeresa Johnson return; 7992f63d549STeresa Johnson for (GlobalVariable &GV : M.globals()) 8002f63d549STeresa Johnson // Add linkage unit visibility to any variable with type metadata, which are 8012f63d549STeresa Johnson // the vtable definitions. We won't have an existing vcall_visibility 8022f63d549STeresa Johnson // metadata on vtable definitions with public visibility. 8032f63d549STeresa Johnson if (GV.hasMetadata(LLVMContext::MD_type) && 8041487747eSTeresa Johnson GV.getVCallVisibility() == GlobalObject::VCallVisibilityPublic && 8051487747eSTeresa Johnson // Don't upgrade the visibility for symbols exported to the dynamic 8061487747eSTeresa Johnson // linker, as we have no information on their eventual use. 8071487747eSTeresa Johnson !DynamicExportSymbols.count(GV.getGUID())) 8082f63d549STeresa Johnson GV.setVCallVisibilityMetadata(GlobalObject::VCallVisibilityLinkageUnit); 8092f63d549STeresa Johnson } 8102f63d549STeresa Johnson 8112f63d549STeresa Johnson /// If whole program visibility asserted, then upgrade all public vcall 8122f63d549STeresa Johnson /// visibility metadata on vtable definition summaries to linkage unit 8132f63d549STeresa Johnson /// visibility in Module summary index (for ThinLTO). 8141487747eSTeresa Johnson void updateVCallVisibilityInIndex( 8151487747eSTeresa Johnson ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, 8161487747eSTeresa Johnson const DenseSet<GlobalValue::GUID> &DynamicExportSymbols) { 8172f63d549STeresa Johnson if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) 8182f63d549STeresa Johnson return; 8192f63d549STeresa Johnson for (auto &P : Index) { 8202f63d549STeresa Johnson for (auto &S : P.second.SummaryList) { 8212f63d549STeresa Johnson auto *GVar = dyn_cast<GlobalVarSummary>(S.get()); 8220a5949dcSTeresa Johnson if (!GVar || 8231487747eSTeresa Johnson GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic || 8241487747eSTeresa Johnson // Don't upgrade the visibility for symbols exported to the dynamic 8251487747eSTeresa Johnson // linker, as we have no information on their eventual use. 8261487747eSTeresa Johnson DynamicExportSymbols.count(P.first)) 8272f63d549STeresa Johnson continue; 8282f63d549STeresa Johnson GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit); 8292f63d549STeresa Johnson } 8302f63d549STeresa Johnson } 8312f63d549STeresa Johnson } 8322f63d549STeresa Johnson 833d2df54e6STeresa Johnson void runWholeProgramDevirtOnIndex( 834d2df54e6STeresa Johnson ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs, 835d2df54e6STeresa Johnson std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) { 836d2df54e6STeresa Johnson DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run(); 837d2df54e6STeresa Johnson } 838d2df54e6STeresa Johnson 839d2df54e6STeresa Johnson void updateIndexWPDForExports( 840d2df54e6STeresa Johnson ModuleSummaryIndex &Summary, 8413d708bf5Sevgeny function_ref<bool(StringRef, ValueInfo)> isExported, 842d2df54e6STeresa Johnson std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) { 843d2df54e6STeresa Johnson for (auto &T : LocalWPDTargetsMap) { 844d2df54e6STeresa Johnson auto &VI = T.first; 845d2df54e6STeresa Johnson // This was enforced earlier during trySingleImplDevirt. 846d2df54e6STeresa Johnson assert(VI.getSummaryList().size() == 1 && 847d2df54e6STeresa Johnson "Devirt of local target has more than one copy"); 848d2df54e6STeresa Johnson auto &S = VI.getSummaryList()[0]; 8493d708bf5Sevgeny if (!isExported(S->modulePath(), VI)) 850d2df54e6STeresa Johnson continue; 851d2df54e6STeresa Johnson 852d2df54e6STeresa Johnson // It's been exported by a cross module import. 853d2df54e6STeresa Johnson for (auto &SlotSummary : T.second) { 854d2df54e6STeresa Johnson auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID); 855d2df54e6STeresa Johnson assert(TIdSum); 856d2df54e6STeresa Johnson auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset); 857d2df54e6STeresa Johnson assert(WPDRes != TIdSum->WPDRes.end()); 858d2df54e6STeresa Johnson WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal( 859d2df54e6STeresa Johnson WPDRes->second.SingleImplName, 860d2df54e6STeresa Johnson Summary.getModuleHash(S->modulePath())); 861d2df54e6STeresa Johnson } 862d2df54e6STeresa Johnson } 863d2df54e6STeresa Johnson } 864d2df54e6STeresa Johnson 865d2df54e6STeresa Johnson } // end namespace llvm 866d2df54e6STeresa Johnson 8678973fae1SEvgeny Leviant static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary) { 8688973fae1SEvgeny Leviant // Check that summary index contains regular LTO module when performing 8698973fae1SEvgeny Leviant // export to prevent occasional use of index from pure ThinLTO compilation 8708973fae1SEvgeny Leviant // (-fno-split-lto-module). This kind of summary index is passed to 8718973fae1SEvgeny Leviant // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting. 8728973fae1SEvgeny Leviant const auto &ModPaths = Summary->modulePaths(); 8738973fae1SEvgeny Leviant if (ClSummaryAction != PassSummaryAction::Import && 8748973fae1SEvgeny Leviant ModPaths.find(ModuleSummaryIndex::getRegularLTOModuleName()) == 8758973fae1SEvgeny Leviant ModPaths.end()) 8768973fae1SEvgeny Leviant return createStringError( 8778973fae1SEvgeny Leviant errc::invalid_argument, 8788973fae1SEvgeny Leviant "combined summary should contain Regular LTO module"); 8798973fae1SEvgeny Leviant return ErrorSuccess(); 8808973fae1SEvgeny Leviant } 8818973fae1SEvgeny Leviant 88237317f12SPeter Collingbourne bool DevirtModule::runForTesting( 883e963c89dSSam Elliott Module &M, function_ref<AAResults &(Function &)> AARGetter, 884f24136f1STeresa Johnson function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter, 885f24136f1STeresa Johnson function_ref<DominatorTree &(Function &)> LookupDomTree) { 8868973fae1SEvgeny Leviant std::unique_ptr<ModuleSummaryIndex> Summary = 8878973fae1SEvgeny Leviant std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 8882b33f653SPeter Collingbourne 8892b33f653SPeter Collingbourne // Handle the command-line summary arguments. This code is for testing 8902b33f653SPeter Collingbourne // purposes only, so we handle errors directly. 8912b33f653SPeter Collingbourne if (!ClReadSummary.empty()) { 8922b33f653SPeter Collingbourne ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary + 8932b33f653SPeter Collingbourne ": "); 8942b33f653SPeter Collingbourne auto ReadSummaryFile = 8952b33f653SPeter Collingbourne ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); 8968973fae1SEvgeny Leviant if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = 8978973fae1SEvgeny Leviant getModuleSummaryIndex(*ReadSummaryFile)) { 8988973fae1SEvgeny Leviant Summary = std::move(*SummaryOrErr); 8998973fae1SEvgeny Leviant ExitOnErr(checkCombinedSummaryForTesting(Summary.get())); 9008973fae1SEvgeny Leviant } else { 9018973fae1SEvgeny Leviant // Try YAML if we've failed with bitcode. 9028973fae1SEvgeny Leviant consumeError(SummaryOrErr.takeError()); 9032b33f653SPeter Collingbourne yaml::Input In(ReadSummaryFile->getBuffer()); 9048973fae1SEvgeny Leviant In >> *Summary; 9052b33f653SPeter Collingbourne ExitOnErr(errorCodeToError(In.error())); 9062b33f653SPeter Collingbourne } 9078973fae1SEvgeny Leviant } 9082b33f653SPeter Collingbourne 909f7691d8bSPeter Collingbourne bool Changed = 9108973fae1SEvgeny Leviant DevirtModule(M, AARGetter, OREGetter, LookupDomTree, 9118973fae1SEvgeny Leviant ClSummaryAction == PassSummaryAction::Export ? Summary.get() 9128973fae1SEvgeny Leviant : nullptr, 9138973fae1SEvgeny Leviant ClSummaryAction == PassSummaryAction::Import ? Summary.get() 9148973fae1SEvgeny Leviant : nullptr) 915f7691d8bSPeter Collingbourne .run(); 9162b33f653SPeter Collingbourne 9172b33f653SPeter Collingbourne if (!ClWriteSummary.empty()) { 9182b33f653SPeter Collingbourne ExitOnError ExitOnErr( 9192b33f653SPeter Collingbourne "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": "); 9202b33f653SPeter Collingbourne std::error_code EC; 9218973fae1SEvgeny Leviant if (StringRef(ClWriteSummary).endswith(".bc")) { 9228973fae1SEvgeny Leviant raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None); 9238973fae1SEvgeny Leviant ExitOnErr(errorCodeToError(EC)); 9248973fae1SEvgeny Leviant WriteIndexToFile(*Summary, OS); 9258973fae1SEvgeny Leviant } else { 92682b3e28eSAbhina Sreeskantharajan raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_TextWithCRLF); 9272b33f653SPeter Collingbourne ExitOnErr(errorCodeToError(EC)); 9282b33f653SPeter Collingbourne yaml::Output Out(OS); 9298973fae1SEvgeny Leviant Out << *Summary; 9308973fae1SEvgeny Leviant } 9312b33f653SPeter Collingbourne } 9322b33f653SPeter Collingbourne 9332b33f653SPeter Collingbourne return Changed; 9342b33f653SPeter Collingbourne } 9352b33f653SPeter Collingbourne 9367efd7506SPeter Collingbourne void DevirtModule::buildTypeIdentifierMap( 937df49d1bbSPeter Collingbourne std::vector<VTableBits> &Bits, 9387efd7506SPeter Collingbourne DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { 939df49d1bbSPeter Collingbourne DenseMap<GlobalVariable *, VTableBits *> GVToBits; 9407efd7506SPeter Collingbourne Bits.reserve(M.getGlobalList().size()); 9417efd7506SPeter Collingbourne SmallVector<MDNode *, 2> Types; 9427efd7506SPeter Collingbourne for (GlobalVariable &GV : M.globals()) { 9437efd7506SPeter Collingbourne Types.clear(); 9447efd7506SPeter Collingbourne GV.getMetadata(LLVMContext::MD_type, Types); 9452b70d616SEugene Leviant if (GV.isDeclaration() || Types.empty()) 946df49d1bbSPeter Collingbourne continue; 947df49d1bbSPeter Collingbourne 9487efd7506SPeter Collingbourne VTableBits *&BitsPtr = GVToBits[&GV]; 9497efd7506SPeter Collingbourne if (!BitsPtr) { 9507efd7506SPeter Collingbourne Bits.emplace_back(); 9517efd7506SPeter Collingbourne Bits.back().GV = &GV; 9527efd7506SPeter Collingbourne Bits.back().ObjectSize = 9537efd7506SPeter Collingbourne M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType()); 9547efd7506SPeter Collingbourne BitsPtr = &Bits.back(); 9557efd7506SPeter Collingbourne } 9567efd7506SPeter Collingbourne 9577efd7506SPeter Collingbourne for (MDNode *Type : Types) { 9587efd7506SPeter Collingbourne auto TypeID = Type->getOperand(1).get(); 959df49d1bbSPeter Collingbourne 960df49d1bbSPeter Collingbourne uint64_t Offset = 961df49d1bbSPeter Collingbourne cast<ConstantInt>( 9627efd7506SPeter Collingbourne cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) 963df49d1bbSPeter Collingbourne ->getZExtValue(); 964df49d1bbSPeter Collingbourne 9657efd7506SPeter Collingbourne TypeIdMap[TypeID].insert({BitsPtr, Offset}); 966df49d1bbSPeter Collingbourne } 967df49d1bbSPeter Collingbourne } 968df49d1bbSPeter Collingbourne } 969df49d1bbSPeter Collingbourne 970df49d1bbSPeter Collingbourne bool DevirtModule::tryFindVirtualCallTargets( 971df49d1bbSPeter Collingbourne std::vector<VirtualCallTarget> &TargetsForSlot, 9727efd7506SPeter Collingbourne const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) { 9737efd7506SPeter Collingbourne for (const TypeMemberInfo &TM : TypeMemberInfos) { 9747efd7506SPeter Collingbourne if (!TM.Bits->GV->isConstant()) 975df49d1bbSPeter Collingbourne return false; 976df49d1bbSPeter Collingbourne 9772f63d549STeresa Johnson // We cannot perform whole program devirtualization analysis on a vtable 9782f63d549STeresa Johnson // with public LTO visibility. 9792f63d549STeresa Johnson if (TM.Bits->GV->getVCallVisibility() == 9802f63d549STeresa Johnson GlobalObject::VCallVisibilityPublic) 9812f63d549STeresa Johnson return false; 9822f63d549STeresa Johnson 9838786754cSPeter Collingbourne Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(), 9843b598b9cSOliver Stannard TM.Offset + ByteOffset, M); 9858786754cSPeter Collingbourne if (!Ptr) 986df49d1bbSPeter Collingbourne return false; 987df49d1bbSPeter Collingbourne 9888786754cSPeter Collingbourne auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts()); 989df49d1bbSPeter Collingbourne if (!Fn) 990df49d1bbSPeter Collingbourne return false; 991df49d1bbSPeter Collingbourne 9926d2032e2Sevgeny if (FunctionsToSkip.match(Fn->getName())) 9936d2032e2Sevgeny return false; 9946d2032e2Sevgeny 995df49d1bbSPeter Collingbourne // We can disregard __cxa_pure_virtual as a possible call target, as 996df49d1bbSPeter Collingbourne // calls to pure virtuals are UB. 997df49d1bbSPeter Collingbourne if (Fn->getName() == "__cxa_pure_virtual") 998df49d1bbSPeter Collingbourne continue; 999df49d1bbSPeter Collingbourne 10007efd7506SPeter Collingbourne TargetsForSlot.push_back({Fn, &TM}); 1001df49d1bbSPeter Collingbourne } 1002df49d1bbSPeter Collingbourne 1003df49d1bbSPeter Collingbourne // Give up if we couldn't find any targets. 1004df49d1bbSPeter Collingbourne return !TargetsForSlot.empty(); 1005df49d1bbSPeter Collingbourne } 1006df49d1bbSPeter Collingbourne 1007d2df54e6STeresa Johnson bool DevirtIndex::tryFindVirtualCallTargets( 1008d2df54e6STeresa Johnson std::vector<ValueInfo> &TargetsForSlot, const TypeIdCompatibleVtableInfo TIdInfo, 1009d2df54e6STeresa Johnson uint64_t ByteOffset) { 1010098d3347SMark de Wever for (const TypeIdOffsetVtableInfo &P : TIdInfo) { 10113c4c2050STeresa Johnson // Find a representative copy of the vtable initializer. 1012c844f884STeresa Johnson // We can have multiple available_externally, linkonce_odr and weak_odr 10130a5949dcSTeresa Johnson // vtable initializers. We can also have multiple external vtable 10140a5949dcSTeresa Johnson // initializers in the case of comdats, which we cannot check here. 10152cefb939STeresa Johnson // The linker should give an error in this case. 1016c844f884STeresa Johnson // 1017c844f884STeresa Johnson // Also, handle the case of same-named local Vtables with the same path 1018c844f884STeresa Johnson // and therefore the same GUID. This can happen if there isn't enough 1019c844f884STeresa Johnson // distinguishing path when compiling the source file. In that case we 1020c844f884STeresa Johnson // conservatively return false early. 1021c844f884STeresa Johnson const GlobalVarSummary *VS = nullptr; 1022c844f884STeresa Johnson bool LocalFound = false; 1023c844f884STeresa Johnson for (auto &S : P.VTableVI.getSummaryList()) { 1024c844f884STeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage())) { 1025c844f884STeresa Johnson if (LocalFound) 1026c844f884STeresa Johnson return false; 1027c844f884STeresa Johnson LocalFound = true; 1028c844f884STeresa Johnson } 10293c4c2050STeresa Johnson auto *CurVS = cast<GlobalVarSummary>(S->getBaseObject()); 10300a5949dcSTeresa Johnson if (!CurVS->vTableFuncs().empty() || 10310a5949dcSTeresa Johnson // Previously clang did not attach the necessary type metadata to 10320a5949dcSTeresa Johnson // available_externally vtables, in which case there would not 10330a5949dcSTeresa Johnson // be any vtable functions listed in the summary and we need 10340a5949dcSTeresa Johnson // to treat this case conservatively (in case the bitcode is old). 10350a5949dcSTeresa Johnson // However, we will also not have any vtable functions in the 10360a5949dcSTeresa Johnson // case of a pure virtual base class. In that case we do want 10370a5949dcSTeresa Johnson // to set VS to avoid treating it conservatively. 10380a5949dcSTeresa Johnson !GlobalValue::isAvailableExternallyLinkage(S->linkage())) { 10393c4c2050STeresa Johnson VS = CurVS; 10402f63d549STeresa Johnson // We cannot perform whole program devirtualization analysis on a vtable 10412f63d549STeresa Johnson // with public LTO visibility. 10422f63d549STeresa Johnson if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic) 10432f63d549STeresa Johnson return false; 10440a5949dcSTeresa Johnson } 10452f63d549STeresa Johnson } 10463c4c2050STeresa Johnson // There will be no VS if all copies are available_externally having no 10473c4c2050STeresa Johnson // type metadata. In that case we can't safely perform WPD. 10483c4c2050STeresa Johnson if (!VS) 10493c4c2050STeresa Johnson return false; 1050c844f884STeresa Johnson if (!VS->isLive()) 1051d2df54e6STeresa Johnson continue; 1052d2df54e6STeresa Johnson for (auto VTP : VS->vTableFuncs()) { 1053d2df54e6STeresa Johnson if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset) 1054d2df54e6STeresa Johnson continue; 1055d2df54e6STeresa Johnson 1056d2df54e6STeresa Johnson TargetsForSlot.push_back(VTP.FuncVI); 1057d2df54e6STeresa Johnson } 1058d2df54e6STeresa Johnson } 1059d2df54e6STeresa Johnson 1060d2df54e6STeresa Johnson // Give up if we couldn't find any targets. 1061d2df54e6STeresa Johnson return !TargetsForSlot.empty(); 1062d2df54e6STeresa Johnson } 1063d2df54e6STeresa Johnson 106450cbd7ccSPeter Collingbourne void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo, 10652325bb34SPeter Collingbourne Constant *TheFn, bool &IsExported) { 10666e4c1cf2STeresa Johnson // Don't devirtualize function if we're told to skip it 10676e4c1cf2STeresa Johnson // in -wholeprogramdevirt-skip. 10686e4c1cf2STeresa Johnson if (FunctionsToSkip.match(TheFn->stripPointerCasts()->getName())) 10696e4c1cf2STeresa Johnson return; 107050cbd7ccSPeter Collingbourne auto Apply = [&](CallSiteInfo &CSInfo) { 107150cbd7ccSPeter Collingbourne for (auto &&VCallSite : CSInfo.CallSites) { 10727110510eSArthur Eubanks if (!OptimizedCalls.insert(&VCallSite.CB).second) 10737110510eSArthur Eubanks continue; 10747110510eSArthur Eubanks 1075f3403fd2SIvan Krasin if (RemarksEnabled) 1076b0a1d3bdSTeresa Johnson VCallSite.emitRemark("single-impl", 1077b0a1d3bdSTeresa Johnson TheFn->stripPointerCasts()->getName(), OREGetter); 1078d55d46f4STeresa Johnson auto &CB = VCallSite.CB; 10797110510eSArthur Eubanks assert(!CB.getCalledFunction() && "devirtualizing direct call?"); 1080d55d46f4STeresa Johnson IRBuilder<> Builder(&CB); 1081d55d46f4STeresa Johnson Value *Callee = 1082d55d46f4STeresa Johnson Builder.CreateBitCast(TheFn, CB.getCalledOperand()->getType()); 1083d55d46f4STeresa Johnson 1084d55d46f4STeresa Johnson // If checking is enabled, add support to compare the virtual function 1085d55d46f4STeresa Johnson // pointer to the devirtualized target. In case of a mismatch, perform a 1086d55d46f4STeresa Johnson // debug trap. 1087d55d46f4STeresa Johnson if (CheckDevirt) { 1088d55d46f4STeresa Johnson auto *Cond = Builder.CreateICmpNE(CB.getCalledOperand(), Callee); 1089d55d46f4STeresa Johnson Instruction *ThenTerm = 1090d55d46f4STeresa Johnson SplitBlockAndInsertIfThen(Cond, &CB, /*Unreachable=*/false); 1091d55d46f4STeresa Johnson Builder.SetInsertPoint(ThenTerm); 1092d55d46f4STeresa Johnson Function *TrapFn = Intrinsic::getDeclaration(&M, Intrinsic::debugtrap); 1093d55d46f4STeresa Johnson auto *CallTrap = Builder.CreateCall(TrapFn); 1094d55d46f4STeresa Johnson CallTrap->setDebugLoc(CB.getDebugLoc()); 1095d55d46f4STeresa Johnson } 1096d55d46f4STeresa Johnson 1097d55d46f4STeresa Johnson // Devirtualize. 1098d55d46f4STeresa Johnson CB.setCalledOperand(Callee); 1099d55d46f4STeresa Johnson 11000312f614SPeter Collingbourne // This use is no longer unsafe. 11010312f614SPeter Collingbourne if (VCallSite.NumUnsafeUses) 11020312f614SPeter Collingbourne --*VCallSite.NumUnsafeUses; 1103df49d1bbSPeter Collingbourne } 11042974856aSPeter Collingbourne if (CSInfo.isExported()) 11052325bb34SPeter Collingbourne IsExported = true; 110659675ba0SPeter Collingbourne CSInfo.markDevirt(); 110750cbd7ccSPeter Collingbourne }; 110850cbd7ccSPeter Collingbourne Apply(SlotInfo.CSInfo); 110950cbd7ccSPeter Collingbourne for (auto &P : SlotInfo.ConstCSInfo) 111050cbd7ccSPeter Collingbourne Apply(P.second); 111150cbd7ccSPeter Collingbourne } 111250cbd7ccSPeter Collingbourne 1113943afb57SEugene Leviant static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) { 1114943afb57SEugene Leviant // We can't add calls if we haven't seen a definition 1115943afb57SEugene Leviant if (Callee.getSummaryList().empty()) 1116943afb57SEugene Leviant return false; 1117943afb57SEugene Leviant 1118943afb57SEugene Leviant // Insert calls into the summary index so that the devirtualized targets 1119943afb57SEugene Leviant // are eligible for import. 1120943afb57SEugene Leviant // FIXME: Annotate type tests with hotness. For now, mark these as hot 1121943afb57SEugene Leviant // to better ensure we have the opportunity to inline them. 1122943afb57SEugene Leviant bool IsExported = false; 1123943afb57SEugene Leviant auto &S = Callee.getSummaryList()[0]; 1124943afb57SEugene Leviant CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* RelBF = */ 0); 1125943afb57SEugene Leviant auto AddCalls = [&](CallSiteInfo &CSInfo) { 1126943afb57SEugene Leviant for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) { 1127943afb57SEugene Leviant FS->addCall({Callee, CI}); 1128943afb57SEugene Leviant IsExported |= S->modulePath() != FS->modulePath(); 1129943afb57SEugene Leviant } 1130943afb57SEugene Leviant for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) { 1131943afb57SEugene Leviant FS->addCall({Callee, CI}); 1132943afb57SEugene Leviant IsExported |= S->modulePath() != FS->modulePath(); 1133943afb57SEugene Leviant } 1134943afb57SEugene Leviant }; 1135943afb57SEugene Leviant AddCalls(SlotInfo.CSInfo); 1136943afb57SEugene Leviant for (auto &P : SlotInfo.ConstCSInfo) 1137943afb57SEugene Leviant AddCalls(P.second); 1138943afb57SEugene Leviant return IsExported; 1139943afb57SEugene Leviant } 1140943afb57SEugene Leviant 114150cbd7ccSPeter Collingbourne bool DevirtModule::trySingleImplDevirt( 1142943afb57SEugene Leviant ModuleSummaryIndex *ExportSummary, 1143943afb57SEugene Leviant MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, 1144943afb57SEugene Leviant WholeProgramDevirtResolution *Res) { 114550cbd7ccSPeter Collingbourne // See if the program contains a single implementation of this virtual 114650cbd7ccSPeter Collingbourne // function. 114750cbd7ccSPeter Collingbourne Function *TheFn = TargetsForSlot[0].Fn; 114850cbd7ccSPeter Collingbourne for (auto &&Target : TargetsForSlot) 114950cbd7ccSPeter Collingbourne if (TheFn != Target.Fn) 115050cbd7ccSPeter Collingbourne return false; 115150cbd7ccSPeter Collingbourne 115250cbd7ccSPeter Collingbourne // If so, update each call site to call that implementation directly. 115350cbd7ccSPeter Collingbourne if (RemarksEnabled) 115450cbd7ccSPeter Collingbourne TargetsForSlot[0].WasDevirt = true; 11552325bb34SPeter Collingbourne 11562325bb34SPeter Collingbourne bool IsExported = false; 11572325bb34SPeter Collingbourne applySingleImplDevirt(SlotInfo, TheFn, IsExported); 11582325bb34SPeter Collingbourne if (!IsExported) 11592325bb34SPeter Collingbourne return false; 11602325bb34SPeter Collingbourne 11612325bb34SPeter Collingbourne // If the only implementation has local linkage, we must promote to external 11622325bb34SPeter Collingbourne // to make it visible to thin LTO objects. We can only get here during the 11632325bb34SPeter Collingbourne // ThinLTO export phase. 11642325bb34SPeter Collingbourne if (TheFn->hasLocalLinkage()) { 1165c6e5c465SHans Wennborg std::string NewName = (TheFn->getName() + ".llvm.merged").str(); 116688a58cf9SPeter Collingbourne 116788a58cf9SPeter Collingbourne // Since we are renaming the function, any comdats with the same name must 116888a58cf9SPeter Collingbourne // also be renamed. This is required when targeting COFF, as the comdat name 116988a58cf9SPeter Collingbourne // must match one of the names of the symbols in the comdat. 117088a58cf9SPeter Collingbourne if (Comdat *C = TheFn->getComdat()) { 117188a58cf9SPeter Collingbourne if (C->getName() == TheFn->getName()) { 117288a58cf9SPeter Collingbourne Comdat *NewC = M.getOrInsertComdat(NewName); 117388a58cf9SPeter Collingbourne NewC->setSelectionKind(C->getSelectionKind()); 117488a58cf9SPeter Collingbourne for (GlobalObject &GO : M.global_objects()) 117588a58cf9SPeter Collingbourne if (GO.getComdat() == C) 117688a58cf9SPeter Collingbourne GO.setComdat(NewC); 117788a58cf9SPeter Collingbourne } 117888a58cf9SPeter Collingbourne } 117988a58cf9SPeter Collingbourne 11802325bb34SPeter Collingbourne TheFn->setLinkage(GlobalValue::ExternalLinkage); 11812325bb34SPeter Collingbourne TheFn->setVisibility(GlobalValue::HiddenVisibility); 118288a58cf9SPeter Collingbourne TheFn->setName(NewName); 11832325bb34SPeter Collingbourne } 1184943afb57SEugene Leviant if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID())) 1185943afb57SEugene Leviant // Any needed promotion of 'TheFn' has already been done during 1186943afb57SEugene Leviant // LTO unit split, so we can ignore return value of AddCalls. 1187943afb57SEugene Leviant AddCalls(SlotInfo, TheFnVI); 11882325bb34SPeter Collingbourne 11892325bb34SPeter Collingbourne Res->TheKind = WholeProgramDevirtResolution::SingleImpl; 1190adcd0268SBenjamin Kramer Res->SingleImplName = std::string(TheFn->getName()); 11912325bb34SPeter Collingbourne 1192df49d1bbSPeter Collingbourne return true; 1193df49d1bbSPeter Collingbourne } 1194df49d1bbSPeter Collingbourne 1195d2df54e6STeresa Johnson bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot, 1196d2df54e6STeresa Johnson VTableSlotSummary &SlotSummary, 1197d2df54e6STeresa Johnson VTableSlotInfo &SlotInfo, 1198d2df54e6STeresa Johnson WholeProgramDevirtResolution *Res, 1199d2df54e6STeresa Johnson std::set<ValueInfo> &DevirtTargets) { 1200d2df54e6STeresa Johnson // See if the program contains a single implementation of this virtual 1201d2df54e6STeresa Johnson // function. 1202d2df54e6STeresa Johnson auto TheFn = TargetsForSlot[0]; 1203d2df54e6STeresa Johnson for (auto &&Target : TargetsForSlot) 1204d2df54e6STeresa Johnson if (TheFn != Target) 1205d2df54e6STeresa Johnson return false; 1206d2df54e6STeresa Johnson 1207d2df54e6STeresa Johnson // Don't devirtualize if we don't have target definition. 1208d2df54e6STeresa Johnson auto Size = TheFn.getSummaryList().size(); 1209d2df54e6STeresa Johnson if (!Size) 1210d2df54e6STeresa Johnson return false; 1211d2df54e6STeresa Johnson 12126d2032e2Sevgeny // Don't devirtualize function if we're told to skip it 12136d2032e2Sevgeny // in -wholeprogramdevirt-skip. 12146d2032e2Sevgeny if (FunctionsToSkip.match(TheFn.name())) 12156d2032e2Sevgeny return false; 12166d2032e2Sevgeny 1217d2df54e6STeresa Johnson // If the summary list contains multiple summaries where at least one is 1218d2df54e6STeresa Johnson // a local, give up, as we won't know which (possibly promoted) name to use. 1219d2df54e6STeresa Johnson for (auto &S : TheFn.getSummaryList()) 1220d2df54e6STeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1) 1221d2df54e6STeresa Johnson return false; 1222d2df54e6STeresa Johnson 1223d2df54e6STeresa Johnson // Collect functions devirtualized at least for one call site for stats. 1224d2df54e6STeresa Johnson if (PrintSummaryDevirt) 1225d2df54e6STeresa Johnson DevirtTargets.insert(TheFn); 1226d2df54e6STeresa Johnson 1227d2df54e6STeresa Johnson auto &S = TheFn.getSummaryList()[0]; 1228943afb57SEugene Leviant bool IsExported = AddCalls(SlotInfo, TheFn); 1229d2df54e6STeresa Johnson if (IsExported) 1230d2df54e6STeresa Johnson ExportedGUIDs.insert(TheFn.getGUID()); 1231d2df54e6STeresa Johnson 1232d2df54e6STeresa Johnson // Record in summary for use in devirtualization during the ThinLTO import 1233d2df54e6STeresa Johnson // step. 1234d2df54e6STeresa Johnson Res->TheKind = WholeProgramDevirtResolution::SingleImpl; 1235d2df54e6STeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage())) { 1236d2df54e6STeresa Johnson if (IsExported) 1237d2df54e6STeresa Johnson // If target is a local function and we are exporting it by 1238d2df54e6STeresa Johnson // devirtualizing a call in another module, we need to record the 1239d2df54e6STeresa Johnson // promoted name. 1240d2df54e6STeresa Johnson Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal( 1241d2df54e6STeresa Johnson TheFn.name(), ExportSummary.getModuleHash(S->modulePath())); 1242d2df54e6STeresa Johnson else { 1243d2df54e6STeresa Johnson LocalWPDTargetsMap[TheFn].push_back(SlotSummary); 1244adcd0268SBenjamin Kramer Res->SingleImplName = std::string(TheFn.name()); 1245d2df54e6STeresa Johnson } 1246d2df54e6STeresa Johnson } else 1247adcd0268SBenjamin Kramer Res->SingleImplName = std::string(TheFn.name()); 1248d2df54e6STeresa Johnson 1249d2df54e6STeresa Johnson // Name will be empty if this thin link driven off of serialized combined 1250d2df54e6STeresa Johnson // index (e.g. llvm-lto). However, WPD is not supported/invoked for the 1251d2df54e6STeresa Johnson // legacy LTO API anyway. 1252d2df54e6STeresa Johnson assert(!Res->SingleImplName.empty()); 1253d2df54e6STeresa Johnson 1254d2df54e6STeresa Johnson return true; 1255d2df54e6STeresa Johnson } 1256d2df54e6STeresa Johnson 12572974856aSPeter Collingbourne void DevirtModule::tryICallBranchFunnel( 12582974856aSPeter Collingbourne MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, 12592974856aSPeter Collingbourne WholeProgramDevirtResolution *Res, VTableSlot Slot) { 12602974856aSPeter Collingbourne Triple T(M.getTargetTriple()); 12612974856aSPeter Collingbourne if (T.getArch() != Triple::x86_64) 12622974856aSPeter Collingbourne return; 12632974856aSPeter Collingbourne 126466f53d71SVitaly Buka if (TargetsForSlot.size() > ClThreshold) 12652974856aSPeter Collingbourne return; 12662974856aSPeter Collingbourne 12672974856aSPeter Collingbourne bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted; 12682974856aSPeter Collingbourne if (!HasNonDevirt) 12692974856aSPeter Collingbourne for (auto &P : SlotInfo.ConstCSInfo) 12702974856aSPeter Collingbourne if (!P.second.AllCallSitesDevirted) { 12712974856aSPeter Collingbourne HasNonDevirt = true; 12722974856aSPeter Collingbourne break; 12732974856aSPeter Collingbourne } 12742974856aSPeter Collingbourne 12752974856aSPeter Collingbourne if (!HasNonDevirt) 12762974856aSPeter Collingbourne return; 12772974856aSPeter Collingbourne 12782974856aSPeter Collingbourne FunctionType *FT = 12792974856aSPeter Collingbourne FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true); 12802974856aSPeter Collingbourne Function *JT; 12812974856aSPeter Collingbourne if (isa<MDString>(Slot.TypeID)) { 12822974856aSPeter Collingbourne JT = Function::Create(FT, Function::ExternalLinkage, 1283f920da00SDylan McKay M.getDataLayout().getProgramAddressSpace(), 12842974856aSPeter Collingbourne getGlobalName(Slot, {}, "branch_funnel"), &M); 12852974856aSPeter Collingbourne JT->setVisibility(GlobalValue::HiddenVisibility); 12862974856aSPeter Collingbourne } else { 1287f920da00SDylan McKay JT = Function::Create(FT, Function::InternalLinkage, 1288f920da00SDylan McKay M.getDataLayout().getProgramAddressSpace(), 1289f920da00SDylan McKay "branch_funnel", &M); 12902974856aSPeter Collingbourne } 12912974856aSPeter Collingbourne JT->addAttribute(1, Attribute::Nest); 12922974856aSPeter Collingbourne 12932974856aSPeter Collingbourne std::vector<Value *> JTArgs; 12942974856aSPeter Collingbourne JTArgs.push_back(JT->arg_begin()); 12952974856aSPeter Collingbourne for (auto &T : TargetsForSlot) { 12962974856aSPeter Collingbourne JTArgs.push_back(getMemberAddr(T.TM)); 12972974856aSPeter Collingbourne JTArgs.push_back(T.Fn); 12982974856aSPeter Collingbourne } 12992974856aSPeter Collingbourne 13002974856aSPeter Collingbourne BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr); 13017976eb58SJames Y Knight Function *Intr = 13022974856aSPeter Collingbourne Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {}); 13032974856aSPeter Collingbourne 13042974856aSPeter Collingbourne auto *CI = CallInst::Create(Intr, JTArgs, "", BB); 13052974856aSPeter Collingbourne CI->setTailCallKind(CallInst::TCK_MustTail); 13062974856aSPeter Collingbourne ReturnInst::Create(M.getContext(), nullptr, BB); 13072974856aSPeter Collingbourne 13082974856aSPeter Collingbourne bool IsExported = false; 13092974856aSPeter Collingbourne applyICallBranchFunnel(SlotInfo, JT, IsExported); 13102974856aSPeter Collingbourne if (IsExported) 13112974856aSPeter Collingbourne Res->TheKind = WholeProgramDevirtResolution::BranchFunnel; 13122974856aSPeter Collingbourne } 13132974856aSPeter Collingbourne 13142974856aSPeter Collingbourne void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo, 13152974856aSPeter Collingbourne Constant *JT, bool &IsExported) { 13162974856aSPeter Collingbourne auto Apply = [&](CallSiteInfo &CSInfo) { 13172974856aSPeter Collingbourne if (CSInfo.isExported()) 13182974856aSPeter Collingbourne IsExported = true; 13192974856aSPeter Collingbourne if (CSInfo.AllCallSitesDevirted) 13202974856aSPeter Collingbourne return; 13212974856aSPeter Collingbourne for (auto &&VCallSite : CSInfo.CallSites) { 1322cea6f4d5SMircea Trofin CallBase &CB = VCallSite.CB; 13232974856aSPeter Collingbourne 13242974856aSPeter Collingbourne // Jump tables are only profitable if the retpoline mitigation is enabled. 1325cea6f4d5SMircea Trofin Attribute FSAttr = CB.getCaller()->getFnAttribute("target-features"); 1326aab90384SCraig Topper if (!FSAttr.isValid() || 13272974856aSPeter Collingbourne !FSAttr.getValueAsString().contains("+retpoline")) 13282974856aSPeter Collingbourne continue; 13292974856aSPeter Collingbourne 13302974856aSPeter Collingbourne if (RemarksEnabled) 1331b0a1d3bdSTeresa Johnson VCallSite.emitRemark("branch-funnel", 1332b0a1d3bdSTeresa Johnson JT->stripPointerCasts()->getName(), OREGetter); 13332974856aSPeter Collingbourne 13342974856aSPeter Collingbourne // Pass the address of the vtable in the nest register, which is r10 on 13352974856aSPeter Collingbourne // x86_64. 13362974856aSPeter Collingbourne std::vector<Type *> NewArgs; 13372974856aSPeter Collingbourne NewArgs.push_back(Int8PtrTy); 1338e53472deSKazu Hirata append_range(NewArgs, CB.getFunctionType()->params()); 13397976eb58SJames Y Knight FunctionType *NewFT = 1340cea6f4d5SMircea Trofin FunctionType::get(CB.getFunctionType()->getReturnType(), NewArgs, 1341cea6f4d5SMircea Trofin CB.getFunctionType()->isVarArg()); 13427976eb58SJames Y Knight PointerType *NewFTPtr = PointerType::getUnqual(NewFT); 13432974856aSPeter Collingbourne 1344cea6f4d5SMircea Trofin IRBuilder<> IRB(&CB); 13452974856aSPeter Collingbourne std::vector<Value *> Args; 13462974856aSPeter Collingbourne Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy)); 13478299fb8fSKazu Hirata llvm::append_range(Args, CB.args()); 13482974856aSPeter Collingbourne 1349cea6f4d5SMircea Trofin CallBase *NewCS = nullptr; 1350cea6f4d5SMircea Trofin if (isa<CallInst>(CB)) 13517976eb58SJames Y Knight NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args); 13522974856aSPeter Collingbourne else 1353cea6f4d5SMircea Trofin NewCS = IRB.CreateInvoke(NewFT, IRB.CreateBitCast(JT, NewFTPtr), 1354cea6f4d5SMircea Trofin cast<InvokeInst>(CB).getNormalDest(), 1355cea6f4d5SMircea Trofin cast<InvokeInst>(CB).getUnwindDest(), Args); 1356cea6f4d5SMircea Trofin NewCS->setCallingConv(CB.getCallingConv()); 13572974856aSPeter Collingbourne 1358cea6f4d5SMircea Trofin AttributeList Attrs = CB.getAttributes(); 13592974856aSPeter Collingbourne std::vector<AttributeSet> NewArgAttrs; 13602974856aSPeter Collingbourne NewArgAttrs.push_back(AttributeSet::get( 13612974856aSPeter Collingbourne M.getContext(), ArrayRef<Attribute>{Attribute::get( 13622974856aSPeter Collingbourne M.getContext(), Attribute::Nest)})); 13632974856aSPeter Collingbourne for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I) 1364*80ea2bb5SArthur Eubanks NewArgAttrs.push_back(Attrs.getParamAttrs(I)); 1365cea6f4d5SMircea Trofin NewCS->setAttributes( 1366*80ea2bb5SArthur Eubanks AttributeList::get(M.getContext(), Attrs.getFnAttrs(), 1367*80ea2bb5SArthur Eubanks Attrs.getRetAttrs(), NewArgAttrs)); 13682974856aSPeter Collingbourne 1369cea6f4d5SMircea Trofin CB.replaceAllUsesWith(NewCS); 1370cea6f4d5SMircea Trofin CB.eraseFromParent(); 13712974856aSPeter Collingbourne 13722974856aSPeter Collingbourne // This use is no longer unsafe. 13732974856aSPeter Collingbourne if (VCallSite.NumUnsafeUses) 13742974856aSPeter Collingbourne --*VCallSite.NumUnsafeUses; 13752974856aSPeter Collingbourne } 13762974856aSPeter Collingbourne // Don't mark as devirtualized because there may be callers compiled without 13772974856aSPeter Collingbourne // retpoline mitigation, which would mean that they are lowered to 13782974856aSPeter Collingbourne // llvm.type.test and therefore require an llvm.type.test resolution for the 13792974856aSPeter Collingbourne // type identifier. 13802974856aSPeter Collingbourne }; 13812974856aSPeter Collingbourne Apply(SlotInfo.CSInfo); 13822974856aSPeter Collingbourne for (auto &P : SlotInfo.ConstCSInfo) 13832974856aSPeter Collingbourne Apply(P.second); 13842974856aSPeter Collingbourne } 13852974856aSPeter Collingbourne 1386df49d1bbSPeter Collingbourne bool DevirtModule::tryEvaluateFunctionsWithArgs( 1387df49d1bbSPeter Collingbourne MutableArrayRef<VirtualCallTarget> TargetsForSlot, 138850cbd7ccSPeter Collingbourne ArrayRef<uint64_t> Args) { 1389df49d1bbSPeter Collingbourne // Evaluate each function and store the result in each target's RetVal 1390df49d1bbSPeter Collingbourne // field. 1391df49d1bbSPeter Collingbourne for (VirtualCallTarget &Target : TargetsForSlot) { 1392df49d1bbSPeter Collingbourne if (Target.Fn->arg_size() != Args.size() + 1) 1393df49d1bbSPeter Collingbourne return false; 1394df49d1bbSPeter Collingbourne 1395df49d1bbSPeter Collingbourne Evaluator Eval(M.getDataLayout(), nullptr); 1396df49d1bbSPeter Collingbourne SmallVector<Constant *, 2> EvalArgs; 1397df49d1bbSPeter Collingbourne EvalArgs.push_back( 1398df49d1bbSPeter Collingbourne Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0))); 139950cbd7ccSPeter Collingbourne for (unsigned I = 0; I != Args.size(); ++I) { 140050cbd7ccSPeter Collingbourne auto *ArgTy = dyn_cast<IntegerType>( 140150cbd7ccSPeter Collingbourne Target.Fn->getFunctionType()->getParamType(I + 1)); 140250cbd7ccSPeter Collingbourne if (!ArgTy) 140350cbd7ccSPeter Collingbourne return false; 140450cbd7ccSPeter Collingbourne EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I])); 140550cbd7ccSPeter Collingbourne } 140650cbd7ccSPeter Collingbourne 1407df49d1bbSPeter Collingbourne Constant *RetVal; 1408df49d1bbSPeter Collingbourne if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) || 1409df49d1bbSPeter Collingbourne !isa<ConstantInt>(RetVal)) 1410df49d1bbSPeter Collingbourne return false; 1411df49d1bbSPeter Collingbourne Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue(); 1412df49d1bbSPeter Collingbourne } 1413df49d1bbSPeter Collingbourne return true; 1414df49d1bbSPeter Collingbourne } 1415df49d1bbSPeter Collingbourne 141650cbd7ccSPeter Collingbourne void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, 141750cbd7ccSPeter Collingbourne uint64_t TheRetVal) { 14187110510eSArthur Eubanks for (auto Call : CSInfo.CallSites) { 14197110510eSArthur Eubanks if (!OptimizedCalls.insert(&Call.CB).second) 14207110510eSArthur Eubanks continue; 142150cbd7ccSPeter Collingbourne Call.replaceAndErase( 1422e963c89dSSam Elliott "uniform-ret-val", FnName, RemarksEnabled, OREGetter, 1423cea6f4d5SMircea Trofin ConstantInt::get(cast<IntegerType>(Call.CB.getType()), TheRetVal)); 14247110510eSArthur Eubanks } 142559675ba0SPeter Collingbourne CSInfo.markDevirt(); 142650cbd7ccSPeter Collingbourne } 142750cbd7ccSPeter Collingbourne 1428df49d1bbSPeter Collingbourne bool DevirtModule::tryUniformRetValOpt( 142977a8d563SPeter Collingbourne MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo, 143077a8d563SPeter Collingbourne WholeProgramDevirtResolution::ByArg *Res) { 1431df49d1bbSPeter Collingbourne // Uniform return value optimization. If all functions return the same 1432df49d1bbSPeter Collingbourne // constant, replace all calls with that constant. 1433df49d1bbSPeter Collingbourne uint64_t TheRetVal = TargetsForSlot[0].RetVal; 1434df49d1bbSPeter Collingbourne for (const VirtualCallTarget &Target : TargetsForSlot) 1435df49d1bbSPeter Collingbourne if (Target.RetVal != TheRetVal) 1436df49d1bbSPeter Collingbourne return false; 1437df49d1bbSPeter Collingbourne 143877a8d563SPeter Collingbourne if (CSInfo.isExported()) { 143977a8d563SPeter Collingbourne Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 144077a8d563SPeter Collingbourne Res->Info = TheRetVal; 144177a8d563SPeter Collingbourne } 144277a8d563SPeter Collingbourne 144350cbd7ccSPeter Collingbourne applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal); 1444f3403fd2SIvan Krasin if (RemarksEnabled) 1445f3403fd2SIvan Krasin for (auto &&Target : TargetsForSlot) 1446f3403fd2SIvan Krasin Target.WasDevirt = true; 1447df49d1bbSPeter Collingbourne return true; 1448df49d1bbSPeter Collingbourne } 1449df49d1bbSPeter Collingbourne 145059675ba0SPeter Collingbourne std::string DevirtModule::getGlobalName(VTableSlot Slot, 145159675ba0SPeter Collingbourne ArrayRef<uint64_t> Args, 145259675ba0SPeter Collingbourne StringRef Name) { 145359675ba0SPeter Collingbourne std::string FullName = "__typeid_"; 145459675ba0SPeter Collingbourne raw_string_ostream OS(FullName); 145559675ba0SPeter Collingbourne OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset; 145659675ba0SPeter Collingbourne for (uint64_t Arg : Args) 145759675ba0SPeter Collingbourne OS << '_' << Arg; 145859675ba0SPeter Collingbourne OS << '_' << Name; 145959675ba0SPeter Collingbourne return OS.str(); 146059675ba0SPeter Collingbourne } 146159675ba0SPeter Collingbourne 1462b15a35e6SPeter Collingbourne bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() { 1463b15a35e6SPeter Collingbourne Triple T(M.getTargetTriple()); 14646904cd94SFangrui Song return T.isX86() && T.getObjectFormat() == Triple::ELF; 1465b15a35e6SPeter Collingbourne } 1466b15a35e6SPeter Collingbourne 146759675ba0SPeter Collingbourne void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, 146859675ba0SPeter Collingbourne StringRef Name, Constant *C) { 146959675ba0SPeter Collingbourne GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage, 147059675ba0SPeter Collingbourne getGlobalName(Slot, Args, Name), C, &M); 147159675ba0SPeter Collingbourne GA->setVisibility(GlobalValue::HiddenVisibility); 147259675ba0SPeter Collingbourne } 147359675ba0SPeter Collingbourne 1474b15a35e6SPeter Collingbourne void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, 1475b15a35e6SPeter Collingbourne StringRef Name, uint32_t Const, 1476b15a35e6SPeter Collingbourne uint32_t &Storage) { 1477b15a35e6SPeter Collingbourne if (shouldExportConstantsAsAbsoluteSymbols()) { 1478b15a35e6SPeter Collingbourne exportGlobal( 1479b15a35e6SPeter Collingbourne Slot, Args, Name, 1480b15a35e6SPeter Collingbourne ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy)); 1481b15a35e6SPeter Collingbourne return; 1482b15a35e6SPeter Collingbourne } 1483b15a35e6SPeter Collingbourne 1484b15a35e6SPeter Collingbourne Storage = Const; 1485b15a35e6SPeter Collingbourne } 1486b15a35e6SPeter Collingbourne 148759675ba0SPeter Collingbourne Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, 1488b15a35e6SPeter Collingbourne StringRef Name) { 1489cc5c5888SBob Haarman Constant *C = 1490cc5c5888SBob Haarman M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty); 149159675ba0SPeter Collingbourne auto *GV = dyn_cast<GlobalVariable>(C); 1492b15a35e6SPeter Collingbourne if (GV) 1493b15a35e6SPeter Collingbourne GV->setVisibility(GlobalValue::HiddenVisibility); 1494b15a35e6SPeter Collingbourne return C; 1495b15a35e6SPeter Collingbourne } 1496b15a35e6SPeter Collingbourne 1497b15a35e6SPeter Collingbourne Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, 1498b15a35e6SPeter Collingbourne StringRef Name, IntegerType *IntTy, 1499b15a35e6SPeter Collingbourne uint32_t Storage) { 1500b15a35e6SPeter Collingbourne if (!shouldExportConstantsAsAbsoluteSymbols()) 1501b15a35e6SPeter Collingbourne return ConstantInt::get(IntTy, Storage); 1502b15a35e6SPeter Collingbourne 1503b15a35e6SPeter Collingbourne Constant *C = importGlobal(Slot, Args, Name); 1504b15a35e6SPeter Collingbourne auto *GV = cast<GlobalVariable>(C->stripPointerCasts()); 1505b15a35e6SPeter Collingbourne C = ConstantExpr::getPtrToInt(C, IntTy); 1506b15a35e6SPeter Collingbourne 150714dcf02fSPeter Collingbourne // We only need to set metadata if the global is newly created, in which 150814dcf02fSPeter Collingbourne // case it would not have hidden visibility. 15090deb9a9aSBenjamin Kramer if (GV->hasMetadata(LLVMContext::MD_absolute_symbol)) 151059675ba0SPeter Collingbourne return C; 151114dcf02fSPeter Collingbourne 151214dcf02fSPeter Collingbourne auto SetAbsRange = [&](uint64_t Min, uint64_t Max) { 151314dcf02fSPeter Collingbourne auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min)); 151414dcf02fSPeter Collingbourne auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max)); 151514dcf02fSPeter Collingbourne GV->setMetadata(LLVMContext::MD_absolute_symbol, 151614dcf02fSPeter Collingbourne MDNode::get(M.getContext(), {MinC, MaxC})); 151714dcf02fSPeter Collingbourne }; 1518b15a35e6SPeter Collingbourne unsigned AbsWidth = IntTy->getBitWidth(); 151914dcf02fSPeter Collingbourne if (AbsWidth == IntPtrTy->getBitWidth()) 152014dcf02fSPeter Collingbourne SetAbsRange(~0ull, ~0ull); // Full set. 1521b15a35e6SPeter Collingbourne else 152214dcf02fSPeter Collingbourne SetAbsRange(0, 1ull << AbsWidth); 1523b15a35e6SPeter Collingbourne return C; 152459675ba0SPeter Collingbourne } 152559675ba0SPeter Collingbourne 152650cbd7ccSPeter Collingbourne void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, 152750cbd7ccSPeter Collingbourne bool IsOne, 152850cbd7ccSPeter Collingbourne Constant *UniqueMemberAddr) { 152950cbd7ccSPeter Collingbourne for (auto &&Call : CSInfo.CallSites) { 15307110510eSArthur Eubanks if (!OptimizedCalls.insert(&Call.CB).second) 15317110510eSArthur Eubanks continue; 1532cea6f4d5SMircea Trofin IRBuilder<> B(&Call.CB); 1533001052a0SPeter Collingbourne Value *Cmp = 1534cc5c5888SBob Haarman B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, Call.VTable, 1535cc5c5888SBob Haarman B.CreateBitCast(UniqueMemberAddr, Call.VTable->getType())); 1536cea6f4d5SMircea Trofin Cmp = B.CreateZExt(Cmp, Call.CB.getType()); 1537e963c89dSSam Elliott Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter, 1538e963c89dSSam Elliott Cmp); 153950cbd7ccSPeter Collingbourne } 154059675ba0SPeter Collingbourne CSInfo.markDevirt(); 154150cbd7ccSPeter Collingbourne } 154250cbd7ccSPeter Collingbourne 15432974856aSPeter Collingbourne Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) { 15442974856aSPeter Collingbourne Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy); 15452974856aSPeter Collingbourne return ConstantExpr::getGetElementPtr(Int8Ty, C, 15462974856aSPeter Collingbourne ConstantInt::get(Int64Ty, M->Offset)); 15472974856aSPeter Collingbourne } 15482974856aSPeter Collingbourne 1549df49d1bbSPeter Collingbourne bool DevirtModule::tryUniqueRetValOpt( 1550f3403fd2SIvan Krasin unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot, 155159675ba0SPeter Collingbourne CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res, 155259675ba0SPeter Collingbourne VTableSlot Slot, ArrayRef<uint64_t> Args) { 1553df49d1bbSPeter Collingbourne // IsOne controls whether we look for a 0 or a 1. 1554df49d1bbSPeter Collingbourne auto tryUniqueRetValOptFor = [&](bool IsOne) { 1555cdc71612SEugene Zelenko const TypeMemberInfo *UniqueMember = nullptr; 1556df49d1bbSPeter Collingbourne for (const VirtualCallTarget &Target : TargetsForSlot) { 15573866cc5fSPeter Collingbourne if (Target.RetVal == (IsOne ? 1 : 0)) { 15587efd7506SPeter Collingbourne if (UniqueMember) 1559df49d1bbSPeter Collingbourne return false; 15607efd7506SPeter Collingbourne UniqueMember = Target.TM; 1561df49d1bbSPeter Collingbourne } 1562df49d1bbSPeter Collingbourne } 1563df49d1bbSPeter Collingbourne 15647efd7506SPeter Collingbourne // We should have found a unique member or bailed out by now. We already 1565df49d1bbSPeter Collingbourne // checked for a uniform return value in tryUniformRetValOpt. 15667efd7506SPeter Collingbourne assert(UniqueMember); 1567df49d1bbSPeter Collingbourne 15682974856aSPeter Collingbourne Constant *UniqueMemberAddr = getMemberAddr(UniqueMember); 156959675ba0SPeter Collingbourne if (CSInfo.isExported()) { 157059675ba0SPeter Collingbourne Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 157159675ba0SPeter Collingbourne Res->Info = IsOne; 157259675ba0SPeter Collingbourne 157359675ba0SPeter Collingbourne exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr); 157459675ba0SPeter Collingbourne } 157559675ba0SPeter Collingbourne 157659675ba0SPeter Collingbourne // Replace each call with the comparison. 157750cbd7ccSPeter Collingbourne applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne, 157850cbd7ccSPeter Collingbourne UniqueMemberAddr); 157950cbd7ccSPeter Collingbourne 1580f3403fd2SIvan Krasin // Update devirtualization statistics for targets. 1581f3403fd2SIvan Krasin if (RemarksEnabled) 1582f3403fd2SIvan Krasin for (auto &&Target : TargetsForSlot) 1583f3403fd2SIvan Krasin Target.WasDevirt = true; 1584f3403fd2SIvan Krasin 1585df49d1bbSPeter Collingbourne return true; 1586df49d1bbSPeter Collingbourne }; 1587df49d1bbSPeter Collingbourne 1588df49d1bbSPeter Collingbourne if (BitWidth == 1) { 1589df49d1bbSPeter Collingbourne if (tryUniqueRetValOptFor(true)) 1590df49d1bbSPeter Collingbourne return true; 1591df49d1bbSPeter Collingbourne if (tryUniqueRetValOptFor(false)) 1592df49d1bbSPeter Collingbourne return true; 1593df49d1bbSPeter Collingbourne } 1594df49d1bbSPeter Collingbourne return false; 1595df49d1bbSPeter Collingbourne } 1596df49d1bbSPeter Collingbourne 159750cbd7ccSPeter Collingbourne void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, 159850cbd7ccSPeter Collingbourne Constant *Byte, Constant *Bit) { 159950cbd7ccSPeter Collingbourne for (auto Call : CSInfo.CallSites) { 16007110510eSArthur Eubanks if (!OptimizedCalls.insert(&Call.CB).second) 16017110510eSArthur Eubanks continue; 1602cea6f4d5SMircea Trofin auto *RetType = cast<IntegerType>(Call.CB.getType()); 1603cea6f4d5SMircea Trofin IRBuilder<> B(&Call.CB); 1604001052a0SPeter Collingbourne Value *Addr = 1605001052a0SPeter Collingbourne B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte); 160650cbd7ccSPeter Collingbourne if (RetType->getBitWidth() == 1) { 160714359ef1SJames Y Knight Value *Bits = B.CreateLoad(Int8Ty, Addr); 160850cbd7ccSPeter Collingbourne Value *BitsAndBit = B.CreateAnd(Bits, Bit); 160950cbd7ccSPeter Collingbourne auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); 161050cbd7ccSPeter Collingbourne Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled, 1611e963c89dSSam Elliott OREGetter, IsBitSet); 161250cbd7ccSPeter Collingbourne } else { 161350cbd7ccSPeter Collingbourne Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo()); 161450cbd7ccSPeter Collingbourne Value *Val = B.CreateLoad(RetType, ValAddr); 1615e963c89dSSam Elliott Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, 1616e963c89dSSam Elliott OREGetter, Val); 161750cbd7ccSPeter Collingbourne } 161850cbd7ccSPeter Collingbourne } 161914dcf02fSPeter Collingbourne CSInfo.markDevirt(); 162050cbd7ccSPeter Collingbourne } 162150cbd7ccSPeter Collingbourne 1622df49d1bbSPeter Collingbourne bool DevirtModule::tryVirtualConstProp( 162359675ba0SPeter Collingbourne MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, 162459675ba0SPeter Collingbourne WholeProgramDevirtResolution *Res, VTableSlot Slot) { 1625df49d1bbSPeter Collingbourne // This only works if the function returns an integer. 1626df49d1bbSPeter Collingbourne auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType()); 1627df49d1bbSPeter Collingbourne if (!RetType) 1628df49d1bbSPeter Collingbourne return false; 1629df49d1bbSPeter Collingbourne unsigned BitWidth = RetType->getBitWidth(); 1630df49d1bbSPeter Collingbourne if (BitWidth > 64) 1631df49d1bbSPeter Collingbourne return false; 1632df49d1bbSPeter Collingbourne 163317febdbbSPeter Collingbourne // Make sure that each function is defined, does not access memory, takes at 163417febdbbSPeter Collingbourne // least one argument, does not use its first argument (which we assume is 163517febdbbSPeter Collingbourne // 'this'), and has the same return type. 163637317f12SPeter Collingbourne // 163737317f12SPeter Collingbourne // Note that we test whether this copy of the function is readnone, rather 163837317f12SPeter Collingbourne // than testing function attributes, which must hold for any copy of the 163937317f12SPeter Collingbourne // function, even a less optimized version substituted at link time. This is 164037317f12SPeter Collingbourne // sound because the virtual constant propagation optimizations effectively 164137317f12SPeter Collingbourne // inline all implementations of the virtual function into each call site, 164237317f12SPeter Collingbourne // rather than using function attributes to perform local optimization. 1643df49d1bbSPeter Collingbourne for (VirtualCallTarget &Target : TargetsForSlot) { 164437317f12SPeter Collingbourne if (Target.Fn->isDeclaration() || 164537317f12SPeter Collingbourne computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) != 164637317f12SPeter Collingbourne MAK_ReadNone || 164717febdbbSPeter Collingbourne Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() || 1648df49d1bbSPeter Collingbourne Target.Fn->getReturnType() != RetType) 1649df49d1bbSPeter Collingbourne return false; 1650df49d1bbSPeter Collingbourne } 1651df49d1bbSPeter Collingbourne 165250cbd7ccSPeter Collingbourne for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) { 1653df49d1bbSPeter Collingbourne if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first)) 1654df49d1bbSPeter Collingbourne continue; 1655df49d1bbSPeter Collingbourne 165677a8d563SPeter Collingbourne WholeProgramDevirtResolution::ByArg *ResByArg = nullptr; 165777a8d563SPeter Collingbourne if (Res) 165877a8d563SPeter Collingbourne ResByArg = &Res->ResByArg[CSByConstantArg.first]; 165977a8d563SPeter Collingbourne 166077a8d563SPeter Collingbourne if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg)) 1661df49d1bbSPeter Collingbourne continue; 1662df49d1bbSPeter Collingbourne 166359675ba0SPeter Collingbourne if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second, 166459675ba0SPeter Collingbourne ResByArg, Slot, CSByConstantArg.first)) 1665df49d1bbSPeter Collingbourne continue; 1666df49d1bbSPeter Collingbourne 16677efd7506SPeter Collingbourne // Find an allocation offset in bits in all vtables associated with the 16687efd7506SPeter Collingbourne // type. 1669df49d1bbSPeter Collingbourne uint64_t AllocBefore = 1670df49d1bbSPeter Collingbourne findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); 1671df49d1bbSPeter Collingbourne uint64_t AllocAfter = 1672df49d1bbSPeter Collingbourne findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); 1673df49d1bbSPeter Collingbourne 1674df49d1bbSPeter Collingbourne // Calculate the total amount of padding needed to store a value at both 1675df49d1bbSPeter Collingbourne // ends of the object. 1676df49d1bbSPeter Collingbourne uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; 1677df49d1bbSPeter Collingbourne for (auto &&Target : TargetsForSlot) { 1678df49d1bbSPeter Collingbourne TotalPaddingBefore += std::max<int64_t>( 1679df49d1bbSPeter Collingbourne (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); 1680df49d1bbSPeter Collingbourne TotalPaddingAfter += std::max<int64_t>( 1681df49d1bbSPeter Collingbourne (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); 1682df49d1bbSPeter Collingbourne } 1683df49d1bbSPeter Collingbourne 1684df49d1bbSPeter Collingbourne // If the amount of padding is too large, give up. 1685df49d1bbSPeter Collingbourne // FIXME: do something smarter here. 1686df49d1bbSPeter Collingbourne if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) 1687df49d1bbSPeter Collingbourne continue; 1688df49d1bbSPeter Collingbourne 1689df49d1bbSPeter Collingbourne // Calculate the offset to the value as a (possibly negative) byte offset 1690df49d1bbSPeter Collingbourne // and (if applicable) a bit offset, and store the values in the targets. 1691df49d1bbSPeter Collingbourne int64_t OffsetByte; 1692df49d1bbSPeter Collingbourne uint64_t OffsetBit; 1693df49d1bbSPeter Collingbourne if (TotalPaddingBefore <= TotalPaddingAfter) 1694df49d1bbSPeter Collingbourne setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, 1695df49d1bbSPeter Collingbourne OffsetBit); 1696df49d1bbSPeter Collingbourne else 1697df49d1bbSPeter Collingbourne setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, 1698df49d1bbSPeter Collingbourne OffsetBit); 1699df49d1bbSPeter Collingbourne 1700f3403fd2SIvan Krasin if (RemarksEnabled) 1701f3403fd2SIvan Krasin for (auto &&Target : TargetsForSlot) 1702f3403fd2SIvan Krasin Target.WasDevirt = true; 1703f3403fd2SIvan Krasin 170414dcf02fSPeter Collingbourne 170514dcf02fSPeter Collingbourne if (CSByConstantArg.second.isExported()) { 170614dcf02fSPeter Collingbourne ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 1707b15a35e6SPeter Collingbourne exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte, 1708b15a35e6SPeter Collingbourne ResByArg->Byte); 1709b15a35e6SPeter Collingbourne exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit, 1710b15a35e6SPeter Collingbourne ResByArg->Bit); 171114dcf02fSPeter Collingbourne } 171214dcf02fSPeter Collingbourne 171314dcf02fSPeter Collingbourne // Rewrite each call to a load from OffsetByte/OffsetBit. 1714b15a35e6SPeter Collingbourne Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte); 1715b15a35e6SPeter Collingbourne Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit); 171650cbd7ccSPeter Collingbourne applyVirtualConstProp(CSByConstantArg.second, 171750cbd7ccSPeter Collingbourne TargetsForSlot[0].Fn->getName(), ByteConst, BitConst); 1718df49d1bbSPeter Collingbourne } 1719df49d1bbSPeter Collingbourne return true; 1720df49d1bbSPeter Collingbourne } 1721df49d1bbSPeter Collingbourne 1722df49d1bbSPeter Collingbourne void DevirtModule::rebuildGlobal(VTableBits &B) { 1723df49d1bbSPeter Collingbourne if (B.Before.Bytes.empty() && B.After.Bytes.empty()) 1724df49d1bbSPeter Collingbourne return; 1725df49d1bbSPeter Collingbourne 1726ef5cfc2dSPeter Collingbourne // Align the before byte array to the global's minimum alignment so that we 1727ef5cfc2dSPeter Collingbourne // don't break any alignment requirements on the global. 1728d3085c25SGuillaume Chatelet Align Alignment = M.getDataLayout().getValueOrABITypeAlignment( 1729d3085c25SGuillaume Chatelet B.GV->getAlign(), B.GV->getValueType()); 17300e62011dSGuillaume Chatelet B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment)); 1731df49d1bbSPeter Collingbourne 1732df49d1bbSPeter Collingbourne // Before was stored in reverse order; flip it now. 1733df49d1bbSPeter Collingbourne for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I) 1734df49d1bbSPeter Collingbourne std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]); 1735df49d1bbSPeter Collingbourne 1736df49d1bbSPeter Collingbourne // Build an anonymous global containing the before bytes, followed by the 1737df49d1bbSPeter Collingbourne // original initializer, followed by the after bytes. 1738df49d1bbSPeter Collingbourne auto NewInit = ConstantStruct::getAnon( 1739df49d1bbSPeter Collingbourne {ConstantDataArray::get(M.getContext(), B.Before.Bytes), 1740df49d1bbSPeter Collingbourne B.GV->getInitializer(), 1741df49d1bbSPeter Collingbourne ConstantDataArray::get(M.getContext(), B.After.Bytes)}); 1742df49d1bbSPeter Collingbourne auto NewGV = 1743df49d1bbSPeter Collingbourne new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(), 1744df49d1bbSPeter Collingbourne GlobalVariable::PrivateLinkage, NewInit, "", B.GV); 1745df49d1bbSPeter Collingbourne NewGV->setSection(B.GV->getSection()); 1746df49d1bbSPeter Collingbourne NewGV->setComdat(B.GV->getComdat()); 17470e62011dSGuillaume Chatelet NewGV->setAlignment(MaybeAlign(B.GV->getAlignment())); 1748df49d1bbSPeter Collingbourne 17490312f614SPeter Collingbourne // Copy the original vtable's metadata to the anonymous global, adjusting 17500312f614SPeter Collingbourne // offsets as required. 17510312f614SPeter Collingbourne NewGV->copyMetadata(B.GV, B.Before.Bytes.size()); 17520312f614SPeter Collingbourne 1753df49d1bbSPeter Collingbourne // Build an alias named after the original global, pointing at the second 1754df49d1bbSPeter Collingbourne // element (the original initializer). 1755df49d1bbSPeter Collingbourne auto Alias = GlobalAlias::create( 1756df49d1bbSPeter Collingbourne B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", 1757df49d1bbSPeter Collingbourne ConstantExpr::getGetElementPtr( 1758df49d1bbSPeter Collingbourne NewInit->getType(), NewGV, 1759df49d1bbSPeter Collingbourne ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0), 1760df49d1bbSPeter Collingbourne ConstantInt::get(Int32Ty, 1)}), 1761df49d1bbSPeter Collingbourne &M); 1762df49d1bbSPeter Collingbourne Alias->setVisibility(B.GV->getVisibility()); 1763df49d1bbSPeter Collingbourne Alias->takeName(B.GV); 1764df49d1bbSPeter Collingbourne 1765df49d1bbSPeter Collingbourne B.GV->replaceAllUsesWith(Alias); 1766df49d1bbSPeter Collingbourne B.GV->eraseFromParent(); 1767df49d1bbSPeter Collingbourne } 1768df49d1bbSPeter Collingbourne 1769f3403fd2SIvan Krasin bool DevirtModule::areRemarksEnabled() { 1770f3403fd2SIvan Krasin const auto &FL = M.getFunctionList(); 17715e1c0e76STeresa Johnson for (const Function &Fn : FL) { 1772de53bfb9SAdam Nemet const auto &BBL = Fn.getBasicBlockList(); 1773de53bfb9SAdam Nemet if (BBL.empty()) 17745e1c0e76STeresa Johnson continue; 1775de53bfb9SAdam Nemet auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front()); 1776f3403fd2SIvan Krasin return DI.isEnabled(); 1777f3403fd2SIvan Krasin } 17785e1c0e76STeresa Johnson return false; 17795e1c0e76STeresa Johnson } 1780f3403fd2SIvan Krasin 17816014c46cSTeresa Johnson void DevirtModule::scanTypeTestUsers( 17826014c46cSTeresa Johnson Function *TypeTestFunc, 17836014c46cSTeresa Johnson DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { 1784df49d1bbSPeter Collingbourne // Find all virtual calls via a virtual table pointer %p under an assumption 17857efd7506SPeter Collingbourne // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p 17867efd7506SPeter Collingbourne // points to a member of the type identifier %md. Group calls by (type ID, 17877efd7506SPeter Collingbourne // offset) pair (effectively the identity of the virtual function) and store 17887efd7506SPeter Collingbourne // to CallSlots. 17897efd7506SPeter Collingbourne for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end(); 1790df49d1bbSPeter Collingbourne I != E;) { 1791df49d1bbSPeter Collingbourne auto CI = dyn_cast<CallInst>(I->getUser()); 1792df49d1bbSPeter Collingbourne ++I; 1793df49d1bbSPeter Collingbourne if (!CI) 1794df49d1bbSPeter Collingbourne continue; 1795df49d1bbSPeter Collingbourne 1796ccdc225cSPeter Collingbourne // Search for virtual calls based on %p and add them to DevirtCalls. 1797ccdc225cSPeter Collingbourne SmallVector<DevirtCallSite, 1> DevirtCalls; 1798df49d1bbSPeter Collingbourne SmallVector<CallInst *, 1> Assumes; 1799f24136f1STeresa Johnson auto &DT = LookupDomTree(*CI->getFunction()); 1800f24136f1STeresa Johnson findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT); 1801df49d1bbSPeter Collingbourne 180280bf137fSTeresa Johnson Metadata *TypeId = 180380bf137fSTeresa Johnson cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata(); 18046014c46cSTeresa Johnson // If we found any, add them to CallSlots. 18056014c46cSTeresa Johnson if (!Assumes.empty()) { 1806df49d1bbSPeter Collingbourne Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); 1807d291bd51STeresa Johnson for (DevirtCallSite Call : DevirtCalls) 1808cea6f4d5SMircea Trofin CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, nullptr); 1809ccdc225cSPeter Collingbourne } 1810df49d1bbSPeter Collingbourne 18116014c46cSTeresa Johnson auto RemoveTypeTestAssumes = [&]() { 18127efd7506SPeter Collingbourne // We no longer need the assumes or the type test. 1813df49d1bbSPeter Collingbourne for (auto Assume : Assumes) 1814df49d1bbSPeter Collingbourne Assume->eraseFromParent(); 1815df49d1bbSPeter Collingbourne // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we 1816df49d1bbSPeter Collingbourne // may use the vtable argument later. 1817df49d1bbSPeter Collingbourne if (CI->use_empty()) 1818df49d1bbSPeter Collingbourne CI->eraseFromParent(); 18196014c46cSTeresa Johnson }; 18206014c46cSTeresa Johnson 18216014c46cSTeresa Johnson // At this point we could remove all type test assume sequences, as they 18226014c46cSTeresa Johnson // were originally inserted for WPD. However, we can keep these in the 18236014c46cSTeresa Johnson // code stream for later analysis (e.g. to help drive more efficient ICP 18246014c46cSTeresa Johnson // sequences). They will eventually be removed by a second LowerTypeTests 18256014c46cSTeresa Johnson // invocation that cleans them up. In order to do this correctly, the first 18266014c46cSTeresa Johnson // LowerTypeTests invocation needs to know that they have "Unknown" type 18276014c46cSTeresa Johnson // test resolution, so that they aren't treated as Unsat and lowered to 18286014c46cSTeresa Johnson // False, which will break any uses on assumes. Below we remove any type 18296014c46cSTeresa Johnson // test assumes that will not be treated as Unknown by LTT. 18306014c46cSTeresa Johnson 18316014c46cSTeresa Johnson // The type test assumes will be treated by LTT as Unsat if the type id is 18326014c46cSTeresa Johnson // not used on a global (in which case it has no entry in the TypeIdMap). 18336014c46cSTeresa Johnson if (!TypeIdMap.count(TypeId)) 18346014c46cSTeresa Johnson RemoveTypeTestAssumes(); 18356014c46cSTeresa Johnson 18366014c46cSTeresa Johnson // For ThinLTO importing, we need to remove the type test assumes if this is 18376014c46cSTeresa Johnson // an MDString type id without a corresponding TypeIdSummary. Any 18386014c46cSTeresa Johnson // non-MDString type ids are ignored and treated as Unknown by LTT, so their 18396014c46cSTeresa Johnson // type test assumes can be kept. If the MDString type id is missing a 18406014c46cSTeresa Johnson // TypeIdSummary (e.g. because there was no use on a vcall, preventing the 18416014c46cSTeresa Johnson // exporting phase of WPD from analyzing it), then it would be treated as 18426014c46cSTeresa Johnson // Unsat by LTT and we need to remove its type test assumes here. If not 18436014c46cSTeresa Johnson // used on a vcall we don't need them for later optimization use in any 18446014c46cSTeresa Johnson // case. 18456014c46cSTeresa Johnson else if (ImportSummary && isa<MDString>(TypeId)) { 18466014c46cSTeresa Johnson const TypeIdSummary *TidSummary = 18476014c46cSTeresa Johnson ImportSummary->getTypeIdSummary(cast<MDString>(TypeId)->getString()); 18486014c46cSTeresa Johnson if (!TidSummary) 18496014c46cSTeresa Johnson RemoveTypeTestAssumes(); 18506014c46cSTeresa Johnson else 18516014c46cSTeresa Johnson // If one was created it should not be Unsat, because if we reached here 18526014c46cSTeresa Johnson // the type id was used on a global. 18536014c46cSTeresa Johnson assert(TidSummary->TTRes.TheKind != TypeTestResolution::Unsat); 18546014c46cSTeresa Johnson } 1855df49d1bbSPeter Collingbourne } 18560312f614SPeter Collingbourne } 18570312f614SPeter Collingbourne 18580312f614SPeter Collingbourne void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) { 18590312f614SPeter Collingbourne Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test); 18600312f614SPeter Collingbourne 18610312f614SPeter Collingbourne for (auto I = TypeCheckedLoadFunc->use_begin(), 18620312f614SPeter Collingbourne E = TypeCheckedLoadFunc->use_end(); 18630312f614SPeter Collingbourne I != E;) { 18640312f614SPeter Collingbourne auto CI = dyn_cast<CallInst>(I->getUser()); 18650312f614SPeter Collingbourne ++I; 18660312f614SPeter Collingbourne if (!CI) 18670312f614SPeter Collingbourne continue; 18680312f614SPeter Collingbourne 18690312f614SPeter Collingbourne Value *Ptr = CI->getArgOperand(0); 18700312f614SPeter Collingbourne Value *Offset = CI->getArgOperand(1); 18710312f614SPeter Collingbourne Value *TypeIdValue = CI->getArgOperand(2); 18720312f614SPeter Collingbourne Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata(); 18730312f614SPeter Collingbourne 18740312f614SPeter Collingbourne SmallVector<DevirtCallSite, 1> DevirtCalls; 18750312f614SPeter Collingbourne SmallVector<Instruction *, 1> LoadedPtrs; 18760312f614SPeter Collingbourne SmallVector<Instruction *, 1> Preds; 18770312f614SPeter Collingbourne bool HasNonCallUses = false; 1878f24136f1STeresa Johnson auto &DT = LookupDomTree(*CI->getFunction()); 18790312f614SPeter Collingbourne findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, 1880f24136f1STeresa Johnson HasNonCallUses, CI, DT); 18810312f614SPeter Collingbourne 18820312f614SPeter Collingbourne // Start by generating "pessimistic" code that explicitly loads the function 18830312f614SPeter Collingbourne // pointer from the vtable and performs the type check. If possible, we will 18840312f614SPeter Collingbourne // eliminate the load and the type check later. 18850312f614SPeter Collingbourne 18860312f614SPeter Collingbourne // If possible, only generate the load at the point where it is used. 18870312f614SPeter Collingbourne // This helps avoid unnecessary spills. 18880312f614SPeter Collingbourne IRBuilder<> LoadB( 18890312f614SPeter Collingbourne (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI); 18900312f614SPeter Collingbourne Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset); 18910312f614SPeter Collingbourne Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy)); 18920312f614SPeter Collingbourne Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr); 18930312f614SPeter Collingbourne 18940312f614SPeter Collingbourne for (Instruction *LoadedPtr : LoadedPtrs) { 18950312f614SPeter Collingbourne LoadedPtr->replaceAllUsesWith(LoadedValue); 18960312f614SPeter Collingbourne LoadedPtr->eraseFromParent(); 18970312f614SPeter Collingbourne } 18980312f614SPeter Collingbourne 18990312f614SPeter Collingbourne // Likewise for the type test. 19000312f614SPeter Collingbourne IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI); 19010312f614SPeter Collingbourne CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue}); 19020312f614SPeter Collingbourne 19030312f614SPeter Collingbourne for (Instruction *Pred : Preds) { 19040312f614SPeter Collingbourne Pred->replaceAllUsesWith(TypeTestCall); 19050312f614SPeter Collingbourne Pred->eraseFromParent(); 19060312f614SPeter Collingbourne } 19070312f614SPeter Collingbourne 19080312f614SPeter Collingbourne // We have already erased any extractvalue instructions that refer to the 19090312f614SPeter Collingbourne // intrinsic call, but the intrinsic may have other non-extractvalue uses 19100312f614SPeter Collingbourne // (although this is unlikely). In that case, explicitly build a pair and 19110312f614SPeter Collingbourne // RAUW it. 19120312f614SPeter Collingbourne if (!CI->use_empty()) { 19130312f614SPeter Collingbourne Value *Pair = UndefValue::get(CI->getType()); 19140312f614SPeter Collingbourne IRBuilder<> B(CI); 19150312f614SPeter Collingbourne Pair = B.CreateInsertValue(Pair, LoadedValue, {0}); 19160312f614SPeter Collingbourne Pair = B.CreateInsertValue(Pair, TypeTestCall, {1}); 19170312f614SPeter Collingbourne CI->replaceAllUsesWith(Pair); 19180312f614SPeter Collingbourne } 19190312f614SPeter Collingbourne 19200312f614SPeter Collingbourne // The number of unsafe uses is initially the number of uses. 19210312f614SPeter Collingbourne auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall]; 19220312f614SPeter Collingbourne NumUnsafeUses = DevirtCalls.size(); 19230312f614SPeter Collingbourne 19240312f614SPeter Collingbourne // If the function pointer has a non-call user, we cannot eliminate the type 19250312f614SPeter Collingbourne // check, as one of those users may eventually call the pointer. Increment 19260312f614SPeter Collingbourne // the unsafe use count to make sure it cannot reach zero. 19270312f614SPeter Collingbourne if (HasNonCallUses) 19280312f614SPeter Collingbourne ++NumUnsafeUses; 19290312f614SPeter Collingbourne for (DevirtCallSite Call : DevirtCalls) { 1930cea6f4d5SMircea Trofin CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, 193150cbd7ccSPeter Collingbourne &NumUnsafeUses); 19320312f614SPeter Collingbourne } 19330312f614SPeter Collingbourne 19340312f614SPeter Collingbourne CI->eraseFromParent(); 19350312f614SPeter Collingbourne } 19360312f614SPeter Collingbourne } 19370312f614SPeter Collingbourne 19386d284fabSPeter Collingbourne void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) { 1939d2df54e6STeresa Johnson auto *TypeId = dyn_cast<MDString>(Slot.TypeID); 1940d2df54e6STeresa Johnson if (!TypeId) 1941d2df54e6STeresa Johnson return; 19429a3f9797SPeter Collingbourne const TypeIdSummary *TidSummary = 1943d2df54e6STeresa Johnson ImportSummary->getTypeIdSummary(TypeId->getString()); 19449a3f9797SPeter Collingbourne if (!TidSummary) 19459a3f9797SPeter Collingbourne return; 19469a3f9797SPeter Collingbourne auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset); 19479a3f9797SPeter Collingbourne if (ResI == TidSummary->WPDRes.end()) 19489a3f9797SPeter Collingbourne return; 19499a3f9797SPeter Collingbourne const WholeProgramDevirtResolution &Res = ResI->second; 19506d284fabSPeter Collingbourne 19516d284fabSPeter Collingbourne if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) { 1952d2df54e6STeresa Johnson assert(!Res.SingleImplName.empty()); 19536d284fabSPeter Collingbourne // The type of the function in the declaration is irrelevant because every 19546d284fabSPeter Collingbourne // call site will cast it to the correct type. 195513680223SJames Y Knight Constant *SingleImpl = 195613680223SJames Y Knight cast<Constant>(M.getOrInsertFunction(Res.SingleImplName, 195713680223SJames Y Knight Type::getVoidTy(M.getContext())) 195813680223SJames Y Knight .getCallee()); 19596d284fabSPeter Collingbourne 19606d284fabSPeter Collingbourne // This is the import phase so we should not be exporting anything. 19616d284fabSPeter Collingbourne bool IsExported = false; 19626d284fabSPeter Collingbourne applySingleImplDevirt(SlotInfo, SingleImpl, IsExported); 19636d284fabSPeter Collingbourne assert(!IsExported); 19646d284fabSPeter Collingbourne } 19650152c815SPeter Collingbourne 19660152c815SPeter Collingbourne for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) { 19670152c815SPeter Collingbourne auto I = Res.ResByArg.find(CSByConstantArg.first); 19680152c815SPeter Collingbourne if (I == Res.ResByArg.end()) 19690152c815SPeter Collingbourne continue; 19700152c815SPeter Collingbourne auto &ResByArg = I->second; 19710152c815SPeter Collingbourne // FIXME: We should figure out what to do about the "function name" argument 19720152c815SPeter Collingbourne // to the apply* functions, as the function names are unavailable during the 19730152c815SPeter Collingbourne // importing phase. For now we just pass the empty string. This does not 19740152c815SPeter Collingbourne // impact correctness because the function names are just used for remarks. 19750152c815SPeter Collingbourne switch (ResByArg.TheKind) { 19760152c815SPeter Collingbourne case WholeProgramDevirtResolution::ByArg::UniformRetVal: 19770152c815SPeter Collingbourne applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info); 19780152c815SPeter Collingbourne break; 197959675ba0SPeter Collingbourne case WholeProgramDevirtResolution::ByArg::UniqueRetVal: { 198059675ba0SPeter Collingbourne Constant *UniqueMemberAddr = 198159675ba0SPeter Collingbourne importGlobal(Slot, CSByConstantArg.first, "unique_member"); 198259675ba0SPeter Collingbourne applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info, 198359675ba0SPeter Collingbourne UniqueMemberAddr); 198459675ba0SPeter Collingbourne break; 198559675ba0SPeter Collingbourne } 198614dcf02fSPeter Collingbourne case WholeProgramDevirtResolution::ByArg::VirtualConstProp: { 1987b15a35e6SPeter Collingbourne Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte", 1988b15a35e6SPeter Collingbourne Int32Ty, ResByArg.Byte); 1989b15a35e6SPeter Collingbourne Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty, 1990b15a35e6SPeter Collingbourne ResByArg.Bit); 199114dcf02fSPeter Collingbourne applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit); 19920e6694d1SAdrian Prantl break; 199314dcf02fSPeter Collingbourne } 19940152c815SPeter Collingbourne default: 19950152c815SPeter Collingbourne break; 19960152c815SPeter Collingbourne } 19970152c815SPeter Collingbourne } 19982974856aSPeter Collingbourne 19992974856aSPeter Collingbourne if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) { 200013680223SJames Y Knight // The type of the function is irrelevant, because it's bitcast at calls 200113680223SJames Y Knight // anyhow. 200213680223SJames Y Knight Constant *JT = cast<Constant>( 200313680223SJames Y Knight M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"), 200413680223SJames Y Knight Type::getVoidTy(M.getContext())) 200513680223SJames Y Knight .getCallee()); 20062974856aSPeter Collingbourne bool IsExported = false; 20072974856aSPeter Collingbourne applyICallBranchFunnel(SlotInfo, JT, IsExported); 20082974856aSPeter Collingbourne assert(!IsExported); 20092974856aSPeter Collingbourne } 20106d284fabSPeter Collingbourne } 20116d284fabSPeter Collingbourne 20126d284fabSPeter Collingbourne void DevirtModule::removeRedundantTypeTests() { 20136d284fabSPeter Collingbourne auto True = ConstantInt::getTrue(M.getContext()); 20146d284fabSPeter Collingbourne for (auto &&U : NumUnsafeUsesForTypeTest) { 20156d284fabSPeter Collingbourne if (U.second == 0) { 20166d284fabSPeter Collingbourne U.first->replaceAllUsesWith(True); 20176d284fabSPeter Collingbourne U.first->eraseFromParent(); 20186d284fabSPeter Collingbourne } 20196d284fabSPeter Collingbourne } 20206d284fabSPeter Collingbourne } 20216d284fabSPeter Collingbourne 20220312f614SPeter Collingbourne bool DevirtModule::run() { 2023d0b1f30bSTeresa Johnson // If only some of the modules were split, we cannot correctly perform 2024d0b1f30bSTeresa Johnson // this transformation. We already checked for the presense of type tests 2025d0b1f30bSTeresa Johnson // with partially split modules during the thin link, and would have emitted 2026d0b1f30bSTeresa Johnson // an error if any were found, so here we can simply return. 2027d0b1f30bSTeresa Johnson if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) || 2028d0b1f30bSTeresa Johnson (ImportSummary && ImportSummary->partiallySplitLTOUnits())) 2029d0b1f30bSTeresa Johnson return false; 2030d0b1f30bSTeresa Johnson 20310312f614SPeter Collingbourne Function *TypeTestFunc = 20320312f614SPeter Collingbourne M.getFunction(Intrinsic::getName(Intrinsic::type_test)); 20330312f614SPeter Collingbourne Function *TypeCheckedLoadFunc = 20340312f614SPeter Collingbourne M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load)); 20350312f614SPeter Collingbourne Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume)); 20360312f614SPeter Collingbourne 2037b406baaeSPeter Collingbourne // Normally if there are no users of the devirtualization intrinsics in the 2038b406baaeSPeter Collingbourne // module, this pass has nothing to do. But if we are exporting, we also need 2039b406baaeSPeter Collingbourne // to handle any users that appear only in the function summaries. 2040f7691d8bSPeter Collingbourne if (!ExportSummary && 2041b406baaeSPeter Collingbourne (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc || 20420312f614SPeter Collingbourne AssumeFunc->use_empty()) && 20430312f614SPeter Collingbourne (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty())) 20440312f614SPeter Collingbourne return false; 20450312f614SPeter Collingbourne 20466014c46cSTeresa Johnson // Rebuild type metadata into a map for easy lookup. 20476014c46cSTeresa Johnson std::vector<VTableBits> Bits; 20486014c46cSTeresa Johnson DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap; 20496014c46cSTeresa Johnson buildTypeIdentifierMap(Bits, TypeIdMap); 20506014c46cSTeresa Johnson 20510312f614SPeter Collingbourne if (TypeTestFunc && AssumeFunc) 20526014c46cSTeresa Johnson scanTypeTestUsers(TypeTestFunc, TypeIdMap); 20530312f614SPeter Collingbourne 20540312f614SPeter Collingbourne if (TypeCheckedLoadFunc) 20550312f614SPeter Collingbourne scanTypeCheckedLoadUsers(TypeCheckedLoadFunc); 2056df49d1bbSPeter Collingbourne 2057f7691d8bSPeter Collingbourne if (ImportSummary) { 20586d284fabSPeter Collingbourne for (auto &S : CallSlots) 20596d284fabSPeter Collingbourne importResolution(S.first, S.second); 20606d284fabSPeter Collingbourne 20616d284fabSPeter Collingbourne removeRedundantTypeTests(); 20626d284fabSPeter Collingbourne 20632f63d549STeresa Johnson // We have lowered or deleted the type instrinsics, so we will no 20642f63d549STeresa Johnson // longer have enough information to reason about the liveness of virtual 20652f63d549STeresa Johnson // function pointers in GlobalDCE. 20662f63d549STeresa Johnson for (GlobalVariable &GV : M.globals()) 20672f63d549STeresa Johnson GV.eraseMetadata(LLVMContext::MD_vcall_visibility); 20682f63d549STeresa Johnson 20696d284fabSPeter Collingbourne // The rest of the code is only necessary when exporting or during regular 20706d284fabSPeter Collingbourne // LTO, so we are done. 20716d284fabSPeter Collingbourne return true; 20726d284fabSPeter Collingbourne } 20736d284fabSPeter Collingbourne 20747efd7506SPeter Collingbourne if (TypeIdMap.empty()) 2075df49d1bbSPeter Collingbourne return true; 2076df49d1bbSPeter Collingbourne 2077b406baaeSPeter Collingbourne // Collect information from summary about which calls to try to devirtualize. 2078f7691d8bSPeter Collingbourne if (ExportSummary) { 2079b406baaeSPeter Collingbourne DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID; 2080b406baaeSPeter Collingbourne for (auto &P : TypeIdMap) { 2081b406baaeSPeter Collingbourne if (auto *TypeId = dyn_cast<MDString>(P.first)) 2082b406baaeSPeter Collingbourne MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back( 2083b406baaeSPeter Collingbourne TypeId); 2084b406baaeSPeter Collingbourne } 2085b406baaeSPeter Collingbourne 2086f7691d8bSPeter Collingbourne for (auto &P : *ExportSummary) { 20879667b91bSPeter Collingbourne for (auto &S : P.second.SummaryList) { 2088b406baaeSPeter Collingbourne auto *FS = dyn_cast<FunctionSummary>(S.get()); 2089b406baaeSPeter Collingbourne if (!FS) 2090b406baaeSPeter Collingbourne continue; 2091b406baaeSPeter Collingbourne // FIXME: Only add live functions. 20925d8aea10SGeorge Rimar for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { 20935d8aea10SGeorge Rimar for (Metadata *MD : MetadataByGUID[VF.GUID]) { 2094943afb57SEugene Leviant CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS); 20955d8aea10SGeorge Rimar } 20965d8aea10SGeorge Rimar } 20975d8aea10SGeorge Rimar for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { 20985d8aea10SGeorge Rimar for (Metadata *MD : MetadataByGUID[VF.GUID]) { 20992974856aSPeter Collingbourne CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS); 21005d8aea10SGeorge Rimar } 21015d8aea10SGeorge Rimar } 2102b406baaeSPeter Collingbourne for (const FunctionSummary::ConstVCall &VC : 21035d8aea10SGeorge Rimar FS->type_test_assume_const_vcalls()) { 21045d8aea10SGeorge Rimar for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { 21052325bb34SPeter Collingbourne CallSlots[{MD, VC.VFunc.Offset}] 21065d8aea10SGeorge Rimar .ConstCSInfo[VC.Args] 2107943afb57SEugene Leviant .addSummaryTypeTestAssumeUser(FS); 21085d8aea10SGeorge Rimar } 21095d8aea10SGeorge Rimar } 21102325bb34SPeter Collingbourne for (const FunctionSummary::ConstVCall &VC : 21115d8aea10SGeorge Rimar FS->type_checked_load_const_vcalls()) { 21125d8aea10SGeorge Rimar for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { 2113b406baaeSPeter Collingbourne CallSlots[{MD, VC.VFunc.Offset}] 2114b406baaeSPeter Collingbourne .ConstCSInfo[VC.Args] 21152974856aSPeter Collingbourne .addSummaryTypeCheckedLoadUser(FS); 2116b406baaeSPeter Collingbourne } 2117b406baaeSPeter Collingbourne } 2118b406baaeSPeter Collingbourne } 21195d8aea10SGeorge Rimar } 21205d8aea10SGeorge Rimar } 2121b406baaeSPeter Collingbourne 21227efd7506SPeter Collingbourne // For each (type, offset) pair: 2123df49d1bbSPeter Collingbourne bool DidVirtualConstProp = false; 2124f3403fd2SIvan Krasin std::map<std::string, Function*> DevirtTargets; 2125df49d1bbSPeter Collingbourne for (auto &S : CallSlots) { 21267efd7506SPeter Collingbourne // Search each of the members of the type identifier for the virtual 21277efd7506SPeter Collingbourne // function implementation at offset S.first.ByteOffset, and add to 21287efd7506SPeter Collingbourne // TargetsForSlot. 2129df49d1bbSPeter Collingbourne std::vector<VirtualCallTarget> TargetsForSlot; 21302325bb34SPeter Collingbourne WholeProgramDevirtResolution *Res = nullptr; 21316014c46cSTeresa Johnson const std::set<TypeMemberInfo> &TypeMemberInfos = TypeIdMap[S.first.TypeID]; 21326014c46cSTeresa Johnson if (ExportSummary && isa<MDString>(S.first.TypeID) && 21336014c46cSTeresa Johnson TypeMemberInfos.size()) 21346014c46cSTeresa Johnson // For any type id used on a global's type metadata, create the type id 21356014c46cSTeresa Johnson // summary resolution regardless of whether we can devirtualize, so that 21366014c46cSTeresa Johnson // lower type tests knows the type id is not Unsat. If it was not used on 21376014c46cSTeresa Johnson // a global's type metadata, the TypeIdMap entry set will be empty, and 21386014c46cSTeresa Johnson // we don't want to create an entry (with the default Unknown type 21396014c46cSTeresa Johnson // resolution), which can prevent detection of the Unsat. 2140f7691d8bSPeter Collingbourne Res = &ExportSummary 21419a3f9797SPeter Collingbourne ->getOrInsertTypeIdSummary( 21429a3f9797SPeter Collingbourne cast<MDString>(S.first.TypeID)->getString()) 21432325bb34SPeter Collingbourne .WPDRes[S.first.ByteOffset]; 21446014c46cSTeresa Johnson if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos, 21456014c46cSTeresa Johnson S.first.ByteOffset)) { 21462325bb34SPeter Collingbourne 2147943afb57SEugene Leviant if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) { 21482974856aSPeter Collingbourne DidVirtualConstProp |= 21492974856aSPeter Collingbourne tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first); 21502974856aSPeter Collingbourne 21512974856aSPeter Collingbourne tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first); 21522974856aSPeter Collingbourne } 2153f3403fd2SIvan Krasin 2154f3403fd2SIvan Krasin // Collect functions devirtualized at least for one call site for stats. 2155f3403fd2SIvan Krasin if (RemarksEnabled) 2156f3403fd2SIvan Krasin for (const auto &T : TargetsForSlot) 2157f3403fd2SIvan Krasin if (T.WasDevirt) 2158adcd0268SBenjamin Kramer DevirtTargets[std::string(T.Fn->getName())] = T.Fn; 2159b05e06e4SIvan Krasin } 2160df49d1bbSPeter Collingbourne 2161b406baaeSPeter Collingbourne // CFI-specific: if we are exporting and any llvm.type.checked.load 2162b406baaeSPeter Collingbourne // intrinsics were *not* devirtualized, we need to add the resulting 2163b406baaeSPeter Collingbourne // llvm.type.test intrinsics to the function summaries so that the 2164b406baaeSPeter Collingbourne // LowerTypeTests pass will export them. 2165f7691d8bSPeter Collingbourne if (ExportSummary && isa<MDString>(S.first.TypeID)) { 2166b406baaeSPeter Collingbourne auto GUID = 2167b406baaeSPeter Collingbourne GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString()); 2168b406baaeSPeter Collingbourne for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers) 2169b406baaeSPeter Collingbourne FS->addTypeTest(GUID); 2170b406baaeSPeter Collingbourne for (auto &CCS : S.second.ConstCSInfo) 2171b406baaeSPeter Collingbourne for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers) 2172b406baaeSPeter Collingbourne FS->addTypeTest(GUID); 2173b406baaeSPeter Collingbourne } 2174b406baaeSPeter Collingbourne } 2175b406baaeSPeter Collingbourne 2176f3403fd2SIvan Krasin if (RemarksEnabled) { 2177f3403fd2SIvan Krasin // Generate remarks for each devirtualized function. 2178f3403fd2SIvan Krasin for (const auto &DT : DevirtTargets) { 2179f3403fd2SIvan Krasin Function *F = DT.second; 2180e963c89dSSam Elliott 2181e963c89dSSam Elliott using namespace ore; 21829110cb45SPeter Collingbourne OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F) 21839110cb45SPeter Collingbourne << "devirtualized " 2184d2df54e6STeresa Johnson << NV("FunctionName", DT.first)); 2185b05e06e4SIvan Krasin } 2186df49d1bbSPeter Collingbourne } 2187df49d1bbSPeter Collingbourne 21886d284fabSPeter Collingbourne removeRedundantTypeTests(); 21890312f614SPeter Collingbourne 2190df49d1bbSPeter Collingbourne // Rebuild each global we touched as part of virtual constant propagation to 2191df49d1bbSPeter Collingbourne // include the before and after bytes. 2192df49d1bbSPeter Collingbourne if (DidVirtualConstProp) 2193df49d1bbSPeter Collingbourne for (VTableBits &B : Bits) 2194df49d1bbSPeter Collingbourne rebuildGlobal(B); 2195df49d1bbSPeter Collingbourne 21962f63d549STeresa Johnson // We have lowered or deleted the type instrinsics, so we will no 21973b598b9cSOliver Stannard // longer have enough information to reason about the liveness of virtual 21983b598b9cSOliver Stannard // function pointers in GlobalDCE. 21993b598b9cSOliver Stannard for (GlobalVariable &GV : M.globals()) 22003b598b9cSOliver Stannard GV.eraseMetadata(LLVMContext::MD_vcall_visibility); 22013b598b9cSOliver Stannard 2202df49d1bbSPeter Collingbourne return true; 2203df49d1bbSPeter Collingbourne } 2204d2df54e6STeresa Johnson 2205d2df54e6STeresa Johnson void DevirtIndex::run() { 2206d2df54e6STeresa Johnson if (ExportSummary.typeIdCompatibleVtableMap().empty()) 2207d2df54e6STeresa Johnson return; 2208d2df54e6STeresa Johnson 2209d2df54e6STeresa Johnson DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID; 2210d2df54e6STeresa Johnson for (auto &P : ExportSummary.typeIdCompatibleVtableMap()) { 2211d2df54e6STeresa Johnson NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first); 2212d2df54e6STeresa Johnson } 2213d2df54e6STeresa Johnson 2214d2df54e6STeresa Johnson // Collect information from summary about which calls to try to devirtualize. 2215d2df54e6STeresa Johnson for (auto &P : ExportSummary) { 2216d2df54e6STeresa Johnson for (auto &S : P.second.SummaryList) { 2217d2df54e6STeresa Johnson auto *FS = dyn_cast<FunctionSummary>(S.get()); 2218d2df54e6STeresa Johnson if (!FS) 2219d2df54e6STeresa Johnson continue; 2220d2df54e6STeresa Johnson // FIXME: Only add live functions. 2221d2df54e6STeresa Johnson for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { 2222d2df54e6STeresa Johnson for (StringRef Name : NameByGUID[VF.GUID]) { 2223d2df54e6STeresa Johnson CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS); 2224d2df54e6STeresa Johnson } 2225d2df54e6STeresa Johnson } 2226d2df54e6STeresa Johnson for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { 2227d2df54e6STeresa Johnson for (StringRef Name : NameByGUID[VF.GUID]) { 2228d2df54e6STeresa Johnson CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS); 2229d2df54e6STeresa Johnson } 2230d2df54e6STeresa Johnson } 2231d2df54e6STeresa Johnson for (const FunctionSummary::ConstVCall &VC : 2232d2df54e6STeresa Johnson FS->type_test_assume_const_vcalls()) { 2233d2df54e6STeresa Johnson for (StringRef Name : NameByGUID[VC.VFunc.GUID]) { 2234d2df54e6STeresa Johnson CallSlots[{Name, VC.VFunc.Offset}] 2235d2df54e6STeresa Johnson .ConstCSInfo[VC.Args] 2236d2df54e6STeresa Johnson .addSummaryTypeTestAssumeUser(FS); 2237d2df54e6STeresa Johnson } 2238d2df54e6STeresa Johnson } 2239d2df54e6STeresa Johnson for (const FunctionSummary::ConstVCall &VC : 2240d2df54e6STeresa Johnson FS->type_checked_load_const_vcalls()) { 2241d2df54e6STeresa Johnson for (StringRef Name : NameByGUID[VC.VFunc.GUID]) { 2242d2df54e6STeresa Johnson CallSlots[{Name, VC.VFunc.Offset}] 2243d2df54e6STeresa Johnson .ConstCSInfo[VC.Args] 2244d2df54e6STeresa Johnson .addSummaryTypeCheckedLoadUser(FS); 2245d2df54e6STeresa Johnson } 2246d2df54e6STeresa Johnson } 2247d2df54e6STeresa Johnson } 2248d2df54e6STeresa Johnson } 2249d2df54e6STeresa Johnson 2250d2df54e6STeresa Johnson std::set<ValueInfo> DevirtTargets; 2251d2df54e6STeresa Johnson // For each (type, offset) pair: 2252d2df54e6STeresa Johnson for (auto &S : CallSlots) { 2253d2df54e6STeresa Johnson // Search each of the members of the type identifier for the virtual 2254d2df54e6STeresa Johnson // function implementation at offset S.first.ByteOffset, and add to 2255d2df54e6STeresa Johnson // TargetsForSlot. 2256d2df54e6STeresa Johnson std::vector<ValueInfo> TargetsForSlot; 2257d2df54e6STeresa Johnson auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID); 2258d2df54e6STeresa Johnson assert(TidSummary); 22596014c46cSTeresa Johnson // Create the type id summary resolution regardlness of whether we can 22606014c46cSTeresa Johnson // devirtualize, so that lower type tests knows the type id is used on 22616014c46cSTeresa Johnson // a global and not Unsat. 2262d2df54e6STeresa Johnson WholeProgramDevirtResolution *Res = 2263d2df54e6STeresa Johnson &ExportSummary.getOrInsertTypeIdSummary(S.first.TypeID) 2264d2df54e6STeresa Johnson .WPDRes[S.first.ByteOffset]; 22656014c46cSTeresa Johnson if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary, 22666014c46cSTeresa Johnson S.first.ByteOffset)) { 2267d2df54e6STeresa Johnson 2268d2df54e6STeresa Johnson if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res, 2269d2df54e6STeresa Johnson DevirtTargets)) 2270d2df54e6STeresa Johnson continue; 2271d2df54e6STeresa Johnson } 2272d2df54e6STeresa Johnson } 2273d2df54e6STeresa Johnson 2274d2df54e6STeresa Johnson // Optionally have the thin link print message for each devirtualized 2275d2df54e6STeresa Johnson // function. 2276d2df54e6STeresa Johnson if (PrintSummaryDevirt) 2277d2df54e6STeresa Johnson for (const auto &DT : DevirtTargets) 2278d2df54e6STeresa Johnson errs() << "Devirtualized call to " << DT << "\n"; 2279d2df54e6STeresa Johnson } 2280