1 //===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements whole program optimization of virtual calls in cases
11 // where we know (via !type metadata) that the list of callees is fixed. This
12 // includes the following:
13 // - Single implementation devirtualization: if a virtual call has a single
14 //   possible callee, replace all calls with a direct call to that callee.
15 // - Virtual constant propagation: if the virtual function's return type is an
16 //   integer <=64 bits and all possible callees are readnone, for each class and
17 //   each list of constant arguments: evaluate the function, store the return
18 //   value alongside the virtual table, and rewrite each virtual call as a load
19 //   from the virtual table.
20 // - Uniform return value optimization: if the conditions for virtual constant
21 //   propagation hold and each function returns the same constant value, replace
22 //   each virtual call with that constant.
23 // - Unique return value optimization for i1 return values: if the conditions
24 //   for virtual constant propagation hold and a single vtable's function
25 //   returns 0, or a single vtable's function returns 1, replace each virtual
26 //   call with a comparison of the vptr against that vtable's address.
27 //
28 //===----------------------------------------------------------------------===//
29 
30 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/MapVector.h"
34 #include "llvm/Analysis/TypeMetadataUtils.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/IRBuilder.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Transforms/IPO.h"
45 #include "llvm/Transforms/Utils/Evaluator.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 
48 #include <set>
49 
50 using namespace llvm;
51 using namespace wholeprogramdevirt;
52 
53 #define DEBUG_TYPE "wholeprogramdevirt"
54 
55 // Find the minimum offset that we may store a value of size Size bits at. If
56 // IsAfter is set, look for an offset before the object, otherwise look for an
57 // offset after the object.
58 uint64_t
59 wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
60                                      bool IsAfter, uint64_t Size) {
61   // Find a minimum offset taking into account only vtable sizes.
62   uint64_t MinByte = 0;
63   for (const VirtualCallTarget &Target : Targets) {
64     if (IsAfter)
65       MinByte = std::max(MinByte, Target.minAfterBytes());
66     else
67       MinByte = std::max(MinByte, Target.minBeforeBytes());
68   }
69 
70   // Build a vector of arrays of bytes covering, for each target, a slice of the
71   // used region (see AccumBitVector::BytesUsed in
72   // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
73   // this aligns the used regions to start at MinByte.
74   //
75   // In this example, A, B and C are vtables, # is a byte already allocated for
76   // a virtual function pointer, AAAA... (etc.) are the used regions for the
77   // vtables and Offset(X) is the value computed for the Offset variable below
78   // for X.
79   //
80   //                    Offset(A)
81   //                    |       |
82   //                            |MinByte
83   // A: ################AAAAAAAA|AAAAAAAA
84   // B: ########BBBBBBBBBBBBBBBB|BBBB
85   // C: ########################|CCCCCCCCCCCCCCCC
86   //            |   Offset(B)   |
87   //
88   // This code produces the slices of A, B and C that appear after the divider
89   // at MinByte.
90   std::vector<ArrayRef<uint8_t>> Used;
91   for (const VirtualCallTarget &Target : Targets) {
92     ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
93                                        : Target.TM->Bits->Before.BytesUsed;
94     uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
95                               : MinByte - Target.minBeforeBytes();
96 
97     // Disregard used regions that are smaller than Offset. These are
98     // effectively all-free regions that do not need to be checked.
99     if (VTUsed.size() > Offset)
100       Used.push_back(VTUsed.slice(Offset));
101   }
102 
103   if (Size == 1) {
104     // Find a free bit in each member of Used.
105     for (unsigned I = 0;; ++I) {
106       uint8_t BitsUsed = 0;
107       for (auto &&B : Used)
108         if (I < B.size())
109           BitsUsed |= B[I];
110       if (BitsUsed != 0xff)
111         return (MinByte + I) * 8 +
112                countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
113     }
114   } else {
115     // Find a free (Size/8) byte region in each member of Used.
116     // FIXME: see if alignment helps.
117     for (unsigned I = 0;; ++I) {
118       for (auto &&B : Used) {
119         unsigned Byte = 0;
120         while ((I + Byte) < B.size() && Byte < (Size / 8)) {
121           if (B[I + Byte])
122             goto NextI;
123           ++Byte;
124         }
125       }
126       return (MinByte + I) * 8;
127     NextI:;
128     }
129   }
130 }
131 
132 void wholeprogramdevirt::setBeforeReturnValues(
133     MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
134     unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
135   if (BitWidth == 1)
136     OffsetByte = -(AllocBefore / 8 + 1);
137   else
138     OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
139   OffsetBit = AllocBefore % 8;
140 
141   for (VirtualCallTarget &Target : Targets) {
142     if (BitWidth == 1)
143       Target.setBeforeBit(AllocBefore);
144     else
145       Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
146   }
147 }
148 
149 void wholeprogramdevirt::setAfterReturnValues(
150     MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
151     unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
152   if (BitWidth == 1)
153     OffsetByte = AllocAfter / 8;
154   else
155     OffsetByte = (AllocAfter + 7) / 8;
156   OffsetBit = AllocAfter % 8;
157 
158   for (VirtualCallTarget &Target : Targets) {
159     if (BitWidth == 1)
160       Target.setAfterBit(AllocAfter);
161     else
162       Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
163   }
164 }
165 
166 VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
167     : Fn(Fn), TM(TM),
168       IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()) {}
169 
170 namespace {
171 
172 // A slot in a set of virtual tables. The TypeID identifies the set of virtual
173 // tables, and the ByteOffset is the offset in bytes from the address point to
174 // the virtual function pointer.
175 struct VTableSlot {
176   Metadata *TypeID;
177   uint64_t ByteOffset;
178 };
179 
180 }
181 
182 namespace llvm {
183 
184 template <> struct DenseMapInfo<VTableSlot> {
185   static VTableSlot getEmptyKey() {
186     return {DenseMapInfo<Metadata *>::getEmptyKey(),
187             DenseMapInfo<uint64_t>::getEmptyKey()};
188   }
189   static VTableSlot getTombstoneKey() {
190     return {DenseMapInfo<Metadata *>::getTombstoneKey(),
191             DenseMapInfo<uint64_t>::getTombstoneKey()};
192   }
193   static unsigned getHashValue(const VTableSlot &I) {
194     return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
195            DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
196   }
197   static bool isEqual(const VTableSlot &LHS,
198                       const VTableSlot &RHS) {
199     return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
200   }
201 };
202 
203 }
204 
205 namespace {
206 
207 // A virtual call site. VTable is the loaded virtual table pointer, and CS is
208 // the indirect virtual call.
209 struct VirtualCallSite {
210   Value *VTable;
211   CallSite CS;
212 
213   // If non-null, this field points to the associated unsafe use count stored in
214   // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
215   // of that field for details.
216   unsigned *NumUnsafeUses;
217 
218   void replaceAndErase(Value *New) {
219     CS->replaceAllUsesWith(New);
220     if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
221       BranchInst::Create(II->getNormalDest(), CS.getInstruction());
222       II->getUnwindDest()->removePredecessor(II->getParent());
223     }
224     CS->eraseFromParent();
225     // This use is no longer unsafe.
226     if (NumUnsafeUses)
227       --*NumUnsafeUses;
228   }
229 };
230 
231 struct DevirtModule {
232   Module &M;
233   IntegerType *Int8Ty;
234   PointerType *Int8PtrTy;
235   IntegerType *Int32Ty;
236 
237   MapVector<VTableSlot, std::vector<VirtualCallSite>> CallSlots;
238 
239   // This map keeps track of the number of "unsafe" uses of a loaded function
240   // pointer. The key is the associated llvm.type.test intrinsic call generated
241   // by this pass. An unsafe use is one that calls the loaded function pointer
242   // directly. Every time we eliminate an unsafe use (for example, by
243   // devirtualizing it or by applying virtual constant propagation), we
244   // decrement the value stored in this map. If a value reaches zero, we can
245   // eliminate the type check by RAUWing the associated llvm.type.test call with
246   // true.
247   std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
248 
249   DevirtModule(Module &M)
250       : M(M), Int8Ty(Type::getInt8Ty(M.getContext())),
251         Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
252         Int32Ty(Type::getInt32Ty(M.getContext())) {}
253 
254   void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
255   void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
256 
257   void buildTypeIdentifierMap(
258       std::vector<VTableBits> &Bits,
259       DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
260   bool
261   tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
262                             const std::set<TypeMemberInfo> &TypeMemberInfos,
263                             uint64_t ByteOffset);
264   bool trySingleImplDevirt(ArrayRef<VirtualCallTarget> TargetsForSlot,
265                            MutableArrayRef<VirtualCallSite> CallSites);
266   bool tryEvaluateFunctionsWithArgs(
267       MutableArrayRef<VirtualCallTarget> TargetsForSlot,
268       ArrayRef<ConstantInt *> Args);
269   bool tryUniformRetValOpt(IntegerType *RetType,
270                            ArrayRef<VirtualCallTarget> TargetsForSlot,
271                            MutableArrayRef<VirtualCallSite> CallSites);
272   bool tryUniqueRetValOpt(unsigned BitWidth,
273                           ArrayRef<VirtualCallTarget> TargetsForSlot,
274                           MutableArrayRef<VirtualCallSite> CallSites);
275   bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
276                            ArrayRef<VirtualCallSite> CallSites);
277 
278   void rebuildGlobal(VTableBits &B);
279 
280   bool run();
281 };
282 
283 struct WholeProgramDevirt : public ModulePass {
284   static char ID;
285   WholeProgramDevirt() : ModulePass(ID) {
286     initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
287   }
288   bool runOnModule(Module &M) {
289     if (skipModule(M))
290       return false;
291 
292     return DevirtModule(M).run();
293   }
294 };
295 
296 } // anonymous namespace
297 
298 INITIALIZE_PASS(WholeProgramDevirt, "wholeprogramdevirt",
299                 "Whole program devirtualization", false, false)
300 char WholeProgramDevirt::ID = 0;
301 
302 ModulePass *llvm::createWholeProgramDevirtPass() {
303   return new WholeProgramDevirt;
304 }
305 
306 PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
307                                               ModuleAnalysisManager &) {
308   if (!DevirtModule(M).run())
309     return PreservedAnalyses::all();
310   return PreservedAnalyses::none();
311 }
312 
313 void DevirtModule::buildTypeIdentifierMap(
314     std::vector<VTableBits> &Bits,
315     DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
316   DenseMap<GlobalVariable *, VTableBits *> GVToBits;
317   Bits.reserve(M.getGlobalList().size());
318   SmallVector<MDNode *, 2> Types;
319   for (GlobalVariable &GV : M.globals()) {
320     Types.clear();
321     GV.getMetadata(LLVMContext::MD_type, Types);
322     if (Types.empty())
323       continue;
324 
325     VTableBits *&BitsPtr = GVToBits[&GV];
326     if (!BitsPtr) {
327       Bits.emplace_back();
328       Bits.back().GV = &GV;
329       Bits.back().ObjectSize =
330           M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
331       BitsPtr = &Bits.back();
332     }
333 
334     for (MDNode *Type : Types) {
335       auto TypeID = Type->getOperand(1).get();
336 
337       uint64_t Offset =
338           cast<ConstantInt>(
339               cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
340               ->getZExtValue();
341 
342       TypeIdMap[TypeID].insert({BitsPtr, Offset});
343     }
344   }
345 }
346 
347 bool DevirtModule::tryFindVirtualCallTargets(
348     std::vector<VirtualCallTarget> &TargetsForSlot,
349     const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
350   for (const TypeMemberInfo &TM : TypeMemberInfos) {
351     if (!TM.Bits->GV->isConstant())
352       return false;
353 
354     auto Init = dyn_cast<ConstantArray>(TM.Bits->GV->getInitializer());
355     if (!Init)
356       return false;
357     ArrayType *VTableTy = Init->getType();
358 
359     uint64_t ElemSize =
360         M.getDataLayout().getTypeAllocSize(VTableTy->getElementType());
361     uint64_t GlobalSlotOffset = TM.Offset + ByteOffset;
362     if (GlobalSlotOffset % ElemSize != 0)
363       return false;
364 
365     unsigned Op = GlobalSlotOffset / ElemSize;
366     if (Op >= Init->getNumOperands())
367       return false;
368 
369     auto Fn = dyn_cast<Function>(Init->getOperand(Op)->stripPointerCasts());
370     if (!Fn)
371       return false;
372 
373     // We can disregard __cxa_pure_virtual as a possible call target, as
374     // calls to pure virtuals are UB.
375     if (Fn->getName() == "__cxa_pure_virtual")
376       continue;
377 
378     TargetsForSlot.push_back({Fn, &TM});
379   }
380 
381   // Give up if we couldn't find any targets.
382   return !TargetsForSlot.empty();
383 }
384 
385 bool DevirtModule::trySingleImplDevirt(
386     ArrayRef<VirtualCallTarget> TargetsForSlot,
387     MutableArrayRef<VirtualCallSite> CallSites) {
388   // See if the program contains a single implementation of this virtual
389   // function.
390   Function *TheFn = TargetsForSlot[0].Fn;
391   for (auto &&Target : TargetsForSlot)
392     if (TheFn != Target.Fn)
393       return false;
394 
395   // If so, update each call site to call that implementation directly.
396   for (auto &&VCallSite : CallSites) {
397     VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
398         TheFn, VCallSite.CS.getCalledValue()->getType()));
399     // This use is no longer unsafe.
400     if (VCallSite.NumUnsafeUses)
401       --*VCallSite.NumUnsafeUses;
402   }
403   return true;
404 }
405 
406 bool DevirtModule::tryEvaluateFunctionsWithArgs(
407     MutableArrayRef<VirtualCallTarget> TargetsForSlot,
408     ArrayRef<ConstantInt *> Args) {
409   // Evaluate each function and store the result in each target's RetVal
410   // field.
411   for (VirtualCallTarget &Target : TargetsForSlot) {
412     if (Target.Fn->arg_size() != Args.size() + 1)
413       return false;
414     for (unsigned I = 0; I != Args.size(); ++I)
415       if (Target.Fn->getFunctionType()->getParamType(I + 1) !=
416           Args[I]->getType())
417         return false;
418 
419     Evaluator Eval(M.getDataLayout(), nullptr);
420     SmallVector<Constant *, 2> EvalArgs;
421     EvalArgs.push_back(
422         Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
423     EvalArgs.insert(EvalArgs.end(), Args.begin(), Args.end());
424     Constant *RetVal;
425     if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
426         !isa<ConstantInt>(RetVal))
427       return false;
428     Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
429   }
430   return true;
431 }
432 
433 bool DevirtModule::tryUniformRetValOpt(
434     IntegerType *RetType, ArrayRef<VirtualCallTarget> TargetsForSlot,
435     MutableArrayRef<VirtualCallSite> CallSites) {
436   // Uniform return value optimization. If all functions return the same
437   // constant, replace all calls with that constant.
438   uint64_t TheRetVal = TargetsForSlot[0].RetVal;
439   for (const VirtualCallTarget &Target : TargetsForSlot)
440     if (Target.RetVal != TheRetVal)
441       return false;
442 
443   auto TheRetValConst = ConstantInt::get(RetType, TheRetVal);
444   for (auto Call : CallSites)
445     Call.replaceAndErase(TheRetValConst);
446   return true;
447 }
448 
449 bool DevirtModule::tryUniqueRetValOpt(
450     unsigned BitWidth, ArrayRef<VirtualCallTarget> TargetsForSlot,
451     MutableArrayRef<VirtualCallSite> CallSites) {
452   // IsOne controls whether we look for a 0 or a 1.
453   auto tryUniqueRetValOptFor = [&](bool IsOne) {
454     const TypeMemberInfo *UniqueMember = 0;
455     for (const VirtualCallTarget &Target : TargetsForSlot) {
456       if (Target.RetVal == (IsOne ? 1 : 0)) {
457         if (UniqueMember)
458           return false;
459         UniqueMember = Target.TM;
460       }
461     }
462 
463     // We should have found a unique member or bailed out by now. We already
464     // checked for a uniform return value in tryUniformRetValOpt.
465     assert(UniqueMember);
466 
467     // Replace each call with the comparison.
468     for (auto &&Call : CallSites) {
469       IRBuilder<> B(Call.CS.getInstruction());
470       Value *OneAddr = B.CreateBitCast(UniqueMember->Bits->GV, Int8PtrTy);
471       OneAddr = B.CreateConstGEP1_64(OneAddr, UniqueMember->Offset);
472       Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
473                                 Call.VTable, OneAddr);
474       Call.replaceAndErase(Cmp);
475     }
476     return true;
477   };
478 
479   if (BitWidth == 1) {
480     if (tryUniqueRetValOptFor(true))
481       return true;
482     if (tryUniqueRetValOptFor(false))
483       return true;
484   }
485   return false;
486 }
487 
488 bool DevirtModule::tryVirtualConstProp(
489     MutableArrayRef<VirtualCallTarget> TargetsForSlot,
490     ArrayRef<VirtualCallSite> CallSites) {
491   // This only works if the function returns an integer.
492   auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
493   if (!RetType)
494     return false;
495   unsigned BitWidth = RetType->getBitWidth();
496   if (BitWidth > 64)
497     return false;
498 
499   // Make sure that each function does not access memory, takes at least one
500   // argument, does not use its first argument (which we assume is 'this'),
501   // and has the same return type.
502   for (VirtualCallTarget &Target : TargetsForSlot) {
503     if (!Target.Fn->doesNotAccessMemory() || Target.Fn->arg_empty() ||
504         !Target.Fn->arg_begin()->use_empty() ||
505         Target.Fn->getReturnType() != RetType)
506       return false;
507   }
508 
509   // Group call sites by the list of constant arguments they pass.
510   // The comparator ensures deterministic ordering.
511   struct ByAPIntValue {
512     bool operator()(const std::vector<ConstantInt *> &A,
513                     const std::vector<ConstantInt *> &B) const {
514       return std::lexicographical_compare(
515           A.begin(), A.end(), B.begin(), B.end(),
516           [](ConstantInt *AI, ConstantInt *BI) {
517             return AI->getValue().ult(BI->getValue());
518           });
519     }
520   };
521   std::map<std::vector<ConstantInt *>, std::vector<VirtualCallSite>,
522            ByAPIntValue>
523       VCallSitesByConstantArg;
524   for (auto &&VCallSite : CallSites) {
525     std::vector<ConstantInt *> Args;
526     if (VCallSite.CS.getType() != RetType)
527       continue;
528     for (auto &&Arg :
529          make_range(VCallSite.CS.arg_begin() + 1, VCallSite.CS.arg_end())) {
530       if (!isa<ConstantInt>(Arg))
531         break;
532       Args.push_back(cast<ConstantInt>(&Arg));
533     }
534     if (Args.size() + 1 != VCallSite.CS.arg_size())
535       continue;
536 
537     VCallSitesByConstantArg[Args].push_back(VCallSite);
538   }
539 
540   for (auto &&CSByConstantArg : VCallSitesByConstantArg) {
541     if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
542       continue;
543 
544     if (tryUniformRetValOpt(RetType, TargetsForSlot, CSByConstantArg.second))
545       continue;
546 
547     if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second))
548       continue;
549 
550     // Find an allocation offset in bits in all vtables associated with the
551     // type.
552     uint64_t AllocBefore =
553         findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
554     uint64_t AllocAfter =
555         findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
556 
557     // Calculate the total amount of padding needed to store a value at both
558     // ends of the object.
559     uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
560     for (auto &&Target : TargetsForSlot) {
561       TotalPaddingBefore += std::max<int64_t>(
562           (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
563       TotalPaddingAfter += std::max<int64_t>(
564           (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
565     }
566 
567     // If the amount of padding is too large, give up.
568     // FIXME: do something smarter here.
569     if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
570       continue;
571 
572     // Calculate the offset to the value as a (possibly negative) byte offset
573     // and (if applicable) a bit offset, and store the values in the targets.
574     int64_t OffsetByte;
575     uint64_t OffsetBit;
576     if (TotalPaddingBefore <= TotalPaddingAfter)
577       setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
578                             OffsetBit);
579     else
580       setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
581                            OffsetBit);
582 
583     // Rewrite each call to a load from OffsetByte/OffsetBit.
584     for (auto Call : CSByConstantArg.second) {
585       IRBuilder<> B(Call.CS.getInstruction());
586       Value *Addr = B.CreateConstGEP1_64(Call.VTable, OffsetByte);
587       if (BitWidth == 1) {
588         Value *Bits = B.CreateLoad(Addr);
589         Value *Bit = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
590         Value *BitsAndBit = B.CreateAnd(Bits, Bit);
591         auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
592         Call.replaceAndErase(IsBitSet);
593       } else {
594         Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
595         Value *Val = B.CreateLoad(RetType, ValAddr);
596         Call.replaceAndErase(Val);
597       }
598     }
599   }
600   return true;
601 }
602 
603 void DevirtModule::rebuildGlobal(VTableBits &B) {
604   if (B.Before.Bytes.empty() && B.After.Bytes.empty())
605     return;
606 
607   // Align each byte array to pointer width.
608   unsigned PointerSize = M.getDataLayout().getPointerSize();
609   B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
610   B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
611 
612   // Before was stored in reverse order; flip it now.
613   for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
614     std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
615 
616   // Build an anonymous global containing the before bytes, followed by the
617   // original initializer, followed by the after bytes.
618   auto NewInit = ConstantStruct::getAnon(
619       {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
620        B.GV->getInitializer(),
621        ConstantDataArray::get(M.getContext(), B.After.Bytes)});
622   auto NewGV =
623       new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
624                          GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
625   NewGV->setSection(B.GV->getSection());
626   NewGV->setComdat(B.GV->getComdat());
627 
628   // Copy the original vtable's metadata to the anonymous global, adjusting
629   // offsets as required.
630   NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
631 
632   // Build an alias named after the original global, pointing at the second
633   // element (the original initializer).
634   auto Alias = GlobalAlias::create(
635       B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
636       ConstantExpr::getGetElementPtr(
637           NewInit->getType(), NewGV,
638           ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
639                                ConstantInt::get(Int32Ty, 1)}),
640       &M);
641   Alias->setVisibility(B.GV->getVisibility());
642   Alias->takeName(B.GV);
643 
644   B.GV->replaceAllUsesWith(Alias);
645   B.GV->eraseFromParent();
646 }
647 
648 void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
649                                      Function *AssumeFunc) {
650   // Find all virtual calls via a virtual table pointer %p under an assumption
651   // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
652   // points to a member of the type identifier %md. Group calls by (type ID,
653   // offset) pair (effectively the identity of the virtual function) and store
654   // to CallSlots.
655   DenseSet<Value *> SeenPtrs;
656   for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
657        I != E;) {
658     auto CI = dyn_cast<CallInst>(I->getUser());
659     ++I;
660     if (!CI)
661       continue;
662 
663     // Search for virtual calls based on %p and add them to DevirtCalls.
664     SmallVector<DevirtCallSite, 1> DevirtCalls;
665     SmallVector<CallInst *, 1> Assumes;
666     findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
667 
668     // If we found any, add them to CallSlots. Only do this if we haven't seen
669     // the vtable pointer before, as it may have been CSE'd with pointers from
670     // other call sites, and we don't want to process call sites multiple times.
671     if (!Assumes.empty()) {
672       Metadata *TypeId =
673           cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
674       Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
675       if (SeenPtrs.insert(Ptr).second) {
676         for (DevirtCallSite Call : DevirtCalls) {
677           CallSlots[{TypeId, Call.Offset}].push_back(
678               {CI->getArgOperand(0), Call.CS, nullptr});
679         }
680       }
681     }
682 
683     // We no longer need the assumes or the type test.
684     for (auto Assume : Assumes)
685       Assume->eraseFromParent();
686     // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
687     // may use the vtable argument later.
688     if (CI->use_empty())
689       CI->eraseFromParent();
690   }
691 }
692 
693 void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
694   Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
695 
696   for (auto I = TypeCheckedLoadFunc->use_begin(),
697             E = TypeCheckedLoadFunc->use_end();
698        I != E;) {
699     auto CI = dyn_cast<CallInst>(I->getUser());
700     ++I;
701     if (!CI)
702       continue;
703 
704     Value *Ptr = CI->getArgOperand(0);
705     Value *Offset = CI->getArgOperand(1);
706     Value *TypeIdValue = CI->getArgOperand(2);
707     Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
708 
709     SmallVector<DevirtCallSite, 1> DevirtCalls;
710     SmallVector<Instruction *, 1> LoadedPtrs;
711     SmallVector<Instruction *, 1> Preds;
712     bool HasNonCallUses = false;
713     findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
714                                                HasNonCallUses, CI);
715 
716     // Start by generating "pessimistic" code that explicitly loads the function
717     // pointer from the vtable and performs the type check. If possible, we will
718     // eliminate the load and the type check later.
719 
720     // If possible, only generate the load at the point where it is used.
721     // This helps avoid unnecessary spills.
722     IRBuilder<> LoadB(
723         (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
724     Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
725     Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
726     Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
727 
728     for (Instruction *LoadedPtr : LoadedPtrs) {
729       LoadedPtr->replaceAllUsesWith(LoadedValue);
730       LoadedPtr->eraseFromParent();
731     }
732 
733     // Likewise for the type test.
734     IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
735     CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
736 
737     for (Instruction *Pred : Preds) {
738       Pred->replaceAllUsesWith(TypeTestCall);
739       Pred->eraseFromParent();
740     }
741 
742     // We have already erased any extractvalue instructions that refer to the
743     // intrinsic call, but the intrinsic may have other non-extractvalue uses
744     // (although this is unlikely). In that case, explicitly build a pair and
745     // RAUW it.
746     if (!CI->use_empty()) {
747       Value *Pair = UndefValue::get(CI->getType());
748       IRBuilder<> B(CI);
749       Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
750       Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
751       CI->replaceAllUsesWith(Pair);
752     }
753 
754     // The number of unsafe uses is initially the number of uses.
755     auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
756     NumUnsafeUses = DevirtCalls.size();
757 
758     // If the function pointer has a non-call user, we cannot eliminate the type
759     // check, as one of those users may eventually call the pointer. Increment
760     // the unsafe use count to make sure it cannot reach zero.
761     if (HasNonCallUses)
762       ++NumUnsafeUses;
763     for (DevirtCallSite Call : DevirtCalls) {
764       CallSlots[{TypeId, Call.Offset}].push_back(
765           {Ptr, Call.CS, &NumUnsafeUses});
766     }
767 
768     CI->eraseFromParent();
769   }
770 }
771 
772 bool DevirtModule::run() {
773   Function *TypeTestFunc =
774       M.getFunction(Intrinsic::getName(Intrinsic::type_test));
775   Function *TypeCheckedLoadFunc =
776       M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
777   Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
778 
779   if ((!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
780        AssumeFunc->use_empty()) &&
781       (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
782     return false;
783 
784   if (TypeTestFunc && AssumeFunc)
785     scanTypeTestUsers(TypeTestFunc, AssumeFunc);
786 
787   if (TypeCheckedLoadFunc)
788     scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
789 
790   // Rebuild type metadata into a map for easy lookup.
791   std::vector<VTableBits> Bits;
792   DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
793   buildTypeIdentifierMap(Bits, TypeIdMap);
794   if (TypeIdMap.empty())
795     return true;
796 
797   // For each (type, offset) pair:
798   bool DidVirtualConstProp = false;
799   for (auto &S : CallSlots) {
800     // Search each of the members of the type identifier for the virtual
801     // function implementation at offset S.first.ByteOffset, and add to
802     // TargetsForSlot.
803     std::vector<VirtualCallTarget> TargetsForSlot;
804     if (!tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
805                                    S.first.ByteOffset))
806       continue;
807 
808     if (trySingleImplDevirt(TargetsForSlot, S.second))
809       continue;
810 
811     DidVirtualConstProp |= tryVirtualConstProp(TargetsForSlot, S.second);
812   }
813 
814   // If we were able to eliminate all unsafe uses for a type checked load,
815   // eliminate the type test by replacing it with true.
816   if (TypeCheckedLoadFunc) {
817     auto True = ConstantInt::getTrue(M.getContext());
818     for (auto &&U : NumUnsafeUsesForTypeTest) {
819       if (U.second == 0) {
820         U.first->replaceAllUsesWith(True);
821         U.first->eraseFromParent();
822       }
823     }
824   }
825 
826   // Rebuild each global we touched as part of virtual constant propagation to
827   // include the before and after bytes.
828   if (DidVirtualConstProp)
829     for (VTableBits &B : Bits)
830       rebuildGlobal(B);
831 
832   return true;
833 }
834