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 static CallBase &versionCallSite(CallBase &CB, Value *Callee,
259                                  MDNode *BranchWeights) {
260 
261   IRBuilder<> Builder(&CB);
262   CallBase *OrigInst = &CB;
263   BasicBlock *OrigBlock = OrigInst->getParent();
264 
265   // Create the compare. The called value and callee must have the same type to
266   // be compared.
267   if (CB.getCalledValue()->getType() != Callee->getType())
268     Callee = Builder.CreateBitCast(Callee, CB.getCalledValue()->getType());
269   auto *Cond = Builder.CreateICmpEQ(CB.getCalledValue(), Callee);
270 
271   // Create an if-then-else structure. The original instruction is moved into
272   // the "else" block, and a clone of the original instruction is placed in the
273   // "then" block.
274   Instruction *ThenTerm = nullptr;
275   Instruction *ElseTerm = nullptr;
276   SplitBlockAndInsertIfThenElse(Cond, &CB, &ThenTerm, &ElseTerm, BranchWeights);
277   BasicBlock *ThenBlock = ThenTerm->getParent();
278   BasicBlock *ElseBlock = ElseTerm->getParent();
279   BasicBlock *MergeBlock = OrigInst->getParent();
280 
281   ThenBlock->setName("if.true.direct_targ");
282   ElseBlock->setName("if.false.orig_indirect");
283   MergeBlock->setName("if.end.icp");
284 
285   CallBase *NewInst = cast<CallBase>(OrigInst->clone());
286   OrigInst->moveBefore(ElseTerm);
287   NewInst->insertBefore(ThenTerm);
288 
289   // If the original call site is an invoke instruction, we have extra work to
290   // do since invoke instructions are terminating. We have to fix-up phi nodes
291   // in the invoke's normal and unwind destinations.
292   if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) {
293     auto *NewInvoke = cast<InvokeInst>(NewInst);
294 
295     // Invoke instructions are terminating, so we don't need the terminator
296     // instructions that were just created.
297     ThenTerm->eraseFromParent();
298     ElseTerm->eraseFromParent();
299 
300     // Branch from the "merge" block to the original normal destination.
301     Builder.SetInsertPoint(MergeBlock);
302     Builder.CreateBr(OrigInvoke->getNormalDest());
303 
304     // Fix-up phi nodes in the original invoke's normal and unwind destinations.
305     fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock);
306     fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock);
307 
308     // Now set the normal destinations of the invoke instructions to be the
309     // "merge" block.
310     OrigInvoke->setNormalDest(MergeBlock);
311     NewInvoke->setNormalDest(MergeBlock);
312   }
313 
314   // Create a phi node for the returned value of the call site.
315   createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
316 
317   return *NewInst;
318 }
319 
320 bool llvm::isLegalToPromote(CallBase &CB, Function *Callee,
321                             const char **FailureReason) {
322   assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted");
323 
324   auto &DL = Callee->getParent()->getDataLayout();
325 
326   // Check the return type. The callee's return value type must be bitcast
327   // compatible with the call site's type.
328   Type *CallRetTy = CB.getType();
329   Type *FuncRetTy = Callee->getReturnType();
330   if (CallRetTy != FuncRetTy)
331     if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy, CallRetTy, DL)) {
332       if (FailureReason)
333         *FailureReason = "Return type mismatch";
334       return false;
335     }
336 
337   // The number of formal arguments of the callee.
338   unsigned NumParams = Callee->getFunctionType()->getNumParams();
339 
340   // Check the number of arguments. The callee and call site must agree on the
341   // number of arguments.
342   if (CB.arg_size() != NumParams && !Callee->isVarArg()) {
343     if (FailureReason)
344       *FailureReason = "The number of arguments mismatch";
345     return false;
346   }
347 
348   // Check the argument types. The callee's formal argument types must be
349   // bitcast compatible with the corresponding actual argument types of the call
350   // site.
351   for (unsigned I = 0; I < NumParams; ++I) {
352     Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I);
353     Type *ActualTy = CB.getArgOperand(I)->getType();
354     if (FormalTy == ActualTy)
355       continue;
356     if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) {
357       if (FailureReason)
358         *FailureReason = "Argument type mismatch";
359       return false;
360     }
361   }
362 
363   return true;
364 }
365 
366 CallBase &llvm::promoteCall(CallBase &CB, Function *Callee,
367                             CastInst **RetBitCast) {
368   assert(!CB.getCalledFunction() && "Only indirect call sites can be promoted");
369 
370   // Set the called function of the call site to be the given callee (but don't
371   // change the type).
372   CB.setCalledOperand(Callee);
373 
374   // Since the call site will no longer be direct, we must clear metadata that
375   // is only appropriate for indirect calls. This includes !prof and !callees
376   // metadata.
377   CB.setMetadata(LLVMContext::MD_prof, nullptr);
378   CB.setMetadata(LLVMContext::MD_callees, nullptr);
379 
380   // If the function type of the call site matches that of the callee, no
381   // additional work is required.
382   if (CB.getFunctionType() == Callee->getFunctionType())
383     return CB;
384 
385   // Save the return types of the call site and callee.
386   Type *CallSiteRetTy = CB.getType();
387   Type *CalleeRetTy = Callee->getReturnType();
388 
389   // Change the function type of the call site the match that of the callee.
390   CB.mutateFunctionType(Callee->getFunctionType());
391 
392   // Inspect the arguments of the call site. If an argument's type doesn't
393   // match the corresponding formal argument's type in the callee, bitcast it
394   // to the correct type.
395   auto CalleeType = Callee->getFunctionType();
396   auto CalleeParamNum = CalleeType->getNumParams();
397 
398   LLVMContext &Ctx = Callee->getContext();
399   const AttributeList &CallerPAL = CB.getAttributes();
400   // The new list of argument attributes.
401   SmallVector<AttributeSet, 4> NewArgAttrs;
402   bool AttributeChanged = false;
403 
404   for (unsigned ArgNo = 0; ArgNo < CalleeParamNum; ++ArgNo) {
405     auto *Arg = CB.getArgOperand(ArgNo);
406     Type *FormalTy = CalleeType->getParamType(ArgNo);
407     Type *ActualTy = Arg->getType();
408     if (FormalTy != ActualTy) {
409       auto *Cast = CastInst::CreateBitOrPointerCast(Arg, FormalTy, "", &CB);
410       CB.setArgOperand(ArgNo, Cast);
411 
412       // Remove any incompatible attributes for the argument.
413       AttrBuilder ArgAttrs(CallerPAL.getParamAttributes(ArgNo));
414       ArgAttrs.remove(AttributeFuncs::typeIncompatible(FormalTy));
415 
416       // If byval is used, this must be a pointer type, and the byval type must
417       // match the element type. Update it if present.
418       if (ArgAttrs.getByValType()) {
419         Type *NewTy = Callee->getParamByValType(ArgNo);
420         ArgAttrs.addByValAttr(
421             NewTy ? NewTy : cast<PointerType>(FormalTy)->getElementType());
422       }
423 
424       NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs));
425       AttributeChanged = true;
426     } else
427       NewArgAttrs.push_back(CallerPAL.getParamAttributes(ArgNo));
428   }
429 
430   // If the return type of the call site doesn't match that of the callee, cast
431   // the returned value to the appropriate type.
432   // Remove any incompatible return value attribute.
433   AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
434   if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy) {
435     createRetBitCast(CB, CallSiteRetTy, RetBitCast);
436     RAttrs.remove(AttributeFuncs::typeIncompatible(CalleeRetTy));
437     AttributeChanged = true;
438   }
439 
440   // Set the new callsite attribute.
441   if (AttributeChanged)
442     CB.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttributes(),
443                                         AttributeSet::get(Ctx, RAttrs),
444                                         NewArgAttrs));
445 
446   return CB;
447 }
448 
449 CallBase &llvm::promoteCallWithIfThenElse(CallBase &CB, Function *Callee,
450                                           MDNode *BranchWeights) {
451 
452   // Version the indirect call site. If the called value is equal to the given
453   // callee, 'NewInst' will be executed, otherwise the original call site will
454   // be executed.
455   CallBase &NewInst = versionCallSite(CB, Callee, BranchWeights);
456 
457   // Promote 'NewInst' so that it directly calls the desired function.
458   return promoteCall(NewInst, Callee);
459 }
460 
461 bool llvm::tryPromoteCall(CallBase &CB) {
462   assert(!CB.getCalledFunction());
463   Module *M = CB.getCaller()->getParent();
464   const DataLayout &DL = M->getDataLayout();
465   Value *Callee = CB.getCalledValue();
466 
467   LoadInst *VTableEntryLoad = dyn_cast<LoadInst>(Callee);
468   if (!VTableEntryLoad)
469     return false; // Not a vtable entry load.
470   Value *VTableEntryPtr = VTableEntryLoad->getPointerOperand();
471   APInt VTableOffset(DL.getTypeSizeInBits(VTableEntryPtr->getType()), 0);
472   Value *VTableBasePtr = VTableEntryPtr->stripAndAccumulateConstantOffsets(
473       DL, VTableOffset, /* AllowNonInbounds */ true);
474   LoadInst *VTablePtrLoad = dyn_cast<LoadInst>(VTableBasePtr);
475   if (!VTablePtrLoad)
476     return false; // Not a vtable load.
477   Value *Object = VTablePtrLoad->getPointerOperand();
478   APInt ObjectOffset(DL.getTypeSizeInBits(Object->getType()), 0);
479   Value *ObjectBase = Object->stripAndAccumulateConstantOffsets(
480       DL, ObjectOffset, /* AllowNonInbounds */ true);
481   if (!(isa<AllocaInst>(ObjectBase) && ObjectOffset == 0))
482     // Not an Alloca or the offset isn't zero.
483     return false;
484 
485   // Look for the vtable pointer store into the object by the ctor.
486   BasicBlock::iterator BBI(VTablePtrLoad);
487   Value *VTablePtr = FindAvailableLoadedValue(
488       VTablePtrLoad, VTablePtrLoad->getParent(), BBI, 0, nullptr, nullptr);
489   if (!VTablePtr)
490     return false; // No vtable found.
491   APInt VTableOffsetGVBase(DL.getTypeSizeInBits(VTablePtr->getType()), 0);
492   Value *VTableGVBase = VTablePtr->stripAndAccumulateConstantOffsets(
493       DL, VTableOffsetGVBase, /* AllowNonInbounds */ true);
494   GlobalVariable *GV = dyn_cast<GlobalVariable>(VTableGVBase);
495   if (!(GV && GV->isConstant() && GV->hasDefinitiveInitializer()))
496     // Not in the form of a global constant variable with an initializer.
497     return false;
498 
499   Constant *VTableGVInitializer = GV->getInitializer();
500   APInt VTableGVOffset = VTableOffsetGVBase + VTableOffset;
501   if (!(VTableGVOffset.getActiveBits() <= 64))
502     return false; // Out of range.
503   Constant *Ptr = getPointerAtOffset(VTableGVInitializer,
504                                      VTableGVOffset.getZExtValue(),
505                                      *M);
506   if (!Ptr)
507     return false; // No constant (function) pointer found.
508   Function *DirectCallee = dyn_cast<Function>(Ptr->stripPointerCasts());
509   if (!DirectCallee)
510     return false; // No function pointer found.
511 
512   if (!isLegalToPromote(CB, DirectCallee))
513     return false;
514 
515   // Success.
516   promoteCall(CB, DirectCallee);
517   return true;
518 }
519 
520 #undef DEBUG_TYPE
521