1 //===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===//
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 file implements utilities useful for promoting indirect call sites to
10 // direct call sites.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
15 #include "llvm/Analysis/Loads.h"
16 #include "llvm/Analysis/TypeMetadataUtils.h"
17 #include "llvm/IR/IRBuilder.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "call-promotion-utils"
24 
25 /// Fix-up phi nodes in an invoke instruction's normal destination.
26 ///
27 /// After versioning an invoke instruction, values coming from the original
28 /// block will now be coming from the "merge" block. For example, in the code
29 /// below:
30 ///
31 ///   then_bb:
32 ///     %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
33 ///
34 ///   else_bb:
35 ///     %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
36 ///
37 ///   merge_bb:
38 ///     %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
39 ///     br %normal_dst
40 ///
41 ///   normal_dst:
42 ///     %t3 = phi i32 [ %x, %orig_bb ], ...
43 ///
44 /// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in
45 /// "normal_dst" must be fixed to refer to "merge_bb":
46 ///
47 ///    normal_dst:
48 ///      %t3 = phi i32 [ %x, %merge_bb ], ...
49 ///
50 static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
51                                       BasicBlock *MergeBlock) {
52   for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
53     int Idx = Phi.getBasicBlockIndex(OrigBlock);
54     if (Idx == -1)
55       continue;
56     Phi.setIncomingBlock(Idx, MergeBlock);
57   }
58 }
59 
60 /// Fix-up phi nodes in an invoke instruction's unwind destination.
61 ///
62 /// After versioning an invoke instruction, values coming from the original
63 /// block will now be coming from either the "then" block or the "else" block.
64 /// For example, in the code below:
65 ///
66 ///   then_bb:
67 ///     %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
68 ///
69 ///   else_bb:
70 ///     %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
71 ///
72 ///   unwind_dst:
73 ///     %t3 = phi i32 [ %x, %orig_bb ], ...
74 ///
75 /// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in
76 /// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb":
77 ///
78 ///   unwind_dst:
79 ///     %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
80 ///
81 static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
82                                       BasicBlock *ThenBlock,
83                                       BasicBlock *ElseBlock) {
84   for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
85     int Idx = Phi.getBasicBlockIndex(OrigBlock);
86     if (Idx == -1)
87       continue;
88     auto *V = Phi.getIncomingValue(Idx);
89     Phi.setIncomingBlock(Idx, ThenBlock);
90     Phi.addIncoming(V, ElseBlock);
91   }
92 }
93 
94 /// Create a phi node for the returned value of a call or invoke instruction.
95 ///
96 /// After versioning a call or invoke instruction that returns a value, we have
97 /// to merge the value of the original and new instructions. We do this by
98 /// creating a phi node and replacing uses of the original instruction with this
99 /// phi node.
100 ///
101 /// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is
102 /// defined in "then_bb", we create the following phi node:
103 ///
104 ///   ; Uses of the original instruction are replaced by uses of the phi node.
105 ///   %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ],
106 ///
107 static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
108                              BasicBlock *MergeBlock, IRBuilder<> &Builder) {
109 
110   if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
111     return;
112 
113   Builder.SetInsertPoint(&MergeBlock->front());
114   PHINode *Phi = Builder.CreatePHI(OrigInst->getType(), 0);
115   SmallVector<User *, 16> UsersToUpdate;
116   for (User *U : OrigInst->users())
117     UsersToUpdate.push_back(U);
118   for (User *U : UsersToUpdate)
119     U->replaceUsesOfWith(OrigInst, Phi);
120   Phi->addIncoming(OrigInst, OrigInst->getParent());
121   Phi->addIncoming(NewInst, NewInst->getParent());
122 }
123 
124 /// Cast a call or invoke instruction to the given type.
125 ///
126 /// When promoting a call site, the return type of the call site might not match
127 /// that of the callee. If this is the case, we have to cast the returned value
128 /// to the correct type. The location of the cast depends on if we have a call
129 /// or invoke instruction.
130 ///
131 /// For example, if the call instruction below requires a bitcast after
132 /// promotion:
133 ///
134 ///   orig_bb:
135 ///     %t0 = call i32 @func()
136 ///     ...
137 ///
138 /// The bitcast is placed after the call instruction:
139 ///
140 ///   orig_bb:
141 ///     ; Uses of the original return value are replaced by uses of the bitcast.
142 ///     %t0 = call i32 @func()
143 ///     %t1 = bitcast i32 %t0 to ...
144 ///     ...
145 ///
146 /// A similar transformation is performed for invoke instructions. However,
147 /// since invokes are terminating, a new block is created for the bitcast. For
148 /// example, if the invoke instruction below requires a bitcast after promotion:
149 ///
150 ///   orig_bb:
151 ///     %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
152 ///
153 /// The edge between the original block and the invoke's normal destination is
154 /// split, and the bitcast is placed there:
155 ///
156 ///   orig_bb:
157 ///     %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
158 ///
159 ///   split_bb:
160 ///     ; Uses of the original return value are replaced by uses of the bitcast.
161 ///     %t1 = bitcast i32 %t0 to ...
162 ///     br label %normal_dst
163 ///
164 static void createRetBitCast(CallBase &CB, Type *RetTy, CastInst **RetBitCast) {
165 
166   // Save the users of the calling instruction. These uses will be changed to
167   // use the bitcast after we create it.
168   SmallVector<User *, 16> UsersToUpdate;
169   for (User *U : CB.users())
170     UsersToUpdate.push_back(U);
171 
172   // Determine an appropriate location to create the bitcast for the return
173   // value. The location depends on if we have a call or invoke instruction.
174   Instruction *InsertBefore = nullptr;
175   if (auto *Invoke = dyn_cast<InvokeInst>(&CB))
176     InsertBefore =
177         &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front();
178   else
179     InsertBefore = &*std::next(CB.getIterator());
180 
181   // Bitcast the return value to the correct type.
182   auto *Cast = CastInst::CreateBitOrPointerCast(&CB, RetTy, "", InsertBefore);
183   if (RetBitCast)
184     *RetBitCast = Cast;
185 
186   // Replace all the original uses of the calling instruction with the bitcast.
187   for (User *U : UsersToUpdate)
188     U->replaceUsesOfWith(&CB, Cast);
189 }
190 
191 /// Predicate and clone the given call site.
192 ///
193 /// This function creates an if-then-else structure at the location of the call
194 /// site. The "if" condition compares the call site's called value to the given
195 /// callee. The original call site is moved into the "else" block, and a clone
196 /// of the call site is placed in the "then" block. The cloned instruction is
197 /// returned.
198 ///
199 /// For example, the call instruction below:
200 ///
201 ///   orig_bb:
202 ///     %t0 = call i32 %ptr()
203 ///     ...
204 ///
205 /// Is replace by the following:
206 ///
207 ///   orig_bb:
208 ///     %cond = icmp eq i32 ()* %ptr, @func
209 ///     br i1 %cond, %then_bb, %else_bb
210 ///
211 ///   then_bb:
212 ///     ; The clone of the original call instruction is placed in the "then"
213 ///     ; block. It is not yet promoted.
214 ///     %t1 = call i32 %ptr()
215 ///     br merge_bb
216 ///
217 ///   else_bb:
218 ///     ; The original call instruction is moved to the "else" block.
219 ///     %t0 = call i32 %ptr()
220 ///     br merge_bb
221 ///
222 ///   merge_bb:
223 ///     ; Uses of the original call instruction are replaced by uses of the phi
224 ///     ; node.
225 ///     %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
226 ///     ...
227 ///
228 /// A similar transformation is performed for invoke instructions. However,
229 /// since invokes are terminating, more work is required. For example, the
230 /// invoke instruction below:
231 ///
232 ///   orig_bb:
233 ///     %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
234 ///
235 /// Is replace by the following:
236 ///
237 ///   orig_bb:
238 ///     %cond = icmp eq i32 ()* %ptr, @func
239 ///     br i1 %cond, %then_bb, %else_bb
240 ///
241 ///   then_bb:
242 ///     ; The clone of the original invoke instruction is placed in the "then"
243 ///     ; block, and its normal destination is set to the "merge" block. It is
244 ///     ; not yet promoted.
245 ///     %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
246 ///
247 ///   else_bb:
248 ///     ; The original invoke instruction is moved into the "else" block, and
249 ///     ; its normal destination is set to the "merge" block.
250 ///     %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
251 ///
252 ///   merge_bb:
253 ///     ; Uses of the original invoke instruction are replaced by uses of the
254 ///     ; phi node, and the merge block branches to the normal destination.
255 ///     %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
256 ///     br %normal_dst
257 ///
258 /// An indirect musttail call is processed slightly differently in that:
259 /// 1. No merge block needed for the orginal and the cloned callsite, since
260 ///    either one ends the flow. No phi node is needed either.
261 /// 2. The return statement following the original call site is duplicated too
262 ///    and placed immediately after the cloned call site per the IR convention.
263 ///
264 /// For example, the musttail call instruction below:
265 ///
266 ///   orig_bb:
267 ///     %t0 = musttail call i32 %ptr()
268 ///     ...
269 ///
270 /// Is replaced by the following:
271 ///
272 ///   cond_bb:
273 ///     %cond = icmp eq i32 ()* %ptr, @func
274 ///     br i1 %cond, %then_bb, %orig_bb
275 ///
276 ///   then_bb:
277 ///     ; The clone of the original call instruction is placed in the "then"
278 ///     ; block. It is not yet promoted.
279 ///     %t1 = musttail call i32 %ptr()
280 ///     ret %t1
281 ///
282 ///   orig_bb:
283 ///     ; The original call instruction stays in its original block.
284 ///     %t0 = musttail call i32 %ptr()
285 ///     ret %t0
286 static CallBase &versionCallSite(CallBase &CB, Value *Callee,
287                                  MDNode *BranchWeights) {
288 
289   IRBuilder<> Builder(&CB);
290   CallBase *OrigInst = &CB;
291   BasicBlock *OrigBlock = OrigInst->getParent();
292 
293   // Create the compare. The called value and callee must have the same type to
294   // be compared.
295   if (CB.getCalledOperand()->getType() != Callee->getType())
296     Callee = Builder.CreateBitCast(Callee, CB.getCalledOperand()->getType());
297   auto *Cond = Builder.CreateICmpEQ(CB.getCalledOperand(), Callee);
298 
299   if (OrigInst->isMustTailCall()) {
300     // Create an if-then structure. The original instruction stays in its block,
301     // and a clone of the original instruction is placed in the "then" block.
302     Instruction *ThenTerm =
303         SplitBlockAndInsertIfThen(Cond, &CB, false, BranchWeights);
304     BasicBlock *ThenBlock = ThenTerm->getParent();
305     ThenBlock->setName("if.true.direct_targ");
306     CallBase *NewInst = cast<CallBase>(OrigInst->clone());
307     NewInst->insertBefore(ThenTerm);
308 
309     // Place a clone of the optional bitcast after the new call site.
310     Value *NewRetVal = NewInst;
311     auto Next = OrigInst->getNextNode();
312     if (auto *BitCast = dyn_cast_or_null<BitCastInst>(Next)) {
313       assert(BitCast->getOperand(0) == OrigInst &&
314              "bitcast following musttail call must use the call");
315       auto NewBitCast = BitCast->clone();
316       NewBitCast->replaceUsesOfWith(OrigInst, NewInst);
317       NewBitCast->insertBefore(ThenTerm);
318       NewRetVal = NewBitCast;
319       Next = BitCast->getNextNode();
320     }
321 
322     // Place a clone of the return instruction after the new call site.
323     ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
324     assert(Ret && "musttail call must precede a ret with an optional bitcast");
325     auto NewRet = Ret->clone();
326     if (Ret->getReturnValue())
327       NewRet->replaceUsesOfWith(Ret->getReturnValue(), NewRetVal);
328     NewRet->insertBefore(ThenTerm);
329 
330     // A return instructions is terminating, so we don't need the terminator
331     // instruction just created.
332     ThenTerm->eraseFromParent();
333 
334     return *NewInst;
335   }
336 
337   // Create an if-then-else structure. The original instruction is moved into
338   // the "else" block, and a clone of the original instruction is placed in the
339   // "then" block.
340   Instruction *ThenTerm = nullptr;
341   Instruction *ElseTerm = nullptr;
342   SplitBlockAndInsertIfThenElse(Cond, &CB, &ThenTerm, &ElseTerm, BranchWeights);
343   BasicBlock *ThenBlock = ThenTerm->getParent();
344   BasicBlock *ElseBlock = ElseTerm->getParent();
345   BasicBlock *MergeBlock = OrigInst->getParent();
346 
347   ThenBlock->setName("if.true.direct_targ");
348   ElseBlock->setName("if.false.orig_indirect");
349   MergeBlock->setName("if.end.icp");
350 
351   CallBase *NewInst = cast<CallBase>(OrigInst->clone());
352   OrigInst->moveBefore(ElseTerm);
353   NewInst->insertBefore(ThenTerm);
354 
355   // If the original call site is an invoke instruction, we have extra work to
356   // do since invoke instructions are terminating. We have to fix-up phi nodes
357   // in the invoke's normal and unwind destinations.
358   if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) {
359     auto *NewInvoke = cast<InvokeInst>(NewInst);
360 
361     // Invoke instructions are terminating, so we don't need the terminator
362     // instructions that were just created.
363     ThenTerm->eraseFromParent();
364     ElseTerm->eraseFromParent();
365 
366     // Branch from the "merge" block to the original normal destination.
367     Builder.SetInsertPoint(MergeBlock);
368     Builder.CreateBr(OrigInvoke->getNormalDest());
369 
370     // Fix-up phi nodes in the original invoke's normal and unwind destinations.
371     fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock);
372     fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock);
373 
374     // Now set the normal destinations of the invoke instructions to be the
375     // "merge" block.
376     OrigInvoke->setNormalDest(MergeBlock);
377     NewInvoke->setNormalDest(MergeBlock);
378   }
379 
380   // Create a phi node for the returned value of the call site.
381   createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
382 
383   return *NewInst;
384 }
385 
386 bool llvm::isLegalToPromote(const CallBase &CB, Function *Callee,
387                             const char **FailureReason) {
388   assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted");
389 
390   auto &DL = Callee->getParent()->getDataLayout();
391 
392   // Check the return type. The callee's return value type must be bitcast
393   // compatible with the call site's type.
394   Type *CallRetTy = CB.getType();
395   Type *FuncRetTy = Callee->getReturnType();
396   if (CallRetTy != FuncRetTy)
397     if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy, CallRetTy, DL)) {
398       if (FailureReason)
399         *FailureReason = "Return type mismatch";
400       return false;
401     }
402 
403   // The number of formal arguments of the callee.
404   unsigned NumParams = Callee->getFunctionType()->getNumParams();
405 
406   // Check the number of arguments. The callee and call site must agree on the
407   // number of arguments.
408   if (CB.arg_size() != NumParams && !Callee->isVarArg()) {
409     if (FailureReason)
410       *FailureReason = "The number of arguments mismatch";
411     return false;
412   }
413 
414   // Check the argument types. The callee's formal argument types must be
415   // bitcast compatible with the corresponding actual argument types of the call
416   // site.
417   for (unsigned I = 0; I < NumParams; ++I) {
418     Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I);
419     Type *ActualTy = CB.getArgOperand(I)->getType();
420     if (FormalTy == ActualTy)
421       continue;
422     if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) {
423       if (FailureReason)
424         *FailureReason = "Argument type mismatch";
425       return false;
426     }
427   }
428 
429   return true;
430 }
431 
432 CallBase &llvm::promoteCall(CallBase &CB, Function *Callee,
433                             CastInst **RetBitCast) {
434   assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted");
435 
436   // Set the called function of the call site to be the given callee (but don't
437   // change the type).
438   CB.setCalledOperand(Callee);
439 
440   // Since the call site will no longer be direct, we must clear metadata that
441   // is only appropriate for indirect calls. This includes !prof and !callees
442   // metadata.
443   CB.setMetadata(LLVMContext::MD_prof, nullptr);
444   CB.setMetadata(LLVMContext::MD_callees, nullptr);
445 
446   // If the function type of the call site matches that of the callee, no
447   // additional work is required.
448   if (CB.getFunctionType() == Callee->getFunctionType())
449     return CB;
450 
451   // Save the return types of the call site and callee.
452   Type *CallSiteRetTy = CB.getType();
453   Type *CalleeRetTy = Callee->getReturnType();
454 
455   // Change the function type of the call site the match that of the callee.
456   CB.mutateFunctionType(Callee->getFunctionType());
457 
458   // Inspect the arguments of the call site. If an argument's type doesn't
459   // match the corresponding formal argument's type in the callee, bitcast it
460   // to the correct type.
461   auto CalleeType = Callee->getFunctionType();
462   auto CalleeParamNum = CalleeType->getNumParams();
463 
464   LLVMContext &Ctx = Callee->getContext();
465   const AttributeList &CallerPAL = CB.getAttributes();
466   // The new list of argument attributes.
467   SmallVector<AttributeSet, 4> NewArgAttrs;
468   bool AttributeChanged = false;
469 
470   for (unsigned ArgNo = 0; ArgNo < CalleeParamNum; ++ArgNo) {
471     auto *Arg = CB.getArgOperand(ArgNo);
472     Type *FormalTy = CalleeType->getParamType(ArgNo);
473     Type *ActualTy = Arg->getType();
474     if (FormalTy != ActualTy) {
475       auto *Cast = CastInst::CreateBitOrPointerCast(Arg, FormalTy, "", &CB);
476       CB.setArgOperand(ArgNo, Cast);
477 
478       // Remove any incompatible attributes for the argument.
479       AttrBuilder ArgAttrs(CallerPAL.getParamAttributes(ArgNo));
480       ArgAttrs.remove(AttributeFuncs::typeIncompatible(FormalTy));
481 
482       // If byval is used, this must be a pointer type, and the byval type must
483       // match the element type. Update it if present.
484       if (ArgAttrs.getByValType()) {
485         Type *NewTy = Callee->getParamByValType(ArgNo);
486         ArgAttrs.addByValAttr(
487             NewTy ? NewTy : cast<PointerType>(FormalTy)->getElementType());
488       }
489 
490       NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs));
491       AttributeChanged = true;
492     } else
493       NewArgAttrs.push_back(CallerPAL.getParamAttributes(ArgNo));
494   }
495 
496   // If the return type of the call site doesn't match that of the callee, cast
497   // the returned value to the appropriate type.
498   // Remove any incompatible return value attribute.
499   AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
500   if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy) {
501     createRetBitCast(CB, CallSiteRetTy, RetBitCast);
502     RAttrs.remove(AttributeFuncs::typeIncompatible(CalleeRetTy));
503     AttributeChanged = true;
504   }
505 
506   // Set the new callsite attribute.
507   if (AttributeChanged)
508     CB.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttributes(),
509                                         AttributeSet::get(Ctx, RAttrs),
510                                         NewArgAttrs));
511 
512   return CB;
513 }
514 
515 CallBase &llvm::promoteCallWithIfThenElse(CallBase &CB, Function *Callee,
516                                           MDNode *BranchWeights) {
517 
518   // Version the indirect call site. If the called value is equal to the given
519   // callee, 'NewInst' will be executed, otherwise the original call site will
520   // be executed.
521   CallBase &NewInst = versionCallSite(CB, Callee, BranchWeights);
522 
523   // Promote 'NewInst' so that it directly calls the desired function.
524   return promoteCall(NewInst, Callee);
525 }
526 
527 bool llvm::tryPromoteCall(CallBase &CB) {
528   assert(!CB.getCalledFunction());
529   Module *M = CB.getCaller()->getParent();
530   const DataLayout &DL = M->getDataLayout();
531   Value *Callee = CB.getCalledOperand();
532 
533   LoadInst *VTableEntryLoad = dyn_cast<LoadInst>(Callee);
534   if (!VTableEntryLoad)
535     return false; // Not a vtable entry load.
536   Value *VTableEntryPtr = VTableEntryLoad->getPointerOperand();
537   APInt VTableOffset(DL.getTypeSizeInBits(VTableEntryPtr->getType()), 0);
538   Value *VTableBasePtr = VTableEntryPtr->stripAndAccumulateConstantOffsets(
539       DL, VTableOffset, /* AllowNonInbounds */ true);
540   LoadInst *VTablePtrLoad = dyn_cast<LoadInst>(VTableBasePtr);
541   if (!VTablePtrLoad)
542     return false; // Not a vtable load.
543   Value *Object = VTablePtrLoad->getPointerOperand();
544   APInt ObjectOffset(DL.getTypeSizeInBits(Object->getType()), 0);
545   Value *ObjectBase = Object->stripAndAccumulateConstantOffsets(
546       DL, ObjectOffset, /* AllowNonInbounds */ true);
547   if (!(isa<AllocaInst>(ObjectBase) && ObjectOffset == 0))
548     // Not an Alloca or the offset isn't zero.
549     return false;
550 
551   // Look for the vtable pointer store into the object by the ctor.
552   BasicBlock::iterator BBI(VTablePtrLoad);
553   Value *VTablePtr = FindAvailableLoadedValue(
554       VTablePtrLoad, VTablePtrLoad->getParent(), BBI, 0, nullptr, nullptr);
555   if (!VTablePtr)
556     return false; // No vtable found.
557   APInt VTableOffsetGVBase(DL.getTypeSizeInBits(VTablePtr->getType()), 0);
558   Value *VTableGVBase = VTablePtr->stripAndAccumulateConstantOffsets(
559       DL, VTableOffsetGVBase, /* AllowNonInbounds */ true);
560   GlobalVariable *GV = dyn_cast<GlobalVariable>(VTableGVBase);
561   if (!(GV && GV->isConstant() && GV->hasDefinitiveInitializer()))
562     // Not in the form of a global constant variable with an initializer.
563     return false;
564 
565   Constant *VTableGVInitializer = GV->getInitializer();
566   APInt VTableGVOffset = VTableOffsetGVBase + VTableOffset;
567   if (!(VTableGVOffset.getActiveBits() <= 64))
568     return false; // Out of range.
569   Constant *Ptr = getPointerAtOffset(VTableGVInitializer,
570                                      VTableGVOffset.getZExtValue(),
571                                      *M);
572   if (!Ptr)
573     return false; // No constant (function) pointer found.
574   Function *DirectCallee = dyn_cast<Function>(Ptr->stripPointerCasts());
575   if (!DirectCallee)
576     return false; // No function pointer found.
577 
578   if (!isLegalToPromote(CB, DirectCallee))
579     return false;
580 
581   // Success.
582   promoteCall(CB, DirectCallee);
583   return true;
584 }
585 
586 #undef DEBUG_TYPE
587