12cab237bSDimitry Andric //===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===//
22cab237bSDimitry Andric //
32cab237bSDimitry Andric //                     The LLVM Compiler Infrastructure
42cab237bSDimitry Andric //
52cab237bSDimitry Andric // This file is distributed under the University of Illinois Open Source
62cab237bSDimitry Andric // License. See LICENSE.TXT for details.
72cab237bSDimitry Andric //
82cab237bSDimitry Andric //===----------------------------------------------------------------------===//
92cab237bSDimitry Andric //
102cab237bSDimitry Andric // This file implements utilities useful for promoting indirect call sites to
112cab237bSDimitry Andric // direct call sites.
122cab237bSDimitry Andric //
132cab237bSDimitry Andric //===----------------------------------------------------------------------===//
142cab237bSDimitry Andric 
152cab237bSDimitry Andric #include "llvm/Transforms/Utils/CallPromotionUtils.h"
162cab237bSDimitry Andric #include "llvm/IR/IRBuilder.h"
172cab237bSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
182cab237bSDimitry Andric 
192cab237bSDimitry Andric using namespace llvm;
202cab237bSDimitry Andric 
212cab237bSDimitry Andric #define DEBUG_TYPE "call-promotion-utils"
222cab237bSDimitry Andric 
232cab237bSDimitry Andric /// Fix-up phi nodes in an invoke instruction's normal destination.
242cab237bSDimitry Andric ///
252cab237bSDimitry Andric /// After versioning an invoke instruction, values coming from the original
26da09e106SDimitry Andric /// block will now be coming from the "merge" block. For example, in the code
27da09e106SDimitry Andric /// below:
28da09e106SDimitry Andric ///
29da09e106SDimitry Andric ///   then_bb:
30da09e106SDimitry Andric ///     %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
31da09e106SDimitry Andric ///
32da09e106SDimitry Andric ///   else_bb:
33da09e106SDimitry Andric ///     %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
34da09e106SDimitry Andric ///
35da09e106SDimitry Andric ///   merge_bb:
36da09e106SDimitry Andric ///     %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
37da09e106SDimitry Andric ///     br %normal_dst
38da09e106SDimitry Andric ///
39da09e106SDimitry Andric ///   normal_dst:
40da09e106SDimitry Andric ///     %t3 = phi i32 [ %x, %orig_bb ], ...
41da09e106SDimitry Andric ///
42da09e106SDimitry Andric /// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in
43da09e106SDimitry Andric /// "normal_dst" must be fixed to refer to "merge_bb":
44da09e106SDimitry Andric ///
45da09e106SDimitry Andric ///    normal_dst:
46da09e106SDimitry Andric ///      %t3 = phi i32 [ %x, %merge_bb ], ...
47da09e106SDimitry Andric ///
fixupPHINodeForNormalDest(InvokeInst * Invoke,BasicBlock * OrigBlock,BasicBlock * MergeBlock)482cab237bSDimitry Andric static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
49da09e106SDimitry Andric                                       BasicBlock *MergeBlock) {
5030785c0eSDimitry Andric   for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
5130785c0eSDimitry Andric     int Idx = Phi.getBasicBlockIndex(OrigBlock);
522cab237bSDimitry Andric     if (Idx == -1)
532cab237bSDimitry Andric       continue;
5430785c0eSDimitry Andric     Phi.setIncomingBlock(Idx, MergeBlock);
552cab237bSDimitry Andric   }
562cab237bSDimitry Andric }
572cab237bSDimitry Andric 
582cab237bSDimitry Andric /// Fix-up phi nodes in an invoke instruction's unwind destination.
592cab237bSDimitry Andric ///
602cab237bSDimitry Andric /// After versioning an invoke instruction, values coming from the original
612cab237bSDimitry Andric /// block will now be coming from either the "then" block or the "else" block.
62da09e106SDimitry Andric /// For example, in the code below:
63da09e106SDimitry Andric ///
64da09e106SDimitry Andric ///   then_bb:
65da09e106SDimitry Andric ///     %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
66da09e106SDimitry Andric ///
67da09e106SDimitry Andric ///   else_bb:
68da09e106SDimitry Andric ///     %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
69da09e106SDimitry Andric ///
70da09e106SDimitry Andric ///   unwind_dst:
71da09e106SDimitry Andric ///     %t3 = phi i32 [ %x, %orig_bb ], ...
72da09e106SDimitry Andric ///
73da09e106SDimitry Andric /// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in
74da09e106SDimitry Andric /// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb":
75da09e106SDimitry Andric ///
76da09e106SDimitry Andric ///   unwind_dst:
77da09e106SDimitry Andric ///     %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
78da09e106SDimitry Andric ///
fixupPHINodeForUnwindDest(InvokeInst * Invoke,BasicBlock * OrigBlock,BasicBlock * ThenBlock,BasicBlock * ElseBlock)792cab237bSDimitry Andric static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
802cab237bSDimitry Andric                                       BasicBlock *ThenBlock,
812cab237bSDimitry Andric                                       BasicBlock *ElseBlock) {
8230785c0eSDimitry Andric   for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
8330785c0eSDimitry Andric     int Idx = Phi.getBasicBlockIndex(OrigBlock);
842cab237bSDimitry Andric     if (Idx == -1)
852cab237bSDimitry Andric       continue;
8630785c0eSDimitry Andric     auto *V = Phi.getIncomingValue(Idx);
8730785c0eSDimitry Andric     Phi.setIncomingBlock(Idx, ThenBlock);
8830785c0eSDimitry Andric     Phi.addIncoming(V, ElseBlock);
892cab237bSDimitry Andric   }
902cab237bSDimitry Andric }
912cab237bSDimitry Andric 
922cab237bSDimitry Andric /// Create a phi node for the returned value of a call or invoke instruction.
932cab237bSDimitry Andric ///
942cab237bSDimitry Andric /// After versioning a call or invoke instruction that returns a value, we have
952cab237bSDimitry Andric /// to merge the value of the original and new instructions. We do this by
962cab237bSDimitry Andric /// creating a phi node and replacing uses of the original instruction with this
972cab237bSDimitry Andric /// phi node.
98da09e106SDimitry Andric ///
99da09e106SDimitry Andric /// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is
100da09e106SDimitry Andric /// defined in "then_bb", we create the following phi node:
101da09e106SDimitry Andric ///
102da09e106SDimitry Andric ///   ; Uses of the original instruction are replaced by uses of the phi node.
103da09e106SDimitry Andric ///   %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ],
104da09e106SDimitry Andric ///
createRetPHINode(Instruction * OrigInst,Instruction * NewInst,BasicBlock * MergeBlock,IRBuilder<> & Builder)105da09e106SDimitry Andric static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
106da09e106SDimitry Andric                              BasicBlock *MergeBlock, IRBuilder<> &Builder) {
1072cab237bSDimitry Andric 
1082cab237bSDimitry Andric   if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
1092cab237bSDimitry Andric     return;
1102cab237bSDimitry Andric 
111da09e106SDimitry Andric   Builder.SetInsertPoint(&MergeBlock->front());
1122cab237bSDimitry Andric   PHINode *Phi = Builder.CreatePHI(OrigInst->getType(), 0);
1132cab237bSDimitry Andric   SmallVector<User *, 16> UsersToUpdate;
1142cab237bSDimitry Andric   for (User *U : OrigInst->users())
1152cab237bSDimitry Andric     UsersToUpdate.push_back(U);
1162cab237bSDimitry Andric   for (User *U : UsersToUpdate)
1172cab237bSDimitry Andric     U->replaceUsesOfWith(OrigInst, Phi);
1182cab237bSDimitry Andric   Phi->addIncoming(OrigInst, OrigInst->getParent());
119da09e106SDimitry Andric   Phi->addIncoming(NewInst, NewInst->getParent());
1202cab237bSDimitry Andric }
1212cab237bSDimitry Andric 
1222cab237bSDimitry Andric /// Cast a call or invoke instruction to the given type.
1232cab237bSDimitry Andric ///
1242cab237bSDimitry Andric /// When promoting a call site, the return type of the call site might not match
1252cab237bSDimitry Andric /// that of the callee. If this is the case, we have to cast the returned value
1262cab237bSDimitry Andric /// to the correct type. The location of the cast depends on if we have a call
1272cab237bSDimitry Andric /// or invoke instruction.
128da09e106SDimitry Andric ///
129da09e106SDimitry Andric /// For example, if the call instruction below requires a bitcast after
130da09e106SDimitry Andric /// promotion:
131da09e106SDimitry Andric ///
132da09e106SDimitry Andric ///   orig_bb:
133da09e106SDimitry Andric ///     %t0 = call i32 @func()
134da09e106SDimitry Andric ///     ...
135da09e106SDimitry Andric ///
136da09e106SDimitry Andric /// The bitcast is placed after the call instruction:
137da09e106SDimitry Andric ///
138da09e106SDimitry Andric ///   orig_bb:
139da09e106SDimitry Andric ///     ; Uses of the original return value are replaced by uses of the bitcast.
140da09e106SDimitry Andric ///     %t0 = call i32 @func()
141da09e106SDimitry Andric ///     %t1 = bitcast i32 %t0 to ...
142da09e106SDimitry Andric ///     ...
143da09e106SDimitry Andric ///
144da09e106SDimitry Andric /// A similar transformation is performed for invoke instructions. However,
145da09e106SDimitry Andric /// since invokes are terminating, a new block is created for the bitcast. For
146da09e106SDimitry Andric /// example, if the invoke instruction below requires a bitcast after promotion:
147da09e106SDimitry Andric ///
148da09e106SDimitry Andric ///   orig_bb:
149da09e106SDimitry Andric ///     %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
150da09e106SDimitry Andric ///
151da09e106SDimitry Andric /// The edge between the original block and the invoke's normal destination is
152da09e106SDimitry Andric /// split, and the bitcast is placed there:
153da09e106SDimitry Andric ///
154da09e106SDimitry Andric ///   orig_bb:
155da09e106SDimitry Andric ///     %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
156da09e106SDimitry Andric ///
157da09e106SDimitry Andric ///   split_bb:
158da09e106SDimitry Andric ///     ; Uses of the original return value are replaced by uses of the bitcast.
159da09e106SDimitry Andric ///     %t1 = bitcast i32 %t0 to ...
160da09e106SDimitry Andric ///     br label %normal_dst
161da09e106SDimitry Andric ///
createRetBitCast(CallSite CS,Type * RetTy,CastInst ** RetBitCast)162da09e106SDimitry Andric static void createRetBitCast(CallSite CS, Type *RetTy, CastInst **RetBitCast) {
1632cab237bSDimitry Andric 
1642cab237bSDimitry Andric   // Save the users of the calling instruction. These uses will be changed to
1652cab237bSDimitry Andric   // use the bitcast after we create it.
1662cab237bSDimitry Andric   SmallVector<User *, 16> UsersToUpdate;
1672cab237bSDimitry Andric   for (User *U : CS.getInstruction()->users())
1682cab237bSDimitry Andric     UsersToUpdate.push_back(U);
1692cab237bSDimitry Andric 
1702cab237bSDimitry Andric   // Determine an appropriate location to create the bitcast for the return
1712cab237bSDimitry Andric   // value. The location depends on if we have a call or invoke instruction.
1722cab237bSDimitry Andric   Instruction *InsertBefore = nullptr;
1732cab237bSDimitry Andric   if (auto *Invoke = dyn_cast<InvokeInst>(CS.getInstruction()))
174da09e106SDimitry Andric     InsertBefore =
175da09e106SDimitry Andric         &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front();
1762cab237bSDimitry Andric   else
1772cab237bSDimitry Andric     InsertBefore = &*std::next(CS.getInstruction()->getIterator());
1782cab237bSDimitry Andric 
1792cab237bSDimitry Andric   // Bitcast the return value to the correct type.
180*b5893f02SDimitry Andric   auto *Cast = CastInst::CreateBitOrPointerCast(CS.getInstruction(), RetTy, "",
181*b5893f02SDimitry Andric                                                 InsertBefore);
182da09e106SDimitry Andric   if (RetBitCast)
183da09e106SDimitry Andric     *RetBitCast = Cast;
1842cab237bSDimitry Andric 
1852cab237bSDimitry Andric   // Replace all the original uses of the calling instruction with the bitcast.
1862cab237bSDimitry Andric   for (User *U : UsersToUpdate)
1872cab237bSDimitry Andric     U->replaceUsesOfWith(CS.getInstruction(), Cast);
1882cab237bSDimitry Andric }
1892cab237bSDimitry Andric 
1902cab237bSDimitry Andric /// Predicate and clone the given call site.
1912cab237bSDimitry Andric ///
1922cab237bSDimitry Andric /// This function creates an if-then-else structure at the location of the call
1932cab237bSDimitry Andric /// site. The "if" condition compares the call site's called value to the given
1942cab237bSDimitry Andric /// callee. The original call site is moved into the "else" block, and a clone
1952cab237bSDimitry Andric /// of the call site is placed in the "then" block. The cloned instruction is
1962cab237bSDimitry Andric /// returned.
197da09e106SDimitry Andric ///
198da09e106SDimitry Andric /// For example, the call instruction below:
199da09e106SDimitry Andric ///
200da09e106SDimitry Andric ///   orig_bb:
201da09e106SDimitry Andric ///     %t0 = call i32 %ptr()
202da09e106SDimitry Andric ///     ...
203da09e106SDimitry Andric ///
204da09e106SDimitry Andric /// Is replace by the following:
205da09e106SDimitry Andric ///
206da09e106SDimitry Andric ///   orig_bb:
207da09e106SDimitry Andric ///     %cond = icmp eq i32 ()* %ptr, @func
208da09e106SDimitry Andric ///     br i1 %cond, %then_bb, %else_bb
209da09e106SDimitry Andric ///
210da09e106SDimitry Andric ///   then_bb:
211da09e106SDimitry Andric ///     ; The clone of the original call instruction is placed in the "then"
212da09e106SDimitry Andric ///     ; block. It is not yet promoted.
213da09e106SDimitry Andric ///     %t1 = call i32 %ptr()
214da09e106SDimitry Andric ///     br merge_bb
215da09e106SDimitry Andric ///
216da09e106SDimitry Andric ///   else_bb:
217da09e106SDimitry Andric ///     ; The original call instruction is moved to the "else" block.
218da09e106SDimitry Andric ///     %t0 = call i32 %ptr()
219da09e106SDimitry Andric ///     br merge_bb
220da09e106SDimitry Andric ///
221da09e106SDimitry Andric ///   merge_bb:
222da09e106SDimitry Andric ///     ; Uses of the original call instruction are replaced by uses of the phi
223da09e106SDimitry Andric ///     ; node.
224da09e106SDimitry Andric ///     %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
225da09e106SDimitry Andric ///     ...
226da09e106SDimitry Andric ///
227da09e106SDimitry Andric /// A similar transformation is performed for invoke instructions. However,
228da09e106SDimitry Andric /// since invokes are terminating, more work is required. For example, the
229da09e106SDimitry Andric /// invoke instruction below:
230da09e106SDimitry Andric ///
231da09e106SDimitry Andric ///   orig_bb:
232da09e106SDimitry Andric ///     %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
233da09e106SDimitry Andric ///
234da09e106SDimitry Andric /// Is replace by the following:
235da09e106SDimitry Andric ///
236da09e106SDimitry Andric ///   orig_bb:
237da09e106SDimitry Andric ///     %cond = icmp eq i32 ()* %ptr, @func
238da09e106SDimitry Andric ///     br i1 %cond, %then_bb, %else_bb
239da09e106SDimitry Andric ///
240da09e106SDimitry Andric ///   then_bb:
241da09e106SDimitry Andric ///     ; The clone of the original invoke instruction is placed in the "then"
242da09e106SDimitry Andric ///     ; block, and its normal destination is set to the "merge" block. It is
243da09e106SDimitry Andric ///     ; not yet promoted.
244da09e106SDimitry Andric ///     %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
245da09e106SDimitry Andric ///
246da09e106SDimitry Andric ///   else_bb:
247da09e106SDimitry Andric ///     ; The original invoke instruction is moved into the "else" block, and
248da09e106SDimitry Andric ///     ; its normal destination is set to the "merge" block.
249da09e106SDimitry Andric ///     %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
250da09e106SDimitry Andric ///
251da09e106SDimitry Andric ///   merge_bb:
252da09e106SDimitry Andric ///     ; Uses of the original invoke instruction are replaced by uses of the
253da09e106SDimitry Andric ///     ; phi node, and the merge block branches to the normal destination.
254da09e106SDimitry Andric ///     %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
255da09e106SDimitry Andric ///     br %normal_dst
256da09e106SDimitry Andric ///
versionCallSite(CallSite CS,Value * Callee,MDNode * BranchWeights)2572cab237bSDimitry Andric static Instruction *versionCallSite(CallSite CS, Value *Callee,
258da09e106SDimitry Andric                                     MDNode *BranchWeights) {
2592cab237bSDimitry Andric 
2602cab237bSDimitry Andric   IRBuilder<> Builder(CS.getInstruction());
2612cab237bSDimitry Andric   Instruction *OrigInst = CS.getInstruction();
262da09e106SDimitry Andric   BasicBlock *OrigBlock = OrigInst->getParent();
2632cab237bSDimitry Andric 
2642cab237bSDimitry Andric   // Create the compare. The called value and callee must have the same type to
2652cab237bSDimitry Andric   // be compared.
266da09e106SDimitry Andric   if (CS.getCalledValue()->getType() != Callee->getType())
267da09e106SDimitry Andric     Callee = Builder.CreateBitCast(Callee, CS.getCalledValue()->getType());
268da09e106SDimitry Andric   auto *Cond = Builder.CreateICmpEQ(CS.getCalledValue(), Callee);
2692cab237bSDimitry Andric 
2702cab237bSDimitry Andric   // Create an if-then-else structure. The original instruction is moved into
2712cab237bSDimitry Andric   // the "else" block, and a clone of the original instruction is placed in the
2722cab237bSDimitry Andric   // "then" block.
273*b5893f02SDimitry Andric   Instruction *ThenTerm = nullptr;
274*b5893f02SDimitry Andric   Instruction *ElseTerm = nullptr;
2752cab237bSDimitry Andric   SplitBlockAndInsertIfThenElse(Cond, CS.getInstruction(), &ThenTerm, &ElseTerm,
2762cab237bSDimitry Andric                                 BranchWeights);
277da09e106SDimitry Andric   BasicBlock *ThenBlock = ThenTerm->getParent();
278da09e106SDimitry Andric   BasicBlock *ElseBlock = ElseTerm->getParent();
279da09e106SDimitry Andric   BasicBlock *MergeBlock = OrigInst->getParent();
2802cab237bSDimitry Andric 
2812cab237bSDimitry Andric   ThenBlock->setName("if.true.direct_targ");
2822cab237bSDimitry Andric   ElseBlock->setName("if.false.orig_indirect");
2832cab237bSDimitry Andric   MergeBlock->setName("if.end.icp");
2842cab237bSDimitry Andric 
2852cab237bSDimitry Andric   Instruction *NewInst = OrigInst->clone();
2862cab237bSDimitry Andric   OrigInst->moveBefore(ElseTerm);
2872cab237bSDimitry Andric   NewInst->insertBefore(ThenTerm);
2882cab237bSDimitry Andric 
2892cab237bSDimitry Andric   // If the original call site is an invoke instruction, we have extra work to
290da09e106SDimitry Andric   // do since invoke instructions are terminating. We have to fix-up phi nodes
291da09e106SDimitry Andric   // in the invoke's normal and unwind destinations.
2922cab237bSDimitry Andric   if (auto *OrigInvoke = dyn_cast<InvokeInst>(OrigInst)) {
2932cab237bSDimitry Andric     auto *NewInvoke = cast<InvokeInst>(NewInst);
2942cab237bSDimitry Andric 
2952cab237bSDimitry Andric     // Invoke instructions are terminating, so we don't need the terminator
2962cab237bSDimitry Andric     // instructions that were just created.
2972cab237bSDimitry Andric     ThenTerm->eraseFromParent();
2982cab237bSDimitry Andric     ElseTerm->eraseFromParent();
2992cab237bSDimitry Andric 
3002cab237bSDimitry Andric     // Branch from the "merge" block to the original normal destination.
3012cab237bSDimitry Andric     Builder.SetInsertPoint(MergeBlock);
3022cab237bSDimitry Andric     Builder.CreateBr(OrigInvoke->getNormalDest());
3032cab237bSDimitry Andric 
304da09e106SDimitry Andric     // Fix-up phi nodes in the original invoke's normal and unwind destinations.
305da09e106SDimitry Andric     fixupPHINodeForNormalDest(OrigInvoke, OrigBlock, MergeBlock);
306da09e106SDimitry Andric     fixupPHINodeForUnwindDest(OrigInvoke, MergeBlock, ThenBlock, ElseBlock);
307da09e106SDimitry Andric 
308da09e106SDimitry Andric     // Now set the normal destinations of the invoke instructions to be the
3092cab237bSDimitry Andric     // "merge" block.
310da09e106SDimitry Andric     OrigInvoke->setNormalDest(MergeBlock);
3112cab237bSDimitry Andric     NewInvoke->setNormalDest(MergeBlock);
3122cab237bSDimitry Andric   }
3132cab237bSDimitry Andric 
314da09e106SDimitry Andric   // Create a phi node for the returned value of the call site.
315da09e106SDimitry Andric   createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
316da09e106SDimitry Andric 
3172cab237bSDimitry Andric   return NewInst;
3182cab237bSDimitry Andric }
3192cab237bSDimitry Andric 
isLegalToPromote(CallSite CS,Function * Callee,const char ** FailureReason)3202cab237bSDimitry Andric bool llvm::isLegalToPromote(CallSite CS, Function *Callee,
3212cab237bSDimitry Andric                             const char **FailureReason) {
3222cab237bSDimitry Andric   assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
3232cab237bSDimitry Andric 
324*b5893f02SDimitry Andric   auto &DL = Callee->getParent()->getDataLayout();
325*b5893f02SDimitry Andric 
3262cab237bSDimitry Andric   // Check the return type. The callee's return value type must be bitcast
3272cab237bSDimitry Andric   // compatible with the call site's type.
3282cab237bSDimitry Andric   Type *CallRetTy = CS.getInstruction()->getType();
3292cab237bSDimitry Andric   Type *FuncRetTy = Callee->getReturnType();
3302cab237bSDimitry Andric   if (CallRetTy != FuncRetTy)
331*b5893f02SDimitry Andric     if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy, CallRetTy, DL)) {
3322cab237bSDimitry Andric       if (FailureReason)
3332cab237bSDimitry Andric         *FailureReason = "Return type mismatch";
3342cab237bSDimitry Andric       return false;
3352cab237bSDimitry Andric     }
3362cab237bSDimitry Andric 
3372cab237bSDimitry Andric   // The number of formal arguments of the callee.
3382cab237bSDimitry Andric   unsigned NumParams = Callee->getFunctionType()->getNumParams();
3392cab237bSDimitry Andric 
3402cab237bSDimitry Andric   // Check the number of arguments. The callee and call site must agree on the
3412cab237bSDimitry Andric   // number of arguments.
3422cab237bSDimitry Andric   if (CS.arg_size() != NumParams && !Callee->isVarArg()) {
3432cab237bSDimitry Andric     if (FailureReason)
3442cab237bSDimitry Andric       *FailureReason = "The number of arguments mismatch";
3452cab237bSDimitry Andric     return false;
3462cab237bSDimitry Andric   }
3472cab237bSDimitry Andric 
3482cab237bSDimitry Andric   // Check the argument types. The callee's formal argument types must be
3492cab237bSDimitry Andric   // bitcast compatible with the corresponding actual argument types of the call
3502cab237bSDimitry Andric   // site.
3512cab237bSDimitry Andric   for (unsigned I = 0; I < NumParams; ++I) {
3522cab237bSDimitry Andric     Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I);
3532cab237bSDimitry Andric     Type *ActualTy = CS.getArgument(I)->getType();
3542cab237bSDimitry Andric     if (FormalTy == ActualTy)
3552cab237bSDimitry Andric       continue;
356*b5893f02SDimitry Andric     if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) {
3572cab237bSDimitry Andric       if (FailureReason)
3582cab237bSDimitry Andric         *FailureReason = "Argument type mismatch";
3592cab237bSDimitry Andric       return false;
3602cab237bSDimitry Andric     }
3612cab237bSDimitry Andric   }
3622cab237bSDimitry Andric 
3632cab237bSDimitry Andric   return true;
3642cab237bSDimitry Andric }
3652cab237bSDimitry Andric 
promoteCall(CallSite CS,Function * Callee,CastInst ** RetBitCast)366da09e106SDimitry Andric Instruction *llvm::promoteCall(CallSite CS, Function *Callee,
367da09e106SDimitry Andric                                CastInst **RetBitCast) {
3682cab237bSDimitry Andric   assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
3692cab237bSDimitry Andric 
3702cab237bSDimitry Andric   // Set the called function of the call site to be the given callee.
3712cab237bSDimitry Andric   CS.setCalledFunction(Callee);
3722cab237bSDimitry Andric 
3732cab237bSDimitry Andric   // Since the call site will no longer be direct, we must clear metadata that
3742cab237bSDimitry Andric   // is only appropriate for indirect calls. This includes !prof and !callees
3752cab237bSDimitry Andric   // metadata.
3762cab237bSDimitry Andric   CS.getInstruction()->setMetadata(LLVMContext::MD_prof, nullptr);
3772cab237bSDimitry Andric   CS.getInstruction()->setMetadata(LLVMContext::MD_callees, nullptr);
3782cab237bSDimitry Andric 
3792cab237bSDimitry Andric   // If the function type of the call site matches that of the callee, no
3802cab237bSDimitry Andric   // additional work is required.
3812cab237bSDimitry Andric   if (CS.getFunctionType() == Callee->getFunctionType())
382da09e106SDimitry Andric     return CS.getInstruction();
3832cab237bSDimitry Andric 
3842cab237bSDimitry Andric   // Save the return types of the call site and callee.
3852cab237bSDimitry Andric   Type *CallSiteRetTy = CS.getInstruction()->getType();
3862cab237bSDimitry Andric   Type *CalleeRetTy = Callee->getReturnType();
3872cab237bSDimitry Andric 
3882cab237bSDimitry Andric   // Change the function type of the call site the match that of the callee.
3892cab237bSDimitry Andric   CS.mutateFunctionType(Callee->getFunctionType());
3902cab237bSDimitry Andric 
3912cab237bSDimitry Andric   // Inspect the arguments of the call site. If an argument's type doesn't
3922cab237bSDimitry Andric   // match the corresponding formal argument's type in the callee, bitcast it
3932cab237bSDimitry Andric   // to the correct type.
3944ba319b5SDimitry Andric   auto CalleeType = Callee->getFunctionType();
3954ba319b5SDimitry Andric   auto CalleeParamNum = CalleeType->getNumParams();
396*b5893f02SDimitry Andric 
397*b5893f02SDimitry Andric   LLVMContext &Ctx = Callee->getContext();
398*b5893f02SDimitry Andric   const AttributeList &CallerPAL = CS.getAttributes();
399*b5893f02SDimitry Andric   // The new list of argument attributes.
400*b5893f02SDimitry Andric   SmallVector<AttributeSet, 4> NewArgAttrs;
401*b5893f02SDimitry Andric   bool AttributeChanged = false;
402*b5893f02SDimitry Andric 
4034ba319b5SDimitry Andric   for (unsigned ArgNo = 0; ArgNo < CalleeParamNum; ++ArgNo) {
4044ba319b5SDimitry Andric     auto *Arg = CS.getArgument(ArgNo);
4054ba319b5SDimitry Andric     Type *FormalTy = CalleeType->getParamType(ArgNo);
4064ba319b5SDimitry Andric     Type *ActualTy = Arg->getType();
4072cab237bSDimitry Andric     if (FormalTy != ActualTy) {
408*b5893f02SDimitry Andric       auto *Cast = CastInst::CreateBitOrPointerCast(Arg, FormalTy, "",
4092cab237bSDimitry Andric                                                     CS.getInstruction());
4102cab237bSDimitry Andric       CS.setArgument(ArgNo, Cast);
411*b5893f02SDimitry Andric 
412*b5893f02SDimitry Andric       // Remove any incompatible attributes for the argument.
413*b5893f02SDimitry Andric       AttrBuilder ArgAttrs(CallerPAL.getParamAttributes(ArgNo));
414*b5893f02SDimitry Andric       ArgAttrs.remove(AttributeFuncs::typeIncompatible(FormalTy));
415*b5893f02SDimitry Andric       NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs));
416*b5893f02SDimitry Andric       AttributeChanged = true;
417*b5893f02SDimitry Andric     } else
418*b5893f02SDimitry Andric       NewArgAttrs.push_back(CallerPAL.getParamAttributes(ArgNo));
4192cab237bSDimitry Andric   }
4202cab237bSDimitry Andric 
4212cab237bSDimitry Andric   // If the return type of the call site doesn't match that of the callee, cast
4222cab237bSDimitry Andric   // the returned value to the appropriate type.
423*b5893f02SDimitry Andric   // Remove any incompatible return value attribute.
424*b5893f02SDimitry Andric   AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
425*b5893f02SDimitry Andric   if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy) {
426da09e106SDimitry Andric     createRetBitCast(CS, CallSiteRetTy, RetBitCast);
427*b5893f02SDimitry Andric     RAttrs.remove(AttributeFuncs::typeIncompatible(CalleeRetTy));
428*b5893f02SDimitry Andric     AttributeChanged = true;
429*b5893f02SDimitry Andric   }
430*b5893f02SDimitry Andric 
431*b5893f02SDimitry Andric   // Set the new callsite attribute.
432*b5893f02SDimitry Andric   if (AttributeChanged)
433*b5893f02SDimitry Andric     CS.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttributes(),
434*b5893f02SDimitry Andric                                         AttributeSet::get(Ctx, RAttrs),
435*b5893f02SDimitry Andric                                         NewArgAttrs));
436da09e106SDimitry Andric 
437da09e106SDimitry Andric   return CS.getInstruction();
4382cab237bSDimitry Andric }
4392cab237bSDimitry Andric 
promoteCallWithIfThenElse(CallSite CS,Function * Callee,MDNode * BranchWeights)4402cab237bSDimitry Andric Instruction *llvm::promoteCallWithIfThenElse(CallSite CS, Function *Callee,
4412cab237bSDimitry Andric                                              MDNode *BranchWeights) {
4422cab237bSDimitry Andric 
4432cab237bSDimitry Andric   // Version the indirect call site. If the called value is equal to the given
4442cab237bSDimitry Andric   // callee, 'NewInst' will be executed, otherwise the original call site will
4452cab237bSDimitry Andric   // be executed.
446da09e106SDimitry Andric   Instruction *NewInst = versionCallSite(CS, Callee, BranchWeights);
4472cab237bSDimitry Andric 
4482cab237bSDimitry Andric   // Promote 'NewInst' so that it directly calls the desired function.
449da09e106SDimitry Andric   return promoteCall(CallSite(NewInst), Callee);
4502cab237bSDimitry Andric }
4512cab237bSDimitry Andric 
4522cab237bSDimitry Andric #undef DEBUG_TYPE
453