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