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