blob: e58ddcf34667d5bf6be9cab699d216885c5f1162 [file] [log] [blame]
Matthew Simpsone363d2c2017-12-06 21:22:54 +00001//===- CallPromotionUtils.cpp - Utilities for call promotion ----*- C++ -*-===//
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 file implements utilities useful for promoting indirect call sites to
11// direct call sites.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/CallPromotionUtils.h"
16#include "llvm/IR/IRBuilder.h"
17#include "llvm/Transforms/Utils/BasicBlockUtils.h"
18
19using namespace llvm;
20
21#define DEBUG_TYPE "call-promotion-utils"
22
23/// Fix-up phi nodes in an invoke instruction's normal destination.
24///
25/// After versioning an invoke instruction, values coming from the original
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000026/// block will now be coming from the "merge" block. For example, in the code
27/// below:
28///
29/// then_bb:
30/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
31///
32/// else_bb:
33/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
34///
35/// merge_bb:
36/// %t2 = phi i32 [ %t0, %then_bb ], [ %t1, %else_bb ]
37/// br %normal_dst
38///
39/// normal_dst:
40/// %t3 = phi i32 [ %x, %orig_bb ], ...
41///
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":
44///
45/// normal_dst:
46/// %t3 = phi i32 [ %x, %merge_bb ], ...
47///
Matthew Simpsone363d2c2017-12-06 21:22:54 +000048static void fixupPHINodeForNormalDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000049 BasicBlock *MergeBlock) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000050 for (PHINode &Phi : Invoke->getNormalDest()->phis()) {
51 int Idx = Phi.getBasicBlockIndex(OrigBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000052 if (Idx == -1)
53 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000054 Phi.setIncomingBlock(Idx, MergeBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000055 }
56}
57
58/// Fix-up phi nodes in an invoke instruction's unwind destination.
59///
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.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000062/// For example, in the code below:
63///
64/// then_bb:
65/// %t0 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
66///
67/// else_bb:
68/// %t1 = invoke i32 %ptr() to label %merge_bb unwind label %unwind_dst
69///
70/// unwind_dst:
71/// %t3 = phi i32 [ %x, %orig_bb ], ...
72///
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":
75///
76/// unwind_dst:
77/// %t3 = phi i32 [ %x, %then_bb ], [ %x, %else_bb ], ...
78///
Matthew Simpsone363d2c2017-12-06 21:22:54 +000079static void fixupPHINodeForUnwindDest(InvokeInst *Invoke, BasicBlock *OrigBlock,
80 BasicBlock *ThenBlock,
81 BasicBlock *ElseBlock) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000082 for (PHINode &Phi : Invoke->getUnwindDest()->phis()) {
83 int Idx = Phi.getBasicBlockIndex(OrigBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000084 if (Idx == -1)
85 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000086 auto *V = Phi.getIncomingValue(Idx);
87 Phi.setIncomingBlock(Idx, ThenBlock);
88 Phi.addIncoming(V, ElseBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +000089 }
90}
91
Matthew Simpsone363d2c2017-12-06 21:22:54 +000092/// Create a phi node for the returned value of a call or invoke instruction.
93///
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
97/// phi node.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +000098///
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:
101///
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 ],
104///
105static void createRetPHINode(Instruction *OrigInst, Instruction *NewInst,
106 BasicBlock *MergeBlock, IRBuilder<> &Builder) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000107
108 if (OrigInst->getType()->isVoidTy() || OrigInst->use_empty())
109 return;
110
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000111 Builder.SetInsertPoint(&MergeBlock->front());
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000112 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());
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000119 Phi->addIncoming(NewInst, NewInst->getParent());
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000120}
121
122/// Cast a call or invoke instruction to the given type.
123///
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.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000128///
129/// For example, if the call instruction below requires a bitcast after
130/// promotion:
131///
132/// orig_bb:
133/// %t0 = call i32 @func()
134/// ...
135///
136/// The bitcast is placed after the call instruction:
137///
138/// orig_bb:
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 ...
142/// ...
143///
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:
147///
148/// orig_bb:
149/// %t0 = invoke i32 @func() to label %normal_dst unwind label %unwind_dst
150///
151/// The edge between the original block and the invoke's normal destination is
152/// split, and the bitcast is placed there:
153///
154/// orig_bb:
155/// %t0 = invoke i32 @func() to label %split_bb unwind label %unwind_dst
156///
157/// split_bb:
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
161///
162static void createRetBitCast(CallSite CS, Type *RetTy, CastInst **RetBitCast) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000163
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);
169
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()))
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000174 InsertBefore =
175 &SplitEdge(Invoke->getParent(), Invoke->getNormalDest())->front();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000176 else
177 InsertBefore = &*std::next(CS.getInstruction()->getIterator());
178
179 // Bitcast the return value to the correct type.
Scott Linder3759efc2018-10-10 16:35:47 +0000180 auto *Cast = CastInst::CreateBitOrPointerCast(CS.getInstruction(), RetTy, "",
181 InsertBefore);
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000182 if (RetBitCast)
183 *RetBitCast = Cast;
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000184
185 // Replace all the original uses of the calling instruction with the bitcast.
186 for (User *U : UsersToUpdate)
187 U->replaceUsesOfWith(CS.getInstruction(), Cast);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000188}
189
190/// Predicate and clone the given call site.
191///
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
196/// returned.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000197///
198/// For example, the call instruction below:
199///
200/// orig_bb:
201/// %t0 = call i32 %ptr()
202/// ...
203///
204/// Is replace by the following:
205///
206/// orig_bb:
207/// %cond = icmp eq i32 ()* %ptr, @func
208/// br i1 %cond, %then_bb, %else_bb
209///
210/// then_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()
214/// br merge_bb
215///
216/// else_bb:
217/// ; The original call instruction is moved to the "else" block.
218/// %t0 = call i32 %ptr()
219/// br merge_bb
220///
221/// merge_bb:
222/// ; Uses of the original call instruction are replaced by uses of the phi
223/// ; node.
224/// %t2 = phi i32 [ %t0, %else_bb ], [ %t1, %then_bb ]
225/// ...
226///
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:
230///
231/// orig_bb:
232/// %t0 = invoke %ptr() to label %normal_dst unwind label %unwind_dst
233///
234/// Is replace by the following:
235///
236/// orig_bb:
237/// %cond = icmp eq i32 ()* %ptr, @func
238/// br i1 %cond, %then_bb, %else_bb
239///
240/// then_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
245///
246/// else_bb:
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
250///
251/// merge_bb:
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 ]
255/// br %normal_dst
256///
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000257static Instruction *versionCallSite(CallSite CS, Value *Callee,
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000258 MDNode *BranchWeights) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000259
260 IRBuilder<> Builder(CS.getInstruction());
261 Instruction *OrigInst = CS.getInstruction();
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000262 BasicBlock *OrigBlock = OrigInst->getParent();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000263
264 // Create the compare. The called value and callee must have the same type to
265 // be compared.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000266 if (CS.getCalledValue()->getType() != Callee->getType())
267 Callee = Builder.CreateBitCast(Callee, CS.getCalledValue()->getType());
268 auto *Cond = Builder.CreateICmpEQ(CS.getCalledValue(), Callee);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000269
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
272 // "then" block.
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000273 Instruction *ThenTerm = nullptr;
274 Instruction *ElseTerm = nullptr;
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000275 SplitBlockAndInsertIfThenElse(Cond, CS.getInstruction(), &ThenTerm, &ElseTerm,
276 BranchWeights);
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000277 BasicBlock *ThenBlock = ThenTerm->getParent();
278 BasicBlock *ElseBlock = ElseTerm->getParent();
279 BasicBlock *MergeBlock = OrigInst->getParent();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000280
281 ThenBlock->setName("if.true.direct_targ");
282 ElseBlock->setName("if.false.orig_indirect");
283 MergeBlock->setName("if.end.icp");
284
285 Instruction *NewInst = 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
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000290 // do since invoke instructions are terminating. We have to fix-up phi nodes
291 // in the invoke's normal and unwind destinations.
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000292 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
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000304 // 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
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000309 // "merge" block.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000310 OrigInvoke->setNormalDest(MergeBlock);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000311 NewInvoke->setNormalDest(MergeBlock);
312 }
313
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000314 // Create a phi node for the returned value of the call site.
315 createRetPHINode(OrigInst, NewInst, MergeBlock, Builder);
316
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000317 return NewInst;
318}
319
320bool llvm::isLegalToPromote(CallSite CS, Function *Callee,
321 const char **FailureReason) {
322 assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
323
Scott Linder3759efc2018-10-10 16:35:47 +0000324 auto &DL = Callee->getParent()->getDataLayout();
325
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000326 // Check the return type. The callee's return value type must be bitcast
327 // compatible with the call site's type.
328 Type *CallRetTy = CS.getInstruction()->getType();
329 Type *FuncRetTy = Callee->getReturnType();
330 if (CallRetTy != FuncRetTy)
Scott Linder3759efc2018-10-10 16:35:47 +0000331 if (!CastInst::isBitOrNoopPointerCastable(FuncRetTy, CallRetTy, DL)) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000332 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 (CS.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 = CS.getArgument(I)->getType();
354 if (FormalTy == ActualTy)
355 continue;
Scott Linder3759efc2018-10-10 16:35:47 +0000356 if (!CastInst::isBitOrNoopPointerCastable(ActualTy, FormalTy, DL)) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000357 if (FailureReason)
358 *FailureReason = "Argument type mismatch";
359 return false;
360 }
361 }
362
363 return true;
364}
365
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000366Instruction *llvm::promoteCall(CallSite CS, Function *Callee,
367 CastInst **RetBitCast) {
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000368 assert(!CS.getCalledFunction() && "Only indirect call sites can be promoted");
369
370 // Set the called function of the call site to be the given callee.
371 CS.setCalledFunction(Callee);
372
373 // Since the call site will no longer be direct, we must clear metadata that
374 // is only appropriate for indirect calls. This includes !prof and !callees
375 // metadata.
376 CS.getInstruction()->setMetadata(LLVMContext::MD_prof, nullptr);
377 CS.getInstruction()->setMetadata(LLVMContext::MD_callees, nullptr);
378
379 // If the function type of the call site matches that of the callee, no
380 // additional work is required.
381 if (CS.getFunctionType() == Callee->getFunctionType())
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000382 return CS.getInstruction();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000383
384 // Save the return types of the call site and callee.
385 Type *CallSiteRetTy = CS.getInstruction()->getType();
386 Type *CalleeRetTy = Callee->getReturnType();
387
388 // Change the function type of the call site the match that of the callee.
389 CS.mutateFunctionType(Callee->getFunctionType());
390
391 // Inspect the arguments of the call site. If an argument's type doesn't
392 // match the corresponding formal argument's type in the callee, bitcast it
393 // to the correct type.
Taewook Oh923c2162018-04-25 17:19:21 +0000394 auto CalleeType = Callee->getFunctionType();
395 auto CalleeParamNum = CalleeType->getNumParams();
Xin Tong04d49772018-11-26 22:03:52 +0000396
397 LLVMContext &Ctx = Callee->getContext();
398 const AttributeList &CallerPAL = CS.getAttributes();
399 // The new list of argument attributes.
400 SmallVector<AttributeSet, 4> NewArgAttrs;
401 bool AttributeChanged = false;
402
Taewook Oh923c2162018-04-25 17:19:21 +0000403 for (unsigned ArgNo = 0; ArgNo < CalleeParamNum; ++ArgNo) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000404 auto *Arg = CS.getArgument(ArgNo);
Taewook Oh923c2162018-04-25 17:19:21 +0000405 Type *FormalTy = CalleeType->getParamType(ArgNo);
406 Type *ActualTy = Arg->getType();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000407 if (FormalTy != ActualTy) {
Scott Linder3759efc2018-10-10 16:35:47 +0000408 auto *Cast = CastInst::CreateBitOrPointerCast(Arg, FormalTy, "",
409 CS.getInstruction());
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000410 CS.setArgument(ArgNo, Cast);
Xin Tong04d49772018-11-26 22:03:52 +0000411
412 // Remove any incompatible attributes for the argument.
413 AttrBuilder ArgAttrs(CallerPAL.getParamAttributes(ArgNo));
414 ArgAttrs.remove(AttributeFuncs::typeIncompatible(FormalTy));
415 NewArgAttrs.push_back(AttributeSet::get(Ctx, ArgAttrs));
416 AttributeChanged = true;
417 } else
418 NewArgAttrs.push_back(CallerPAL.getParamAttributes(ArgNo));
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000419 }
420
421 // If the return type of the call site doesn't match that of the callee, cast
422 // the returned value to the appropriate type.
Xin Tong04d49772018-11-26 22:03:52 +0000423 // Remove any incompatible return value attribute.
424 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
425 if (!CallSiteRetTy->isVoidTy() && CallSiteRetTy != CalleeRetTy) {
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000426 createRetBitCast(CS, CallSiteRetTy, RetBitCast);
Xin Tong04d49772018-11-26 22:03:52 +0000427 RAttrs.remove(AttributeFuncs::typeIncompatible(CalleeRetTy));
428 AttributeChanged = true;
429 }
430
431 // Set the new callsite attribute.
432 if (AttributeChanged)
433 CS.setAttributes(AttributeList::get(Ctx, CallerPAL.getFnAttributes(),
434 AttributeSet::get(Ctx, RAttrs),
435 NewArgAttrs));
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000436
437 return CS.getInstruction();
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000438}
439
440Instruction *llvm::promoteCallWithIfThenElse(CallSite CS, Function *Callee,
441 MDNode *BranchWeights) {
442
443 // Version the indirect call site. If the called value is equal to the given
444 // callee, 'NewInst' will be executed, otherwise the original call site will
445 // be executed.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000446 Instruction *NewInst = versionCallSite(CS, Callee, BranchWeights);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000447
448 // Promote 'NewInst' so that it directly calls the desired function.
Matthew Simpsoncb35c5d2017-12-20 19:26:37 +0000449 return promoteCall(CallSite(NewInst), Callee);
Matthew Simpsone363d2c2017-12-06 21:22:54 +0000450}
451
452#undef DEBUG_TYPE