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