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