1 //===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements utilities useful for promoting indirect call sites to
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
16 #include "llvm/IR/IRBuilder.h"
17 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #define DEBUG_TYPE "call-promotion-utils"
23 /// Fix-up phi nodes in an invoke instruction's normal destination.
25 /// After versioning an invoke instruction, values coming from the original
26 /// block will now be coming from the "merge" block. For example, in the code
30 /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
33 /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
36 /// %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
40 /// %t3 = phi i32 [ %x, %orig_bb ], ...
42 /// "orig_bb" is no longer a predecessor of "normal_dst", so the phi nodes in
43 /// "normal_dst" must be fixed to refer to "merge_bb":
46 /// %t3 = phi i32 [ %x, %merge_bb ], ...
48 static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
49 BasicBlock *MergeBlock) {
50 for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
51 int Idx = Phi.getBasicBlockIndex(OrigBlock);
54 Phi.setIncomingBlock(Idx, MergeBlock);
58 /// Fix-up phi nodes in an invoke instruction's unwind destination.
60 /// After versioning an invoke instruction, values coming from the original
61 /// block will now be coming from either the "then" block or the "else" block.
62 /// For example, in the code below:
65 /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
68 /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
71 /// %t3 = phi i32 [ %x, %orig_bb ], ...
73 /// "orig_bb" is no longer a predecessor of "unwind_dst", so the phi nodes in
74 /// "unwind_dst" must be fixed to refer to "then_bb" and "else_bb":
77 /// %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
79 static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
80 BasicBlock *ThenBlock,
81 BasicBlock *ElseBlock) {
82 for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
83 int Idx = Phi.getBasicBlockIndex(OrigBlock);
86 auto *V = Phi.getIncomingValue(Idx);
87 Phi.setIncomingBlock(Idx, ThenBlock);
88 Phi.addIncoming(V, ElseBlock);
92 /// Create a phi node for the returned value of a call or invoke instruction.
94 /// After versioning a call or invoke instruction that returns a value, we have
95 /// to merge the value of the original and new instructions. We do this by
96 /// creating a phi node and replacing uses of the original instruction with this
99 /// For example, if \p OrigInst is defined in "else_bb" and \p NewInst is
100 /// defined in "then_bb", we create the following phi node:
102 /// ; Uses of the original instruction are replaced by uses of the phi node.
103 /// %t0 = phi i32 [ %orig_inst, %else_bb ], [ %new_inst, %then_bb ],
105 static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
106 BasicBlock *MergeBlock, IRBuilder<> &Builder) {
108 if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
111 Builder.SetInsertPoint(&MergeBlock->front());
112 PHINode *Phi = Builder.CreatePHI(OrigInst->getType(), 0);
113 SmallVector<User *, 16> UsersToUpdate;
114 for (User *U : OrigInst->users())
115 UsersToUpdate.push_back(U);
116 for (User *U : UsersToUpdate)
117 U->replaceUsesOfWith(OrigInst, Phi);
118 Phi->addIncoming(OrigInst, OrigInst->getParent());
119 Phi->addIncoming(NewInst, NewInst->getParent());
122 /// Cast a call or invoke instruction to the given type.
124 /// When promoting a call site, the return type of the call site might not match
125 /// that of the callee. If this is the case, we have to cast the returned value
126 /// to the correct type. The location of the cast depends on if we have a call
127 /// or invoke instruction.
129 /// For example, if the call instruction below requires a bitcast after
133 /// %t0 = call i32 @func()
136 /// The bitcast is placed after the call instruction:
139 /// ; Uses of the original return value are replaced by uses of the bitcast.
140 /// %t0 = call i32 @func()
141 /// %t1 = bitcast i32 %t0 to ...
144 /// A similar transformation is performed for invoke instructions. However,
145 /// since invokes are terminating, a new block is created for the bitcast. For
146 /// example, if the invoke instruction below requires a bitcast after promotion:
149 /// %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
151 /// The edge between the original block and the invoke's normal destination is
152 /// split, and the bitcast is placed there:
155 /// %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
158 /// ; Uses of the original return value are replaced by uses of the bitcast.
159 /// %t1 = bitcast i32 %t0 to ...
160 /// br label %normal_dst
162 static void createRetBitCast(CallSite CS, Type *RetTy, CastInst **RetBitCast) {
164 // Save the users of the calling instruction. These uses will be changed to
165 // use the bitcast after we create it.
166 SmallVector<User *, 16> UsersToUpdate;
167 for (User *U : CS.getInstruction()->users())
168 UsersToUpdate.push_back(U);
170 // Determine an appropriate location to create the bitcast for the return
171 // value. The location depends on if we have a call or invoke instruction.
172 Instruction *InsertBefore = nullptr;
173 if (auto *Invoke = dyn_cast<InvokeInst>(CS.getInstruction()))
175 &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front();
177 InsertBefore = &*std::next(CS.getInstruction()->getIterator());
179 // Bitcast the return value to the correct type.
180 auto *Cast = CastInst::Create(Instruction::BitCast, CS.getInstruction(),
181 RetTy, "", InsertBefore);
185 // Replace all the original uses of the calling instruction with the bitcast.
186 for (User *U : UsersToUpdate)
187 U->replaceUsesOfWith(CS.getInstruction(), Cast);
190 /// Predicate and clone the given call site.
192 /// This function creates an if-then-else structure at the location of the call
193 /// site. The "if" condition compares the call site's called value to the given
194 /// callee. The original call site is moved into the "else" block, and a clone
195 /// of the call site is placed in the "then" block. The cloned instruction is
198 /// For example, the call instruction below:
201 /// %t0 = call i32 %ptr()
204 /// Is replace by the following:
207 /// %cond = icmp eq i32 ()* %ptr, @func
208 /// br i1 %cond, %then_bb, %else_bb
211 /// ; The clone of the original call instruction is placed in the "then"
212 /// ; block. It is not yet promoted.
213 /// %t1 = call i32 %ptr()
217 /// ; The original call instruction is moved to the "else" block.
218 /// %t0 = call i32 %ptr()
222 /// ; Uses of the original call instruction are replaced by uses of the phi
224 /// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
227 /// A similar transformation is performed for invoke instructions. However,
228 /// since invokes are terminating, more work is required. For example, the
229 /// invoke instruction below:
232 /// %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
234 /// Is replace by the following:
237 /// %cond = icmp eq i32 ()* %ptr, @func
238 /// br i1 %cond, %then_bb, %else_bb
241 /// ; The clone of the original invoke instruction is placed in the "then"
242 /// ; block, and its normal destination is set to the "merge" block. It is
243 /// ; not yet promoted.
244 /// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
247 /// ; The original invoke instruction is moved into the "else" block, and
248 /// ; its normal destination is set to the "merge" block.
249 /// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
252 /// ; Uses of the original invoke instruction are replaced by uses of the
253 /// ; phi node, and the merge block branches to the normal destination.
254 /// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
257 static Instruction *versionCallSite(CallSite CS, Value *Callee,
258 MDNode *BranchWeights) {
260 IRBuilder<> Builder(CS.getInstruction());
261 Instruction *OrigInst = CS.getInstruction();
262 BasicBlock *OrigBlock = OrigInst->getParent();
264 // Create the compare. The called value and callee must have the same type to
266 if (CS.getCalledValue()->getType() != Callee->getType())
267 Callee = Builder.CreateBitCast(Callee, CS.getCalledValue()->getType());
268 auto *Cond = Builder.CreateICmpEQ(CS.getCalledValue(), Callee);
270 // Create an if-then-else structure. The original instruction is moved into
271 // the "else" block, and a clone of the original instruction is placed in the
273 TerminatorInst *ThenTerm = nullptr;
274 TerminatorInst *ElseTerm = nullptr;
275 SplitBlockAndInsertIfThenElse(Cond, CS.getInstruction(), &ThenTerm, &ElseTerm,
277 BasicBlock *ThenBlock = ThenTerm->getParent();
278 BasicBlock *ElseBlock = ElseTerm->getParent();
279 BasicBlock *MergeBlock = OrigInst->getParent();
281 ThenBlock->setName("if.true.direct_targ");
282 ElseBlock->setName("if.false.orig_indirect");
283 MergeBlock->setName("if.end.icp");
285 Instruction *NewInst = OrigInst->clone();
286 OrigInst->moveBefore(ElseTerm);
287 NewInst->insertBefore(ThenTerm);
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);
295 // Invoke instructions are terminating, so we don't need the terminator
296 // instructions that were just created.
297 ThenTerm->eraseFromParent();
298 ElseTerm->eraseFromParent();
300 // Branch from the "merge" block to the original normal destination.
301 Builder.SetInsertPoint(MergeBlock);
302 Builder.CreateBr(OrigInvoke->getNormalDest());
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);
308 // Now set the normal destinations of the invoke instructions to be the
310 OrigInvoke->setNormalDest(MergeBlock);
311 NewInvoke->setNormalDest(MergeBlock);
314 // Create a phi node for the returned value of the call site.
315 createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
320 bool llvm::isLegalToPromote(CallSite CS, Function *Callee,
321 const char **FailureReason) {
322 assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
324 // Check the return type. The callee's return value type must be bitcast
325 // compatible with the call site's type.
326 Type *CallRetTy = CS.getInstruction()->getType();
327 Type *FuncRetTy = Callee->getReturnType();
328 if (CallRetTy != FuncRetTy)
329 if (!CastInst::isBitCastable(FuncRetTy, CallRetTy)) {
331 *FailureReason = "Return type mismatch";
335 // The number of formal arguments of the callee.
336 unsigned NumParams = Callee->getFunctionType()->getNumParams();
338 // Check the number of arguments. The callee and call site must agree on the
339 // number of arguments.
340 if (CS.arg_size() != NumParams && !Callee->isVarArg()) {
342 *FailureReason = "The number of arguments mismatch";
346 // Check the argument types. The callee's formal argument types must be
347 // bitcast compatible with the corresponding actual argument types of the call
349 for (unsigned I = 0; I < NumParams; ++I) {
350 Type *FormalTy = Callee->getFunctionType()->getFunctionParamType(I);
351 Type *ActualTy = CS.getArgument(I)->getType();
352 if (FormalTy == ActualTy)
354 if (!CastInst::isBitCastable(ActualTy, FormalTy)) {
356 *FailureReason = "Argument type mismatch";
364 Instruction *llvm::promoteCall(CallSite CS, Function *Callee,
365 CastInst **RetBitCast) {
366 assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
368 // Set the called function of the call site to be the given callee.
369 CS.setCalledFunction(Callee);
371 // Since the call site will no longer be direct, we must clear metadata that
372 // is only appropriate for indirect calls. This includes !prof and !callees
374 CS.getInstruction()->setMetadata(LLVMContext::MD_prof, nullptr);
375 CS.getInstruction()->setMetadata(LLVMContext::MD_callees, nullptr);
377 // If the function type of the call site matches that of the callee, no
378 // additional work is required.
379 if (CS.getFunctionType() == Callee->getFunctionType())
380 return CS.getInstruction();
382 // Save the return types of the call site and callee.
383 Type *CallSiteRetTy = CS.getInstruction()->getType();
384 Type *CalleeRetTy = Callee->getReturnType();
386 // Change the function type of the call site the match that of the callee.
387 CS.mutateFunctionType(Callee->getFunctionType());
389 // Inspect the arguments of the call site. If an argument's type doesn't
390 // match the corresponding formal argument's type in the callee, bitcast it
391 // to the correct type.
392 for (Use &U : CS.args()) {
393 unsigned ArgNo = CS.getArgumentNo(&U);
394 Type *FormalTy = Callee->getFunctionType()->getParamType(ArgNo);
395 Type *ActualTy = U.get()->getType();
396 if (FormalTy != ActualTy) {
397 auto *Cast = CastInst::Create(Instruction::BitCast, U.get(), FormalTy, "",
398 CS.getInstruction());
399 CS.setArgument(ArgNo, Cast);
403 // If the return type of the call site doesn't match that of the callee, cast
404 // the returned value to the appropriate type.
405 if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy)
406 createRetBitCast(CS, CallSiteRetTy, RetBitCast);
408 return CS.getInstruction();
411 Instruction *llvm::promoteCallWithIfThenElse(CallSite CS, Function *Callee,
412 MDNode *BranchWeights) {
414 // Version the indirect call site. If the called value is equal to the given
415 // callee, 'NewInst' will be executed, otherwise the original call site will
417 Instruction *NewInst = versionCallSite(CS, Callee, BranchWeights);
419 // Promote 'NewInst' so that it directly calls the desired function.
420 return promoteCall(CallSite(NewInst), Callee);