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