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